I'm working on an Android app and I got to a point where I need to add some Store objects to an ArrayList favoriteStores. The problem is that I want this list to persist after closing the application, because my list of favorite stores must stay there until I chose to delete particular items inside it. Anyone got any idea what type of implementation I might use? Thanks in advance,
If you don't want to save arraylist to database, you can save it to file. It is a great way if you just want to save arraylist and don't want to touch sqlite.
You can save arraylist to file with this method
public static <E> void SaveArrayListToSD(Context mContext, String filename, ArrayList<E> list){
try {
FileOutputStream fos = mContext.openFileOutput(filename + ".dat", mContext.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And you can read that saved file to arraylist with this method
public static Object ReadArrayListFromSD(Context mContext,String filename){
try {
FileInputStream fis = mContext.openFileInput(filename + ".dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj= (Object) ois.readObject();
fis.close();
return obj;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<Object>();
}
}
Hope this help.
You can either use a database like SQLite (howto here) or use some serialization technique. There is a related question to serialization here.
General information about storing data in Android can be found here.
Here's a nice post about data storage options in Android, read it carefully and select the option that you find the most appropriate.
Related
I am given an assignment where we are not allowed to use a DB or libraries but only textfile for data storage.
But it has rather complex requirements, for e.g. many validations, because of that, we need to "access the db" (i.e. read the textfile) many times.
My question is: should I create a class like this:
class SomeRepository{
static ArrayList<Users> users = new ArrayList();
public SomeRepository(){
//instantiate this class on program load
//In constructor, we read the text file, instantiate and store everything inside the arraylist.
}
//public getOneUser(){ // for get methods, we don't read from text file at all }
/public save() { //text file saving code overhere }
}
Is this a good approach to solve the above problem? Currently, what we are doing is reading and writing to the text file every time we want to retrieve some data or write something new.
Wouldn't this be too expensive in terms of heap space memory? Or should I just read/write to the text file for every method?
public class IOManager {
public static void writeObjToTxtFile(String fileName, Object object) {
File file = new File(fileName + ".txt");//File will be created in the root directory where the program runs.
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(object);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object readObjFromTxtFile(String fileName) {
Object obj = null;
File file = new File(fileName + ".txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
obj = ois.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return obj;
}
}
Add this class to your project. Since it's general for all Objects, you can pass and receive Objects like these as well: ArrayList<Users>. Play around and Tinker with it to fit whatever your specific purpose is. Hint: You can write other custom methods that calls these methods. eg:
public static void writeUsersToFile(ArrayList<Users> usersArrayList){
writeObjToTxtFile("users",usersArrayList);
}
Ps. Make sure your Objects implement Serializable. Eg:
public class Users implements Serializable {
}
I would suggest reading the contents of your file to a dynamic list such as an arraylist at the start of your program. Make the required queries/changes to your arraylist and then write that arraylist to your file when the program is set to close. This will save significant time over repeated file reads/writes.
This isn't without it's drawbacks, though. You don't want to hogg up memory in case of very large files - but considering this is an assignment, that may not be the case. Additionally, should your program terminate prior to the write at the end, all changes made to your database during the current execution will be lost.
I am using dcm4chee2 to parse through tags with their DicomInputStream and DicomObject. I am then converting the metadata into a ArrayList of type String. However, when I use the toString() method to convert the tags from DicomObject to a String, I am noticing I am not getting a full list of DICOM tags, VR Codes, and Description. Can anyone tell me if there is another DicomObject method I should be using to get a full list rather than the toString()?
Here is the code I currently have:
ArrayList<String> dicomTags = new ArrayList<String>();
DicomInputStream din = null;
FileOutputStream fos = new FileOutputStream("dicomTagResults.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
din = new DicomInputStream(new File(pathName));
try {
DicomObject dcmObj = din.readDicomObject();
dicomTags.add(dcmObj.toString());
for (String findMatch : dicomTags){
System.out.println(findMatch.toString());
oos.writeObject(dicomTags);
oos.close();
}
}
catch (IOException e)
{
e.printStackTrace();
return;
}
You can use
toStringBuffer(StringBuffer sb, DicomObjectToStringParam param)
and define a different DicomObjectToStringParam object (I suspect that it is not providing all of the attributes because the defaults are too small for your dataset).
If you truly want to loop through all of the attributes, you're probably better off using
Iterator<DicomElement> data = dcmObj.datasetIterator();
and handling the sequence elements appropriately as you loop through the iterator.
I am creating a little GUI for a "movie manager" with Java and Swing.
I have a class MovieTableModel that extends AbstractTableModel and has the data for the rows of the table in an Object[][]data.
A second class MovieUI manages the JFrame and well, the GUI in general.
The last class MovieManager is actually just a main function to create an instance of movieui and make it visible.
Now my problem is that by now, data is "saved" in my code. I want it to be able to be loaded and saved. If there is no save-file, one should be created and I should be able to add or delete rows of it (the actionlisteners are already set up, I just need a way to handle the file).
So the GUI looks like this:
MovieManager
This is kinda what I tried:
File tabledata = new File("tabledata.class");
if (!tabledata.exists()) {
try {
tabledata.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
tabledata.
FileInputStream in = new FileInputStream("tabledata.class");
ObjectInputStream input = new ObjectInputStream(in);
Object data = input.readObject();
System.out.print(data);
Both didn't work - I think I do understand how this works in general, but I don't know how to make it to the data in my table, especially as it is saved as an Object[][] but the file is an Object.
And if that works out - how can I add or delete single rows?
Thanks for your help in advance! :)
If you serialize you tablemodel or the object that backs your tablemodel, then you can read it later and restore it to the JTable.
When you read the object again from the ObjectInputStream, I think you are missing the cast to the right type you are saving:
FileInputStream in = new FileInputStream("tabledata.class");
ObjectInputStream input = new ObjectInputStream(in);
Object[][] data = (Object[][])input.readObject();
After you create new file you need to write the data using ObjectOutputStream and then read it with ObjectInputStream.
Object[][] data;
//save
File tabledata = new File("tabledata.dat"); //I wouldn't use class extension (class is for compiled Java)
//creation of file omitted
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tabledata));
out.writeObject(data);
out.close();
//load
ObjectInputStream in = new ObjectInputStream(new FileInputStream(tabledata));
data = (Object[][]) in.readObject(); //explict cast required
in.close();
Because this stores all data as one big chunk I don't think it is possible to just read/write one element. You would have to resort to counting bytes of stored objects and then skip to right position. If you would really need to store huge amount of table data I would use some relational database as backend. Otherwise I wouldn't bother with such optimization. Just rewrite everything on save.
[I'm quite new with Android programming so please excuse me for my nooby questions]
I'm developing a dictionary app. One of this app's feature is the Favourite button which allows user to save favourite words (short-click) and view the list of favourite words (long-click).
So far, I have succeeded in saving words into a text file (myfav.txt). The format of the content of the text file is as below (each item on a line):
A
B
C
...
Z
However, I have problem in loading and viewing this file inside my app. I'm thinking of using ListView to display the content of "myfav.txt" but I don't really know what to do. I have consulted the Qs & As from other similar posts here but found myself more confused as a result.
Therefore, my questions are:
How can I load content of "myfav.txt" and display it using ListView? Could you please give detailed instructions as for beginners?
Are there any better ways to do view the content of "myfav.txt" other than ListView?
Here is my code:
//Reading lines from myfav.txt
btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
File sdcard = Environment.getExternalStorageDirectory();
setContentView(R.layout.text_view);
//trying opening the myfav.txt
try{
File f = new File(sdcard,"myfolder/myfav.txt");
InputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
while((readString = buf.readLine())!= null){
Log.d("Content: ", readString);
//How to code to load/view the content of "myfav.txt"
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return false;
}
});
Thank you very much indeed.
Hi you can find useful example here.
I do not think it's a good idea to use ListView for it. You'll need to provide ListAdapter if you choose this way.
I'd recommend using TextView (if you don't need to edit your text) or EdiText (if you do)
Using a file to save such information is not too sophisticated. I think you should look into tutorials about using SQLite, so you can store the words in a databse, and use cursors to view them in ListViews. You could use a separate boolean coloumn in you schema to mark favourited words that way for example.
Anyways, if you want to stick with files, one solution would be:
Read the contents of the file into a String array. You can use e.g. the Scanner class to easily read in lines from the file, and store them as separate strings in this array.
Construct a simple ArrayAdapter adapter class using this array.
Assign this adapter to a ListView.
Profit.
I am using following for writing to file -
FileOutputStream fout = null;
try {
fout = openFileOutput(fileName, MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(wordList); //writing arraylist<T>
oos.flush();
} catch(IOException e)
{
e.printStackTrace();
}
For reading -
fin = openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
list =(ArrayList<T>)ois.readObject(); //reading in arraylist directly
Hi all I need an advice.
I'll explain my problem. I want take data from web , elaborate the result, keep it and serialize on file.
I need to restore and use data from file , somehow. I dont want that file is been overwritten and lose old data.I need have a sort of list of Object in the File where i can search the last , use Method of another class to find some values etc , insert or similar, etc.....
In this case i used ArrayList but i dont know if it was the best choise.
I tried to do this but i have a problem know. In the specific if use a Class called Data and i want a serilizate file that keep ArrayList. So when i call method save(Object obj) of FileStructureClass(a class that i made to save, load file ) in this method i need to check if file already has an ArrayList so if it's true i can add in that Arraylist the Object , passed as parameter , else i return a new ArrayList. Of course i do a cast from Object to Data Class when i add in ArrayList.
I would fix this problem and then after find a better solution (if there is) to my problem.
The Data Class contains only 3 String and 1 GregoriusCalendar. Keep in mind(for the choise as ArrayList as Solution) that i need save file 1 time at day(i do a check with last element of the arraylist and do check with actual GregoriusCalendar..if past 1 day i can insert the element in arraylist).
After Explain the situation i list my problems
When i try to save for the FIRST time a Data Object in the Arraylist i have an error java.io.EOFException , i think that the problem is in tmp= ArrayList)ois.readObject(); but i cant find a solution. Dont happen when i insert manually a DataObject in the ArrayList and i use a method to insert a second one
According to you , ArrayList is a valid solution for my situation?
This method check if the file has data or not.
If it's empty i create a new one ArrayList and return it
otherwise i read the ArrayList already store in the file , and i return it
public ArrayList<Dati> check() {
ArrayList<Dati> tmp = new ArrayList<Dati>();
ObjectInputStream ois;
try{
fileInput = new FileInputStream("prova.dat");
ois = new ObjectInputStream(fileInput);
if (ois.readObject() == null) {
Logger.getLogger("file is empty");
ois.close();
return tmp;
}
//The error that i recive arrives from the under line
// (Impossible load file check method: java.io.EOFException
tmp = (ArrayList<Dati>) ois.readObject();
ois.close();
} catch (IOException e) {
System.out.println("Impossibile caricare i dati metodo check: "+e);
}
catch (ClassNotFoundException e) {
System.err.println("error");
}
return tmp;
}
//This method recive data of file that contains ArrayList<Data>
// and add to this a Data Object gave as Parameter
public void save(Object obj){
try{
ArrayList<Data> temp = check();
temp.add((Data) obj);
ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("prova.dat"));
os.writeObject(temp);
os.flush();
os.close();
}
catch(IOException e){
System.out.println("Impossible save datas: "+e);
}
}
public Object load(String path){
Object obj=null;
try{
fileInput=new FileInputStream(path);
ois=new ObjectInputStream(fileInput);
obj=ois.readObject();
ois.close();
}
catch(IOException e){
System.out.println("Impossible load file: "+e);
}
catch(ClassNotFoundException e){
System.err.println();
}
return obj;
}
When i try to save for the FIRST time a Data Object in the Arraylist
i have an error java.io.EOFException , i think that the problem is
in tmp= (ArrayList)ois.readObject(); but i cant find a solution. Dont
happen when i insert manually a DataObject in the ArrayList and i
use a method to insert a second one
This seems to be correct. Looking at javadoc, it does seem like ois.readObject() returns null when there is nothing in the file. One approach I can think of is to initialize the file with an empty ArrayList in setup phase.
According to you , ArrayList is a valid solution for my situation?
I don't see why not. But it depends on what you will do with the list after reading it. If you have to search it often and it is large then you may consider a different data structure.