21370

Loading an array from a .txt file? (Android)

Question:

I've searched around and haven't been able to coem up with a solution to this one.. my (first) problem is that i'm getting NPE on FileInputStream instream = context.getApplicationContext().openFileInput(textname);in the getLengthOfText(); method. I've debugged and the correct filename appears to be passed to this method. I've been stuck on this for weeks and really want it to work (newb).

this method is being called by another class. Also, the files are there in data/data and everything else is as it should be. please help!! -Tricknology

/***** this class takes a text file and loads it into an array **/ public class loadArray { Context context; textWriter textwriter; public loadArray (Context cxt) { this.context = cxt; textwriter = new textWriter (cxt); context = cxt; } FileInputStream instream; textWriter tw = new textWriter(context); String[] choiceAry, dummyAry; P p = new P(); // shared prefs helper String Choice; String comp = "notnull"; int addChoiceCount, length; // Context context = this.getApplicationContext(); public void buildDummies(int length) { // addChoiceCount = p.gisI("addChoiceCount"); choiceAry = new String[length]; p.pisI("length", length, context); // dummyAry = new String[100]; } public Integer getLengthOfText(String textname) throws FileNotFoundException {// counts how many lines of text // DataInputStream dis = new DataInputStream(openFileInput("file.dat")); int length = 0; instream = context.getApplicationContext().openFileInput(textname); InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); try { // while (!comp.equals(null)){ while (buffreader.ready()) { String temp = buffreader.readLine(); length++; } buffreader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return length; } public String[] laft(String textname) throws FileNotFoundException { // loads a text file to an array...load array from text........ length = getLengthOfText(textname); buildDummies(length); try { instream = context.getApplicationContext().openFileInput(textname); InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); // load array from text for (int i = 0; i < (length); i++) { try { Choice = buffreader.readLine(); choiceAry[i] = Choice; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } buffreader.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return choiceAry; } public String getOrderName() { // TODO Auto-generated method stub return null; } }

I found the answer thanks to Leeds and billiard from #android-dev

what I was doing is also calling loadArry from another class that did not extend activity.. so it was activity >calling> class that doesnt extend activity >calling> class that doesnt extend activity. somehow in there the context was lost. I basically applied similar lines at the top starting with

Context context; textWriter textwriter; public loadArray (Context cxt) { this.context = cxt; textwriter = new textWriter (cxt); context = cxt;

hope this saves someone a lot of time in the future.

Answer1:

You have made things much too complicated for yourself in the code. In the end, complicated code = harder debugging.

I load text files into arrays all the time.

Consider using the <a href="http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html" rel="nofollow">java.util.StringTokenizer</a> class or the String split() method in class java.lang.String.

TenFour4 brings up another good point.

This is what the code should look like...

Context context; textWriter textwriter; public loadArray (Context cxt){ this.context = cxt; textwriter = new textWriter (cxt); }

<strong>--UPDATE--</strong>

A common mistake is that the file you are trying to read from has not been closed properly, therefore you are getting a NullPointerException whenever you try to access the still open file.

e.g.

PrintWriter pw = new PrintWriter (new FileWriter (fileName)); pw.println ("This is output data: " + data); //new loadArray ().getLengthOfText (fileName); //ERROR Throws NPE pw.close(); //Make Sure you Close Before trying to read the file again! new loadArray ().getLengthOfText (fileName); //Works like a charm :)

Answer2:

As it seems to me, the only reason you may get NPE in the line you said you get it is that context is somehow NULL (openFileInput doesn't throw NPE) make sure that context is not NULL.

Answer3:

Your textWriter instance is getting instantiated while context is still null. Any definitions that occur outside of methods will happen before the constructor is called.

By the way, class names should start with a capital letter and not start with a verb, by convention. It will help you avoid errors and be easier for other people to understand.

Recommend

  • Trying to make my android application put files on my ftp server
  • How to read data from a text file and save some data from it to an Array
  • How to decode the H.264 video stream received from parcelfiledescriptor
  • How and where to install a module in python from github
  • PHP shell_exec running a shellscript with ssh
  • Lucene Query Boosting
  • Unpickling mid-stream (python)
  • Converting a PEM private key file to a JAVA PrivateKey Object
  • jQuery: click function bind in for-loop with closure fix
  • XGBOOST - DMATRIX
  • TCameraComponent and TVideoCaptureDevice do not initialize in Win32
  • branch out of range compile error
  • How can I get a specific line from a text file? [duplicate]
  • Streaming data from a NVarchar(Max) column using c#
  • How To Delete All Words After X Characters
  • How can I include the Ivy dependency and none of its dependencies?
  • How to grep for a specific pattern and print everything above and below that pattern until you reach
  • git cherry-pick: how consider only lines modified by the commit (i.e., not the surrounding context)?
  • react native create element with string
  • Greek letters in legend in R
  • Is it mandatory to have a doGet or doPost method?
  • Rodeo UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal
  • Need code translation from VB to C#
  • rewrite uppercase url to lowercase url htaccess
  • Authentication failed with Azure Active Directory in Windows Phone
  • In-place sed command not working
  • how to set variables in a php include file?
  • Z3: Convert between FP and BitVector?
  • Creating Java object from class name with constructor, which contains parameters [duplicate]
  • Reduction and collapse clauses in OMP have some confusing points
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Debug.DrawLine not showing in the GameView
  • How to use RequestBodyAdvice
  • R - Combining Columns to String Based on Logical Match
  • Read text file and split every line in MSBuild
  • Array.prototype.includes - not transformed with babel
  • Counter field in MS Access, how to generate?
  • Convert array of 8 bytes to signed long in C++
  • Return words with double consecutive letters
  • how to add data labels for bar graph in matlab