Firstly, I have researched this issue a lot. I learned to read from my text file in the resource folder. The problem is that I do not want the line to end because the file is actually an arraylist written using json and inside that arraylist are objects. I need to access only one object. Here is what I mean:
I have a Book class that has an int-called chapter, int called title and int called pageNum. I created several Book objects and added them to an ArrayList. Then I used the following code to write an ArrayList to a text file (in a regular java project):
ArrayList<Book> aList = new ArrayList<Book>(); aList.add(book1); //etc...add more Book objects here... File aFile = new File("books.txt"); FileOutputStream aFileStream = new FileOutputStream(aFile); JSONOutputStream jsonOut = new JSONOutputStream(aFileStream); jsonOut.writeObject(aList); jsonOut.close();
This code creates a text file, which is then placed in the / assets folder in my Android project, because I want it to be included in the application. In a non-Android Java project, I could just use the following code to refill the ArrayList so that I can parse book objects from specific indexes:
File bFile = new File("books.txt"); FileInputStream bFileStream = new FileInputStream(bFile); JSONInputStream jsonIn = new JSONInputStream(bFileStream); Arraylist<Book> bList = (ArrayList<Book>) jsonIn.readObject(); Book aBook = bList.get(253);
The json code I use comes from quickconnectfamily.org. You must add a file called qc_json.jar to the build path of your project. http://www.quickconnectfamily.org/qcjson/more.html
The problem in Android is when I read the file using InputStream, I can get the whole file into a string, the code above does not work in Android. I cannot wrap JSONInputStreams around InputStream, only around FileInputStream. But it seems I can not use FileInputStream.
So I need a way to create an ArrayList, not a string in my Android app. Without giving too much about my application, the application basically generates a random number and creates a Book object from this index in an ArrayList. The user then receives information from this particular book. Sounds silly, but the real application is much cooler.
I am open to solutions, alternative methods of storing objects in a text file, etc. Please do not just post criticism regarding my grammar, syntax, or application idea. I'm new to application development, and I don't care about personal opinions. If someone wants to see more code, I can download it, but at the moment this does not seem necessary. Thanks.