adding hashmap object to internal memory every time - android

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.

Related

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

How to perform caching in android?

I am building an articles reading android application like TechChurn. I am fetching data from server in the form of json.
I am parsing Id(unique),title, author name and articles-content from json and displaying it in list-view.
Those parsed content is stored in local for accessing without internet access.
This i have done using a cache function.
Here is my code that is using for caching -
public final class CacheThis {
private CacheThis() {
}
public static void writeObject(Context context, String fileName,
Object object) throws IOException {
FileOutputStream fos;
ObjectOutputStream oos;
if (fileExistance(fileName, context)) {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE
| Context.MODE_APPEND);
oos = new AppendingObjectOutputStream(fos);
} else {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE
| Context.MODE_APPEND);
oos = new ObjectOutputStream(fos);
}
oos.writeObject(object);
oos.flush();
oos.close();
fos.close();
}
public static List<Object> readObject(Context context, String fileName) {
List<Object> list = new ArrayList<Object>(0);
FileInputStream fis;
try {
fis = context.openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object;
try {
while (true) {
object = ois.readObject();
list.add(object);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public static boolean fileExistance(String fname, Context context) {
File file = context.getFileStreamPath(fname);
return file.exists();
}
}
my article should be cached based on id instead its been loaded for every-time when app is started
Use the following methods to store and retrieve the data.. Here you can store the object..
private void writeData(Object data, String fileName) {
try {
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(data);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object readData(String fileName){
Object data = null;
if (context != null) {
try {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
data = is.readObject();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return data;
}
Write the data once you got the response from the server(at first request to the server). Use the id as file name. After that check for the particular file before you want to hit server for data. If the file is available then you can get the data from that file, otherwise hit the server.

Activity not reading serialized objects from another activity

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");

Storing serialized objects into sdcard as file causing FileNotFoundException

I want to serialize an object and store it inside sdcard under my project name but I'm getting FileNotFoundException.
My code is written below:
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
File dir = new File(Environment.getExternalStorageDirectory(), FILE_LOCATION + username);
try {
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, FILE_NAME);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(formList);
objectOutputStream.close();
} catch(IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
What is the reason for this issue? I'm running in emulator and my application is in android 3.0.
I suspect your filename is invalid, maybe that . in the directory? Or the file-name its self.
Correct me if I'm wrong, but don't you have to create the File before you write to it?
File file = new File(dir, FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
I would like to share my solution for this since I got a lot of help from Stackoverflow on this issue (by searching for previous answers). My solution resulted for a couple of hours of searching and piecing together solutions. I hope it helps someone.
This will write and read an ArrayList of custom objects to and from External Storage.
I have a class that provides IO to my activities and other classes. Alarm is my custom class.
#SuppressWarnings("unchecked")
public static ArrayList<Alarm> restoreAlarmsFromSDCard(String fileName,
Context context) {
FileInputStream fileInputStream = null;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();//Alarm is my custom class
//Check if External storage is mounted
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
Log.v("FileIOService", "No Such Directory Exists");
}
File file = new File(dir, fileName);
fileInputStream = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fileInputStream);
alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Do something here to warn user
}
return alarmList;
}
public static void saveAlarmsToSDCard(String fileName, ArrayList<Alarm> alarmList,Context context) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(alarmList);
objectOutputStream.close();
} catch (IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
}else{
//Do something to warn user that operation did not succeed
}
}

Android:Writing data to a file

with the below piece of code, I'm able to create a new file called output.txt and i'm able to write data. Problem is this file gets recreated once i close my app and then open my app again. As because i create this in onCreate().
But i would like to have the file created only once and then i would like to append the data there after.
private File outputFile = null;
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
#Override
public void onCreate(Bundle savedInstanceState) {
....
if(outputFile == null)
outputFile = new File("/storage/new/output.txt");
if(osr==null){
try {
osr = new FileOutputStream(outputFile);
out = new DataOutputStream(osr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
.....
try {
out.writeBytes(data);
out.flush();
//out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try setting the append flag to true when constructing your FileOutputStream
osr = new FileOutputStream(outputFile, true);
Try,
FileOutputStream fileOut = openFileOutput(outputFile, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.writeBytes(data);
osw.flush();

Categories

Resources