Activity not reading serialized objects from another activity - android

Essentially, what I'm trying to do is save an ArrayList of Strings in one activity and then read them in another. The file is created (I can see it in the DDMS) but for some reason I can't get the activity to read the objects.
Here's the reading code:
try {
FileInputStream fis = new FileInputStream("purchased_songs.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
purchasedSongs = (ArrayList<String>) ois.readObject();
ois.close();
for(int i=0;i<purchasedSongs.size();i++)
Log.d("purchased songs",purchasedSongs.get(i));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the writing code:
try {
FileOutputStream fos = openFileOutput("purchased_songs.obj",MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(purchasedSongs);
os.close();
}catch(Exception e){
e.printStackTrace();
}

Of course I figured out what is wrong.
Change
FileInputStream fis = new FileInputStream("purchased_songs.obj");
to
FileInputStream fis = openFileInput("purchased_songs.obj");

Related

How to Write/Read ArrayList<Marker> into file

I need to write/read an ArrayList<Marker> to a file.
Here is what I did so far:
Save List:
private void saveToFile(ArrayList<Marker> arrayList) {
try {
FileOutputStream fileOutputStream = openFileOutput("test.txt", Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fileOutputStream);
out.writeObject(arrayList);
out.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Load List
private ArrayList<Marker> loadFromFile() {
ArrayList<Marker> savedArrayList = null;
try {
FileInputStream inputStream = openFileInput("test.txt");
ObjectInputStream in = new ObjectInputStream(inputStream);
savedArrayList = (ArrayList<Marker>) in.readObject();
in.close();
inputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return savedArrayList;
}
When I run the code I'm getting ClassNotFoundException.
The issue is that I need to store the whole ArrayList<Marker> as object.
I have found a solution that it separates the Marker into lat/long and write it to the text file as numbers, but it is not suitable for me.
I understand that the Marker Class is not Serializable, but how then it can be saved as an whole object?

Save arraylist of objects and reading it from file

I have an arraylist of objects in a fragmentActivity
private List<Movie> myMovies = null;
I have options to add, remove and all that from the movie list, but once I close the application all is lost. How can I save the array into a file and retrieve the array from the file?
I have:
public void writeArray() {
File f = new File(getFilesDir()+"MyMovieArray.srl");
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream objectwrite = new ObjectOutputStream(fos);
objectwrite.writeObject(myMovies);
fos.close();
if (!f.exists()) {
f.mkdirs();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Movie> read(Context context) {
ObjectInputStream input = null;
ArrayList<Movie> ReturnClass = null;
File f = new File(this.getFilesDir(),"MyMovieArray");
try {
input = new ObjectInputStream(new FileInputStream(f));
ReturnClass = (ArrayList<Movie>) input.readObject();
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ReturnClass;
}
but it is not working. getFilesDir() always points to a nullpointerexception
Is this the right way to do it?
Any sugestions on how can I save the array into a file and retrieve the array from the file?
UPDATE 1: Found the fix, just needed to write File f = new File(getFilesDir(), "MyMovieArray.srl");
New problem arrised: I have this code for onCreate:
myMovies = read(this);
if(myMovies==null){
myMovies = new ArrayList<Movie>();
populateMovieListWithExamples();
writeArray();
}
Everytime I start the application it always shows the list with the populate examples... if I add or remove once I reopen it is always the same list. Sugestions?
UPDATE 2 Just needed Movie class to be serializable. Thank you all for your help. Have a good day everyone
You are saving to MyMovieArray.srl but reading from MyMovieArray. Read also from MyMovieArray.srl
File object should be created like this (both in write and read):
File f = new File(getFilesDir(), "MyMovieArray.srl");
Use File f = new File(getFilesDir(), "MyMovieArray.srl");
in both writeArray() and read() methods

Read a file, if it doesn't exist then create

Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. It works for me perfectly like it should, so I do not want to change my code.
The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file.
Code for saving data:
String data = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Code for loading data:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte [fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want?
Add
File file = new File(FILENAME);
if(!file.exists())
{
file.createNewFile()
// write code for saving data to the file
}
above
fis = openFileInput(FILENAME);
This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one.
If you're working on Android, why don't you use the API's solution for saving files?
Quoting:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data.
But regarding your original question:
So If I add the saving data code in to the "FileNotFoundException"
catch of the loading data part then could I achieve what I want?
Yes, you could achieve it.
Try this one:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile()){
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try {
// ...
// read data
// ...
}finally{
r.close();
}
}
Ref: Java read a file, if it doesn't exist create it

adding hashmap object to internal memory every time

i have a hashmap object which i am saving in Internal memory, but each time its replacing the hashmap object instead of adding, how can i add the hasmap object each time when i call this method:
here is my code:
public void saveDataInInternalStorage(Context context, HashMap<String, HashMap<String, String>> hashMapObject,
String fileName) {
try {
File file = new File(context.getDir("data", MODE_PRIVATE), fileName);
// if (file.exists()) {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.writeObject(hashMapObject);
outputStream.flush();
outputStream.close();
// }
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
Just change this line:
FileOutputStream fos = new FileOutputStream(file, true);
The truetells the FOS to append the content to the file, not overwrite ist.

How to write/read array to file in android

I am writing to file in android and read from the same file using the below code:
//Write data on file
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("gasettings.dat", MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved", Toast.LENGTH_SHORT)
.show();
}
catch (Exception e) {
e.printStackTrace();
}
and the code for reading from file is:
InputStreamReader isr = null;
fileInputStream fIn = null;
char[] inputBuffer = new char[255];
String data = null;
try {
fIn = openFileInput("gasettings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
}
catch (Exception e) {
e.printStackTrace();
}
as per now I am only able to save a string to this file.
I like to write a DATE array to it and also want to read back the data as array.
I know that the return type of read method will be changed, but I am not getting the idea of how to read and write the DATE array or any other array to the file.
Thanks
In that case, your better choice is using JSON. It will allow you to save an array in String format, read it back and convert it again into the original array.
Take a look of this example: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/

Categories

Resources