Is SharedPreference a good way to store large chunks of data? - android

I'm currently storing large chunks of user data as JSON string in SharedPreferences. It's working nicely but I wonder if it will cause any problems, for example large app size or memory problems.
Are there any better or recommended way to store large chunks of data in Android app, other than SharedPreferences?

Why don't you just store it in SQLite DB? You can organise the data in a well format.

I think it's not good practice to save large data in SharedPreference. You can store large data in either database or create a read or writable file.
You can create readable & writable file like
Write file by this method
public static void writeToFile(String data,Context context, String fileName) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(fileName+".txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read file by this method
public static String readFromFile(Context context, String fileName) {
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName + ".txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}

Related

When i destroy my app more than 2 times it does not read in the data from txt file, the data is lost

I have an app that saves Strings to textfile when closing the app and reads them in again on starting the app. If i destroy my app 1 time the data reappears and if i destroy it a 2nd time it reappears again. However when i destroy it the 3rd time all the data is lost.
I've tried everything but it just dont work, i've tried using onsavedinstancestate() etc but im lost.. If anyone could point me in the right direction i would really appreciate it!
My readFromFile() and writeToFile() methods:
private void writeToFile(String data, Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("start.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("start.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}

Android Protected variable storage even after factory reset

I'm working on Aosp. I want to keep a variable in the system but When I use a shared preference, the variable is deleted when I perform a Factory reset. I need to change and save the variable I want to keep. Think like a Mac address
You can put all the variables you want to save into a json and save it in internal storage
and you can retrive it whenever you want
example code for read and write
private void saveConfig(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
} }
private String readConfig() {
String data = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
data = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("Error", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("Error", "Can not read file: " + e.toString());
}
return data;
}
and your json can be
{
"variable1": "Value",
"variable2": false
}

Read persistance data when app is removed

i wanted to write and read data into/from a file.
I have searched and founnd these two methods which work perfectly..
public void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
But this file is being deleted when i remove the application from my android device.
Is there any method to save and retrieve data whatever if the user deleted the app ?
You can't. When removing an app, the files in it's local storage are removed.
You can however save your files in an external directory. That way, they aren't deleted when the user removes the app. You can read more about it here.

Android FileOutputStream location save file

I have an app that saves into a file (internal storage) data input by the user and at startup it loads this file and shows the contents. I would like to know: where can I find my file (data.txt)?
In addition, if I input "Hello" and then "World" when I load the file, I see "HelloWorld" in the same line but I want "Hello" and "World" printed on two different lines.
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Thanks.
[UPDATE]
I've inserted "\n" after every input:
user = (EditText) v.findViewById(R.id.username);
writeToFile(user.getText().toString() + "\n");
But when I print my file, they are always on the same line.
Where can I find my file (data.txt)?
You can find the path of the directory, which is created by openFileOutput, by using YourActivity.this.getFilesDir().getAbsolutePath().
But I want "Hello" and "World" printed in two different lines.
Use line.separator after writing a word in a file, for example:
String separator = System.getProperty("line.separator");
outputStreamWriter.write(data);
outputStreamWriter.append(separator);
...
Or you can also use replaceAll to break String into multiple lines:
String separator = System.getProperty("line.separator");
data=data.replaceAll(" ",separator);
I guess you can find it here: data/data/[your package name]/... and regarding writing in two separate lines just add "\n" whenever you need to go to another line.

read file from another activity

I want to read a text file that i had write in another activity using OutputStreamWriter.
this is my readFromFile method in Sale.java:
private int readFromFile(String request) {
int res = 0;
try {
//InputStream inputStream = openFileInput("dalassnums.txt");
File file=new File("dalassnums.txt");
InputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
String s=bufferedReader.readLine();
if(receiveString==request) {
res=Integer.valueOf(s);
break;
}
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
res=0;
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return res;
}
And this is writeToFile method in MainActivity.java:
private void writeToFile2(String numchar) {
try {
//File file=new File("dalassnums.txt");
//OutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter;
if(numchar=="1") outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_PRIVATE));
else outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_APPEND));
for(int k=0; k<imageNums.size();k+=2){
outputStreamWriter.append(imageNums.get(k));
outputStreamWriter.append("\n");
outputStreamWriter.append(imageNums.get(k+1));
outputStreamWriter.append("\n");
}
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
When performing readFromFile, it returns 0 that means file not found;
I read about passing context but i don't know what context to pass; And wondering if there is any other way than passing context.
Any help would be appreciated.
Use : openFileInput in readFromFile, look here for example:
openFileInput() and/or openFileOutput() i/o streams silently failing
Another problem is that this is invalid:
if(numchar=="1")
you should
if(numchar.equals("1"))
otherwise you compare reference values instead content of string

Categories

Resources