Reading text file stored in raw folder through a user class

Asked

Viewed 2,748 times

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 stamps its content 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.

So, I wanted to create a class, so that, after instantiated, I read different files, when I passed to a method the name of the desired file. I would only 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

Since I have this class within the same package, I will modify the initial code, the first one from above, so that I can take advantage of the class created:

 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 Mainactivity, at the click of the button, all the code that worked in reading the file and passed to the method of the created class, taking into account the passage of Context that called.

The problem I face is that the application 'crasha' and Try/catch does not warn me anything.

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

Where I’m 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
  • Friends, I just posted, but I think I’ve solved the problem. You’re in class Testaleituraarquivo, in the method file(). Specifically on the line of the two Toast: when I changed the context gblContext for this worked.

  • I’m sorry, I didn’t find the solution, no. I made a mistake. I continue with the problem.

  • Probably your problem is with the Context try to implement it in a different way.

  • Please post the error log even if you did not find the exact line.

  • I put the error log after the presented codes. Thank you.

  • Dear Paulo Roberto, I have tried in some ways, but it always gives the same error, I do not know what it is. This is the biggest problem, not knowing which is the exact error.

Show 1 more comment

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 is the best technique, but I put it here only for those who might have this kind of problem and at least provoke a good discussion for all.

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

In this code, it takes the context of the initial class and this context variable is used on 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

Done this, I succeeded in displaying each line of the file without any error.

  • I was going to suggest this to you, but I hate global variables, and I bet a lot of people here hate it too, and I didn’t see any other way to do it, so I didn’t answer ;P but it was good on your balcony, the same as my haha :) - and on answering your own question, yes! you both can and should do this whenever you find the answer to your problem.

  • If only I had Private string strGblCard; and private context gblContext; maybe it would be better, no?

  • It’s just that it’s not really going to change much. All the variables you declare up there at Activity you will be able to access from anywhere in your Activity that you are, so it is not necessary nor the this. in front :p

  • Yes, I use the this to be quite clear the 'strength' of the variable. But within the same class this pseudo 'global' scope does not do much harm, don’t you think? Or is there some implication I should know?

  • Global variables are only not used because they can generate conflicts, or you can change their value unintentionally by causing several problems, local variables are always best recommended by the fact that they are forced to be used only for one functionality and preventing use for another functionality. But in your case I believe there will be no problem, unless you eventually add more variables to your Activity then maybe it can create a confusion.

1

When there is a need to use the res raw folder in any of my projects I use it as follows.

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

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

I suggest you change the signatures of the method to work with the Ids of aruqivo raw as for example

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

With this change the method call should be:

obj.lerArquivo(R.raw.teste);

In my view it’s easier to work.

More information Android - Provinding Reources

  • Dear Clebao, this causes me a code saving, as you said, on the one hand, but forces me to make more code to find out, from the name in the raw folder, the file id. It wouldn’t be the same?

  • But the files in your raw folder are not fixed? or you download files on demand?

  • On demand, Clebao. I want to read the contents of the folder, which can be mobile in the amount of files. I don’t want to cast such, since the application itself will have several 'flavors' in independent apks, with amount of different text files.

  • In this case I recommend you work with getResources(). getIdentifier("raw/test","raw", getPackageName()), would soon be basically Inputstream ins = getResources(). openRawResource( getResources(). getIdentifier("raw/test","raw", getPackageName()) );

  • I appreciate the help, Clebao, but it didn’t help. Still having the 'exception', with nothing new in the bug log.

  • By the sue logcat that you placed in the question I could not identify the error, put the Try cat o e.printStackTrace() and paste the logcat again.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.