Mengapa tidak menyimpannya ke folder cache aplikasi Anda menggunakan sesuatu seperti ini:
String path = Environment.getExternalStorageDirectory() + File.separator + "cache" + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
path += "data";
File data = new File(path);
if (!data.createNewFile()) {
data.delete();
data.createNewFile();
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
objectOutputStream.writeObject(actorsList);
objectOutputStream.close();
Dan setelah itu, Anda dapat membacanya kapan saja menggunakan:
List<?> list = null;
File data = new File(path);
try {
if(data.exists()) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
list = (List<Object>) objectInputStream.readObject();
objectInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
PERBARUI: Oke, buat class bernama ObjectToFileUtil, paste kode ini ke class yang dibuat
package <yourpackagehere>;
import android.os.Environment;
import java.io.*;
public class ObjectToFileUtil {
public static String objectToFile(Object object) throws IOException {
String path = Environment.getExternalStorageDirectory() + File.separator + "cache" + File.separator;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
path += "data";
File data = new File(path);
if (!data.createNewFile()) {
data.delete();
data.createNewFile();
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
objectOutputStream.writeObject(object);
objectOutputStream.close();
return path;
}
public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
Object object = null;
File data = new File(path);
if(data.exists()) {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
object = objectInputStream.readObject();
objectInputStream.close();
}
return object;
}
}
Ubah
private String dataPath;
dan ganti metode onPostExecute kelas JSONAsyncTask Anda menjadi
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result) {
try {
dataPath = objectToFile(arrayList);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
Sekarang Anda dapat mengakses get actorList dari File kapan pun Anda mau, dengan menggunakan
try {
actorsList = (ArrayList<Actors>)objectFromFile(dataPath);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Jika Anda ingin menyimpan jalur file setelah menutup aplikasi, Anda harus menyimpan string dataPath (dan memuat saat aplikasi dimulai), misalnya, menggunakan SharedPreferences.