I am working on a articles application like techcrunch I am parsing data from json. I am parsing title,author and image from json. Articles are displayed in list-view. I want to
This probably isn't the best way to do it, but it worked for me.
You might find this helpful: http://www.vogella.com/tutorials/JavaSerialization/article.html
I had to do the same in some project. This is what I did:
public final class cacheThis {
private cacheThis() {}
public static void writeObject(Context context, String fileName, Object object) throws IOException {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.flush();
oos.close();
fos.close();
}
public static Object readObject(Context context, String fileName) throws IOException,
ClassNotFoundException {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
fis.close();
return object;
}
}
To write to file:
cacheThis.writeObject(YourActivity.this, fileName, movieList);
To read from file:
movieList.addAll((List<Movie>) cacheThis.readObject(
VideoActivity.this, fileName));
You have to have your Movie class implements Serializable
I saw you are using Volley
. Volley has built-in HTTP Cache
mechanism.
So the easiest way is to support HTTP cache headers in your backend. It is very easy and it is transparent to the client side. Volley
does the hard work. You can find information here
If you don't have access to the URL you use, you must use internal database to support your application. ContentProvider
API is the best way to do that. And the following library is a great library to construct a database and write to it.
https://github.com/TimotheeJeannin/ProviGen
Basically you need to write every item that you pull from the internet to the database and the ListView
should show the items from the database using ContentProvider
you have just created. When the user opens the app, show the data from the database and then immediately try to pull the new data from your backend.
You must save the json offline. It can be Db or file system. I will prefer to go with Db part.
The approach is ,every time you get data from server save first in you db then from db you can show it to your UI.
Inserting in Db can be slow but you can use beginTransaction and other methods which will make it lighting fast.
Now How can you save data in Db. You have two ways
You can parse json first and create the table structure for name,url and other fields then run the query
Or store the whole json in Db without parsing .By using GSON or other json parsers this approch will be quite helpful.