Reading text file stored in the raw folder through a user class

2

I have a test code that works fine. The function of the test is to read a text file that is in a res \ raw folder. It reads the text file smoothly and prints its contents line by line through Toast.

The functional code is as follows:

package com.example.teste;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //------------------------------------------------
        Button bt = (Button) this.findViewById(R.id.button1);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                InputStream ins = MainActivity.this.getResources().openRawResource(MainActivity.this.getResources().getIdentifier("raw/teste","raw", getPackageName()) );
                InputStreamReader inputreader = new InputStreamReader(ins);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;
            try {
                    while (( line = buffreader.readLine()) != null) {
        Toast.makeText(MainActivity.this, line, Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }//onClick
        });//bt.setOnClick
    }//onCreate
    //**********************************************************
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }//onCreateOptions

}//classe

My intention, however, is to make a reuse of the code, since in several parts of a future application I would enjoy reading several text files.

Then, you wanted to create a class so that after instantiating it, you read different files when you pass a method to the desired file name. I would then be interested in the location, opening, and reading part of the file.

So I created the class as follows:

 package com.example.teste;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import android.app.Activity;
    import android.content.Context;
    import android.widget.Toast;

    public class TestaLeituraArquivo extends Activity {
    Context gblContext;
//--------------------------construtor-----------------
    public TestaLeituraArquivo(Context context){
        this.gblContext=context;
    }//construtor
//---------------------------------método de leitura---------------------------
        public void leArquivo(String strCaminhoNomeArquivo){
                InputStream ins = gblContext.getResources().openRawResource(gblContext.getResources().getIdentifier(strCaminhoNomeArquivo,"raw", getPackageName()) );
            InputStreamReader inputreader = new InputStreamReader(ins);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line;
        try {
                while (( line = buffreader.readLine()) != null) {
    Toast.makeText(gblContext, line, Toast.LENGTH_SHORT).show();
                }
            } catch (IOException e) {
                Toast.makeText(gblContext, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }//leArquivo
    }//Classe

Once I have this class inside the same package, I will modify the initial code, the first one up there, so that I can take advantage of the created class:

 package com.example.teste;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //------------------------------------------------
            Button bt = (Button) this.findViewById(R.id.button1);
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    TestaLeituraArquivo tl = new TestaLeituraArquivo(MainActivity.this);
tl.leArquivo("raw/teste");
                }//onClick
            });//bt.setOnClick
        }//onCreate
        //**********************************************************
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }//onCreateOptions

    }//classe

That is, I just removed from the MainActivity, at the click of the button, all the code that worked on reading the file, and proceeded to the method of the created class, taking into account the Context pass that I called.

The problem I face is that the application 'crash' and Try / catch does not let me know anything.

The error log shows some errors, but nothing indicates the method itself. Talk about lack of communication with the google site, problems with the telephony part, etc.

Where am I making a mistake?

The error log is

02-13 10:44:19.512: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 10:45:36.953: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 10:51:17.559: E/SensorManager(2583): unregisterListener: com.android.phone.AccelerometerListener$1@47bcf058
02-13 10:51:17.750: E/LogsProvider(19112): onCreate()
02-13 10:51:18.109: E/RingtoneManager(2583): getRingtone : content://settings/system/ringtone, streamType : -1
02-13 10:51:18.121: E/RingtoneManager(2583): getActualDefaultRingtoneUri : content://media/internal/audio/media/13
02-13 10:51:18.121: E/RingtoneManager(2583): Uri.parse(uriString) : content://media/internal/audio/media/13
02-13 10:51:18.195: E/SettingsProvider(2486): openAssetFile uri: content://settings/system/ringtone, mode=r
02-13 10:51:18.195: E/SettingsProvider(2486): ringtoneType : 1
02-13 10:51:18.195: E/RingtoneManager(2486): getActualDefaultRingtoneUri : content://media/internal/audio/media/13
02-13 10:51:18.195: E/RingtoneManager(2486): Uri.parse(uriString) : content://media/internal/audio/media/13
02-13 10:51:18.195: E/SettingsProvider(2486): soundUri : content://media/internal/audio/media/13
02-13 10:51:18.481: E/RingtoneManager(2583): getActualDefaultRingtoneUri : content://media/internal/audio/media/13
02-13 10:51:18.481: E/RingtoneManager(2583): Uri.parse(uriString) : content://media/internal/audio/media/13
02-13 10:51:18.492: E/AudioService(2486): sendVolumeUpdate   VOLUME_CHANGED_ACTION  streamType =  2
02-13 10:51:19.277: E/PowerManagerService(2486): reset countdown Timer for PhoneAPP
02-13 10:51:20.500: E/AudioService(2486): sendVolumeUpdate   VOLUME_CHANGED_ACTION  streamType =  2
02-13 10:51:21.731: E/SensorManager(2486): registerListener 7:gp2a Proximity Sensor delay:240
02-13 10:51:21.734: E/SensorManager(2583): registerListener 0:SMB380 delay:240
02-13 10:51:21.738: E/SensorManager(2583): =======>>>Sensor Thread RUNNING <<<========
02-13 10:51:22.398: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$11@47b904c0
02-13 10:51:22.582: E/SensorManager(2486): registerListener 7:gp2a Proximity Sensor delay:240
02-13 10:51:23.477: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$12@47b90578
02-13 10:51:23.512: E/SensorManager(2486): unregisterListener: android.view.WindowOrientationListener$SensorEventListenerImpl@47da0520
02-13 10:51:23.922: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:36.535: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:36.535: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:55.660: E/SensorManager(2486): registerListener 4:gp2a Light Sensor delay:240
02-13 10:51:55.934: E/SensorManager(2486): registerListener 0:SMB380 delay:60
02-13 10:51:56.559: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:56.559: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:51:59.219: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$12@47b90578
02-13 10:51:59.246: E/SensorManager(2486): unregisterListener: android.view.WindowOrientationListener$SensorEventListenerImpl@47da0520
02-13 10:51:59.434: E/WifiService(2486): =========shouldWifiStayAwake: wifiSleepPolicy 2
02-13 10:52:40.289: E/SensorManager(2486): registerListener 4:gp2a Light Sensor delay:240
02-13 10:52:40.555: E/SensorManager(2486): registerListener 0:SMB380 delay:60
02-13 10:52:41.090: E/SensorManager(2486): unregisterListener: com.android.server.PowerManagerService$11@47b904c0
02-13 10:52:41.723: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:41.762: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:41.816: E/PowerManagerService(2486): reset countdown Timer for PhoneAPP
02-13 10:52:41.848: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:41.918: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.020: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.020: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.180: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.243: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.352: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:42.392: E/imdg81(2486): IsShutDownStarted()
02-13 10:52:44.856: E/SensorManager(2583): unregisterListener: com.android.phone.AccelerometerListener$1@47bcf058
02-13 10:52:57.398: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:53:19.419: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 10:53:48.957: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:55:23.664: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:56:23.383: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:57:05.449: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 10:58:05.168: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:01:55.379: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:03:32.785: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:03:55.887: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:05:33.266: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:06:00.133: E/Mms/SmsReceiverService(19272): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:08:18.781: E/libnetutils(2486): dhcp start cmd 11 : [dhcpcd:-ABK] 
02-13 11:08:19.012: E/HierarchicalStateMachine(2486): TetherMaster - unhandledMessage: msg.what=3
02-13 11:08:19.844: E/dalvikvm(19408): Could not find class 'android.database.sqlite.SQLiteCantOpenDatabaseException', referenced from method com.google.android.gms.plus.provider.PlusProvider.a
02-13 11:08:22.609: E/SPPClientService(19480): ============PushLog. commonIsShipBuild. stop!
02-13 11:08:22.625: E/SPPClientService(19480): [PushClientApplication] Push log off : This is Ship build version
02-13 11:08:23.332: E/dalvikvm(19491): Could not find class 'android.os.UserManager', referenced from method xg.b
02-13 11:08:23.332: E/dalvikvm(19491): Could not find class 'android.os.UserManager', referenced from method xg.c
02-13 11:08:27.352: E/dalvikvm(19514): Could not find class 'android.os.StrictMode$ThreadPolicy$Builder', referenced from method J.a.g
02-13 11:18:59.789: E/TalkProvider(2627): replaceContactWithContactId: contactId==0!!! [email protected], acct=1
02-13 11:18:59.805: E/TalkProvider(2627): insert presence failed for account=1 [email protected] client_type=2 status= priority=0 mode=3
02-13 11:19:58.402: E/dalvikvm(19408): Could not find class 'android.os.UserManager', referenced from method xg.b
02-13 11:19:58.406: E/dalvikvm(19408): Could not find class 'android.os.UserManager', referenced from method xg.c
02-13 11:20:01.215: E/dalvikvm(19727): Could not find class 'android.os.StrictMode$ThreadPolicy$Builder', referenced from method J.a.g
02-13 11:20:36.645: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 11:22:34.746: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:23:08.363: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:27:38.953: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:28:24.680: E/Mms/SmsReceiverService(19762): [SMS]Receiver handleMessage : Action =android.provider.Telephony.CB_RECEIVED
02-13 11:35:14.977: E/PowerManagerService(2486): CurLock p:3 mPS:1
02-13 11:36:57.973: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.051: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.121: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.215: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.277: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.289: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.439: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.516: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.582: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.664: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.739: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.808: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.902: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:58.966: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.056: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.056: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.201: E/imdg81(2486): IsShutDownStarted()
02-13 11:36:59.290: E/imdg81(2486): IsShutDownStarted()
02-13 11:37:01.778: E/imdg81(2486): IsShutDownStarted()
02-13 11:37:03.735: E/imdg81(2486): IsShutDownStarted()
02-13 11:37:12.348: E/HierarchicalStateMachine(2486): TetherMaster - unhandledMessage: msg.what=3
02-13 11:37:13.613: E/WifiHW(2486): [WIFI] Unload Driver
02-13 11:37:13.918: E/LogsProvider(19971): onCreate()
02-13 11:37:15.387: E/FlurryAgent(19914): Post to http://ads.flurry.com/v4/getAds.do caught IOException: java.net.UnknownHostException: ads.flurry.com
02-13 11:37:16.805: E/GoogleConversionPing(19950): Error sending ping
02-13 11:37:16.805: E/GoogleConversionPing(19950): java.net.UnknownHostException: Host is unresolved: www.googleadservices.com:80
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at java.net.Socket.connect(Socket.java:1057)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1373)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at com.google.ads.conversiontracking.a.run(SourceFile:168)
02-13 11:37:16.805: E/GoogleConversionPing(19950):  at java.lang.Thread.run(Thread.java:1096)
: E/(): Device disconnected
    
asked by anonymous 13.02.2014 / 14:17

2 answers

2

Researching a lot, I found a way to make it work and everything has to do with what Paulo Roberto suggested: it's a Context problem.

I do not know if it's the best technique, but I put it here only for those who might have this type of problem and at least provoke a good discussion for everyone.

The main change is that I changed the constructor of the user class, the one I created.

In this code, it begins to receive the context of the initial class and this context-variable is used in all lines of code that required this reference.

The initial code with a slight modification is:

[...]
//------------------------------------------------
        Button bt = (Button) this.findViewById(R.id.button1);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//Veja abaixo dois parâmetros no construtor: o caminho-nome do arquivo e o Context desta activity que instancia a classe
//---------
                Teste t = new Teste("raw/teste",MainActivity.this);//construção
//--------
            t.leArquivo();//método que executa a leitura do arquivo texto no objeto 't'
//---------
            }//onClick
        });//bt.setOnClick
[...]

Now, let's go to the user class:

public class Teste extends Activity {
    String strGblCaminhoNomeArquivo="";//variável 'global' do caminho-nome do arquivo
    Context gblContext;//variável 'global' do contexto recebido
//----------construtor
    public Teste(String strCaminhoNomeArquivo, Context context){
        this.strGblCaminhoNomeArquivo=strCaminhoNomeArquivo;
        this.gblContext=context;

    }//construtor
    //---------------------------

/*aqui no método é que o cuidado precisa ser tomado: gblContext teve de ser posto...
*..antes de getResources e de getPackageName().
*Do mesmo mesmo modo, teve de ser posto no Toast também.
*/
public void leArquivo(){
             InputStream ins = gblContext.getResources().openRawResource(gblContext.getResources().getIdentifier(this.strGblCaminhoNomeArquivo,"raw", gblContext.getPackageName()) );
                 InputStreamReader inputreader = new InputStreamReader(ins);
         BufferedReader buffreader = new BufferedReader(inputreader);
         String line;
     try {
             while (( line = buffreader.readLine()) != null) {
 Toast.makeText(gblContext, line, Toast.LENGTH_SHORT).show();
                    }

          } catch (Exception e) {
             Toast.makeText(gblContext, e.getMessage(), Toast.LENGTH_SHORT).show();
         }
    }//leArquivo
}//class

I have succeeded in displaying each line of the file without any error.

    
14.02.2014 / 00:11
1

When there is a need to use the \ res \ raw folder in any of my projects I use the following way.

 InputStream ins = getResources().openRawResource(R.raw.teste);

Every time you put a file in the raw folder, the system automatically creates an ID in the R class for that file, so when you use it this way it becomes much more difficult to get an I / O error.

I suggest that you change the signatures of the method to work with raw file IDs such as

public void lerArquivo(int idResources){...}

With this change the method call should be:

obj.lerArquivo(R.raw.teste);

As I see it, it gets easier to work on.

More information Android - Providing Reources

    
13.02.2014 / 16:08