How do I store data into a flat file in Android? - android

I want to store a few values in the form of high scores. But since I'm not going to be storing more than 5 values, using SQLite doesn't seem appropriate. Another option I was considering was a flat file, but I'm not sure how to go about that...

See here for your Data Storage options. I suppose that in your case the easiest will be to use SharedPreferences.
You could also use Internal Storage to save data in a file that is private to your application. I wouldn't recommend to use External Storage for storing high scores.

If it's an array you can use this:
public void saveArray(String filename, String[] output_field) {
try {
FileOutputStream fos = new FileOutputStream(filename);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(output_field);
out.flush();
out.close();
}
catch (IOException e) {
e.getStackTrace();
}
}
#SuppressWarnings("unchecked")
public String[] loadArray(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
String[] read_field = (String[])in.readObject();
in.close();
return read_field;
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
You just call it like this:
Save Array: saveArray("/sdcard/.mydata/data.dat", MyArray);
Load Array: String[] MyArray = loadArray("/sdcard/.mydata/data.dat");
You can see an example at http://androidworkz.com/2010/07/06/source-code-imageview-flipper-sd-card-scanner/

Related

How can we use cache for stored json data in android [duplicate]

My application should work not only in online but also in offline mode. For that reason I am considering find the best way for cashing data. I't like use SharedPreference for store data but in android documentation writen Maximum size in characters allowed for a preferences value is 8192. I don't know this is ok or not? I tried to pass out of this idea trying to use FileCashing or sqLite cashing.
So what you think guys what is the best SharedPreference vs FileCashing or vs SqLiteCaching?
Save the json in cache directory as file....
Save:
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
// Save the JSONOvject
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( jsonObject );
out.close();
Retrieve:
// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
JSONObject jsonObject = (JSONObject) in.readObject();
in.close();
I personally like to do this the following way. Create a SQLite database that can hold your content. Then, bind the user interface directly to the database using Adapters & Content Providers that send a notification whenever the data is changed so that the UI can update itself. The last piece in the equation is some form of synchronization service that downloads content and saves it to the database asynchronously. That way, you can manage your data very easily because it is all in the same place. The only part you'll have to figure out for your app is how you decide when to update or remove the data from the database.
Adapters
ContentProvider
Synchronization
Based on your requirement I would recommend SQLite data base.
Since shared preference is suitable for configuration storage - often small data/strings.
File cache is hard to manage, so I recommend SQLite - easy to manage and ability to store mass data.
Considering the performance, if the number of index is not that huge, SQLite database should have the acceptable performance. E.g. only several ms slower than a file cache.
You might be able to combine these two approaches together. Use random access file with index-offset stored in SQLite.
I have used Internal Storage which store file in Application package directory that can't be accessible by not rooted device.
Here the class which can create, read and delete the file
public class ReadWriteJsonFileUtils {
Activity activity;
Context context;
public ReadWriteJsonFileUtils(Context context) {
this.context = context;
}
public void createJsonFileData(String filename, String mJsonResponse) {
try {
File checkFile = new File(context.getApplicationInfo().dataDir + "/new_directory_name/");
if (!checkFile.exists()) {
checkFile.mkdir();
}
FileWriter file = new FileWriter(checkFile.getAbsolutePath() + "/" + filename);
file.write(mJsonResponse);
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readJsonFileData(String filename) {
try {
File f = new File(context.getApplicationInfo().dataDir + "/new_directory_name/" + filename);
if (!f.exists()) {
onNoResult();
return null;
}
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
onNoResult();
return null;
}
public void deleteFile() {
File f = new File(context.getApplicationInfo().dataDir + "/new_directory_name/");
File[] files = f.listFiles();
for (File fInDir : files) {
fInDir.delete();
}
}
public void deleteFile(String fileName) {
File f = new File(context.getApplicationInfo().dataDir + "/new_directory_name/" + fileName);
if (f.exists()) {
f.delete();
}
}
}
You can create, read and delete the file by calling ReadWriteJsonFileUtils class methods as follows:
For creating file:
try {
new ReadWriteJsonFileUtils(context).createJsonFileData(file_name, data);
} catch (Exception e) {
e.printStackTrace();
}
For reading file:
String jsonString = new ReadWriteJsonFileUtils(context).readJsonFileData(file_name);
For deleting single file
new ReadWriteJsonFileUtils(context).deleteFile(file_name);
For deleting all file
new ReadWriteJsonFileUtils(context).deleteFile();

How to append data in android (each data in new line)

I am making a bookmark for web browser app this code is saving and loading the data but it is not appending data in new line...every time i am pressing the button it is overwriting previous data ..I want that every time i call bookmarkload(); method in main activity it should save data in new line instead of overwriting it..Please help me as i am new to android tell what line to enter where..so that it start appending data..Thanks in advance ..please give answer in detail if possible.
public class Bookmark {
FileOutputStream fos;
FileInputStream fis = null;
public void bookmarksave(Context context,String FILENAME,String data){
try {
fos = context.openFileOutput(FILENAME, 0);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String bookmarkload(Context context,String FILENAME){
String collected =null;
try{
fis =context.openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
collected = new String(dataArray);
fis.close();
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return collected;
}
}
fos.write(System.getProperty("line.separator").getBytes());
Try this one... new data will be appended in new line..
change the Line fos = context.openFileOutput(FILENAME, 0); to
fos = context.openFileOutput(FILENAME, Context.MODE_APPEND);
This will open your file in append mode, instead of the default (override) mode.
You should also add a new line, otherwise you continue in the same line as before:
fos.write(System.getProperty("line.separator").getBytes());
You can use SharedPreferences to save your bookmark.It's very convenience.And if you want to use File to store them.You can use new FileOutputStream(filename,true) ,true means bytes will be written to the end of the file rather than the beginning.

How to return location Object when loading file from internal file storage?

I am working on some way to store a GPS location within the internal file storage and retrieve it on demand in another method.
As I am new to Android I have tried out several ways and decided to go with the FileOutput-/InputStream as it is more comprehensible to me. I am working with the Android location API(http://developer.android.com/reference/android/location/Location.html).
I know that saving a location Object works technically via writing it to a string and later to bytes, but how can I load a saved file and have the saved location object returned?
My code approach:
public void saveCurrentLocation(){ //method works, I can see the saved file in the file explorer
Location currentLoc = gpsClass.getCurrentLocation(); //method within gpsClass that returns current location
try {
FileOutputStream fos = openFileOutput("SaveLoc", Context.MODE_PRIVATE);
fos.write(currentLoc.toString().getBytes());
fos.close();
}
catch(Exception e) { e.printStackTrace();}
}
public void loadSavedLocation() {
Location savedLoc;
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("SaveLoc")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString);
}
gpsClass.update(??);
}
catch(Exception e) {e.printStackTrace();}
}
I'd like to pass the location Object readout in inputString to "gpsClass.update()" which only takes variables of the type Location. Do I have to make the Object serializable and if yes, how?
Many thanks in advance!
Why not persist your location objects into a SQLite database?
Or something like this:
Save:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(your object);
os.close();
Load:
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
YourClass yourObject = (YourClass) is.readObject();
is.close();
return yourObject;
This should get you back on track

The best way to caching json

My application should work not only in online but also in offline mode. For that reason I am considering find the best way for cashing data. I't like use SharedPreference for store data but in android documentation writen Maximum size in characters allowed for a preferences value is 8192. I don't know this is ok or not? I tried to pass out of this idea trying to use FileCashing or sqLite cashing.
So what you think guys what is the best SharedPreference vs FileCashing or vs SqLiteCaching?
Save the json in cache directory as file....
Save:
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
// Save the JSONOvject
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( jsonObject );
out.close();
Retrieve:
// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
JSONObject jsonObject = (JSONObject) in.readObject();
in.close();
I personally like to do this the following way. Create a SQLite database that can hold your content. Then, bind the user interface directly to the database using Adapters & Content Providers that send a notification whenever the data is changed so that the UI can update itself. The last piece in the equation is some form of synchronization service that downloads content and saves it to the database asynchronously. That way, you can manage your data very easily because it is all in the same place. The only part you'll have to figure out for your app is how you decide when to update or remove the data from the database.
Adapters
ContentProvider
Synchronization
Based on your requirement I would recommend SQLite data base.
Since shared preference is suitable for configuration storage - often small data/strings.
File cache is hard to manage, so I recommend SQLite - easy to manage and ability to store mass data.
Considering the performance, if the number of index is not that huge, SQLite database should have the acceptable performance. E.g. only several ms slower than a file cache.
You might be able to combine these two approaches together. Use random access file with index-offset stored in SQLite.
I have used Internal Storage which store file in Application package directory that can't be accessible by not rooted device.
Here the class which can create, read and delete the file
public class ReadWriteJsonFileUtils {
Activity activity;
Context context;
public ReadWriteJsonFileUtils(Context context) {
this.context = context;
}
public void createJsonFileData(String filename, String mJsonResponse) {
try {
File checkFile = new File(context.getApplicationInfo().dataDir + "/new_directory_name/");
if (!checkFile.exists()) {
checkFile.mkdir();
}
FileWriter file = new FileWriter(checkFile.getAbsolutePath() + "/" + filename);
file.write(mJsonResponse);
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readJsonFileData(String filename) {
try {
File f = new File(context.getApplicationInfo().dataDir + "/new_directory_name/" + filename);
if (!f.exists()) {
onNoResult();
return null;
}
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
onNoResult();
return null;
}
public void deleteFile() {
File f = new File(context.getApplicationInfo().dataDir + "/new_directory_name/");
File[] files = f.listFiles();
for (File fInDir : files) {
fInDir.delete();
}
}
public void deleteFile(String fileName) {
File f = new File(context.getApplicationInfo().dataDir + "/new_directory_name/" + fileName);
if (f.exists()) {
f.delete();
}
}
}
You can create, read and delete the file by calling ReadWriteJsonFileUtils class methods as follows:
For creating file:
try {
new ReadWriteJsonFileUtils(context).createJsonFileData(file_name, data);
} catch (Exception e) {
e.printStackTrace();
}
For reading file:
String jsonString = new ReadWriteJsonFileUtils(context).readJsonFileData(file_name);
For deleting single file
new ReadWriteJsonFileUtils(context).deleteFile(file_name);
For deleting all file
new ReadWriteJsonFileUtils(context).deleteFile();

Cannot retrieve all saved objects and show in listView

Hi in my application I am saving string information entered by the user. then serializing those string for retrival later. When I go to open the file to where they are saved I always only get the last string that was entered. Can you see where i am going wrong?
This is the retrival code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lightlist);
adapter = new ArrayAdapter<String>(LightList.this, android.R.layout.simple_list_item_1, lightNames);
refreshBut = (Button)findViewById(R.id.button1);
try {
File file = getCacheDir();
fis = new FileInputStream(new File(file, LightSetup.FILENAME ));
ois = new ObjectInputStream(fis);
String a;
while((a = (String)ois.readObject()) != null){
adapter.add(a);
setListAdapter(adapter);
}
ois.close();
} catch (FileNotFoundException e) {e.printStackTrace();} catch (StreamCorruptedException e){e.printStackTrace();
} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}
}//end onCreate
And this is the serializing code
public void onClick(View arg0) {
String stringData = data.getText().toString();
try {
File file = getCacheDir();
fos = new FileOutputStream(new File(file,FILENAME ));
os = new ObjectOutputStream(fos);
os.writeObject(stringData);
fos.close();
os.close();
} catch (IOException e) {e.printStackTrace();}
Intent i = new Intent("com.Sonny.HCIProject.CreateConfirm");
startActivity(i);
finish();
}//end onClick
You are doing 2 things in a wrong way:
You don't do setListAdapter in a loop, though it might not do you any harm, you don't need to.
The code in your onClick method does not do what you expect, it simply overwrites the data you serialized in the last time. You need to re-construct the objects you serialized in the past using ObjectInputStream and then add your current object to the object graph(I think you need a List), then you can safely serialize all your objects in the file without overwriting your old objects.
Even you can serialize objects like that, I recommend you store your data in SQLite database in stead of using Java serialization, reconstructing a whole lot of unrelated objects just to store another object is overkill. With SQLite, you INSERT a record to the database, and then you can SELECT all records from the database, it is fast and your code will be more succinct.

Categories

Resources