Created
June 5, 2015 13:13
-
-
Save aantunovic/dc13d2b157597b3efd51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package etfos.hr.tio; | |
import android.content.Context; | |
import android.util.Log; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
import com.google.gson.reflect.TypeToken; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.Reader; | |
import java.io.Serializable; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
public class ModelManager<T extends Serializable> implements Manager { | |
public static final String TAG = ModelManager.class.getSimpleName(); | |
private final File mFile; | |
private Context mContext; | |
private List<T> mItems; | |
protected final String FILE_NAME = new TypeToken<T>() {}.getType().getClass().getName(); | |
private static ModelManager sInstance; | |
public static ModelManager getInstance(Context context) { | |
if (sInstance == null) { | |
sInstance = new ModelManager(context); | |
} | |
return sInstance; | |
} | |
private ModelManager(Context context) { | |
mContext = context; | |
mFile = new File(mContext.getFilesDir(), FILE_NAME); | |
deserialize(); | |
} | |
@Override | |
public void deserialize() { | |
try { | |
Gson gson = new Gson(); | |
InputStream is = mContext.getAssets().open(FILE_NAME); | |
Reader reader = new InputStreamReader(is); | |
T[] items = gson.fromJson(reader, new TypeToken<T[]>() {}.getType()); | |
mItems = Arrays.asList(items); | |
} catch (Exception e) { | |
Log.e(TAG, e.getStackTrace().toString()); | |
} | |
} | |
@Override | |
public void serialize(ArrayList items) { | |
Gson gson = new Gson(); | |
if (mFile != null) { | |
try { | |
FileWriter writer = new FileWriter(mFile); | |
writer.write(gson.toJson(items)); | |
writer.flush(); | |
writer.close(); | |
} catch (IOException e) { | |
Log.e(TAG, e.getStackTrace().toString()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment