Set space/blank/ null value to default value - android

I'm new in developing Android application and currently I'm developing a android software that require user to input quite amount of data and save it on sharedPreferences as database. Here is my coding:
public static final String DEFAULT= "NONE";
When saving the data input by the user, a portion of coding are as shown at the following:
public void OnClickSave(){
button17=(Button)findViewById(R.id.button17);
button17.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.name);
material = (EditText) findViewById(R.id.material);
type = (EditText) findViewById(R.id.type);
proper1 = (EditText) findViewById(R.id.proper1);
p1 = (EditText) findViewById(R.id.p1);
p2 = (EditText) findViewById(R.id.p2);
p3 = (EditText) findViewById(R.id.p3);
po1 = (EditText) findViewById(R.id.po1);
po2 = (EditText) findViewById(R.id.po2);
po3 = (EditText) findViewById(R.id.po3);
c1 = (EditText) findViewById(R.id.c1);
c2 = (EditText) findViewById(R.id.c2);
c3 = (EditText) findViewById(R.id.c3);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name.getText().toString());
editor.putString("material", material.getText().toString());
editor.putString("type", type.getText().toString());
editor.putString("proper1",proper1.getText().toString());
editor.putString("p1", p1.getText().toString());
editor.putString("p2", p2.getText().toString());
editor.putString("p3", p3.getText().toString());
editor.putString("po1", po1.getText().toString());
editor.putString("po2", po2.getText().toString());
editor.putString("po3", po3.getText().toString());
editor.putString("c1", c1.getText().toString());
editor.putString("c2", c2.getText().toString());
editor.putString("c3", c3.getText().toString());
editor.commit();
Toast.makeText(MainActivity.this, "Saved!!!", Toast.LENGTH_LONG).show();
}
}
);
}
For loading of data,
public void OnClickLoad(){
button38=(Button)findViewById(R.id.button38);
button38.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", DEFAULT);
String material = sharedPreferences.getString("material", DEFAULT);
String type = sharedPreferences.getString("type", DEFAULT);
String proper1 = sharedPreferences.getString("proper11", DEFAULT);
String p1 = sharedPreferences.getString("p1", DEFAULT);
String p2 = sharedPreferences.getString("p2", DEFAULT);
String p3 = sharedPreferences.getString("p3", DEFAULT);
String po1 = sharedPreferences.getString("po1", DEFAULT);
String po2 = sharedPreferences.getString("po2", DEFAULT);
String po3 = sharedPreferences.getString("po3", DEFAULT);
String c1 = sharedPreferences.getString("c1", DEFAULT);
String c2 = sharedPreferences.getString("c2", DEFAULT);
String c3 = sharedPreferences.getString("c3", DEFAULT);
}
}
);
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity12.this);
a_builder.setMessage(
"Data input 1:"+ name + "\n"+ material +"\n"+ type +"\n"+ proper1 +"\n"+
p1+ "\n"+p2 +"\n"+ p3 + "\n"+po1 +"\n"+ po2 +"\n"+po3 +"\n"+ s1 +"\n"+s2 +"\n"+s3 + "\n" )
.setCancelable(false)
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setNegativeButton("Return", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
;
AlertDialog alert= a_builder.create();
alert.setTitle("Checking");
alert.show();
}
When the user didn't input any data and didn't press the save button, the data shows will be the DEFAULT data, which is NONE as set.
public static final String DEFAULT= "NONE";
However, when the user didn't input any data and press the save button, the output of the data become blank.
Here's the question, is that possible to set the blank input or space input to DEFAULT data? (Means when user didn't insert any input(or space only) and save, corresponding data loaded is NONE.)
I been refer to some solution similar to this ,knowing that I can do it manually 1 by 1, but is that any alternative solution to make it faster and put into the Sharepreferances?
Thank in advance for anyone who concern and help ! Sorry for my poor language.

However, when the user didn't input any data and press the save button, the output of the data become blank.
It's empty string "".
Here's the question, is that possible to set the blank input or space input to DEFAULT data?
You are doing this wrong way. You should not put the entry into shared preferences, when there's noting entered. Then during read you would get your DEFAULT. So make helper like
protected void storeData(SharedPreferences.Editor editor, String key, EditText et) {
String content = et.getText().toString();
// is there any content? Empty string is no content
if ("".equals(content)) {
// ensure we do not retain previously stored value for that key
editor.remove(key);
} else {
// save new data in the storage
editor.putString(key, content);
}
}
and then replace all the calls you have that put string data directly, like this one:
editor.putString("p1", p1.getText().toString());
with calls to our helper:
storeData(editor, "p1", p1);

Related

how to make the number stay in the latest number instead of going back to the default?

my TxnNo(A0010001) came from Unitcode(A001) + LastTxnNo(0001). This is my button click.
Db_Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Model txn = new Model();// initialize your model class first
BigDecimal paidAmt = new BigDecimal(D_Amount.getText().toString()).setScale(2, RoundingMode.HALF_UP);
txn.setName(D_Name.getText().toString());
txn.setTxnNo(D_Txn.getText().toString());
txn.setTxnDate(Select_Date.getText().toString());
txn.setAmount(paidAmt);
txn.setDescription1(D_Description.getSelectedItem().toString());
txn.setDescription2(Ds_Description.getText().toString());
try {
SQLiteDatabase db = mSQLiteHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName());
cv.put("TxnNo", txn.getTxnNo());
cv.put("TxnDate", txn.getTxnDate());
cv.put("Amount", txn.getAmount().toPlainString());
cv.put("Description1", txn.getDescription1());
cv.put("Description2", txn.getDescription2());
db.insert("Donation_Details", null, cv);
db.close();
increaseNumber++;
populate_TxnNo();
Toast.makeText(Donation_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
I put increaseNumber++; to make sure it will increase automatically. So Everytime I click the button. the number will change "A0010001" to "A0010002" and so on. But once I leave this page, and go in again. It will back to "A0010001". How to make it stay at the latest number instead of going back to "A0010001".
This is the method to set the numbering.
private void populate_TxnNo() {
int lastNumber = Integer.valueOf(txn.getLastTxnNo());
lastNumber = lastNumber + increaseNumber;
String stringLast = String.format("%04d", lastNumber);
String txnNo = txn.getUnit_Code() + stringLast;
//increaseNumber++;
D_Txn.setText(txnNo);
}
UPDATE
So for me to understand the Shared preference I put those code to the button new.
Db_New.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increaseNumber++;
populate_TxnNo();
}
});
But I don't know how to use Shared preference even though I see the example of code... Can anyone explain it for me? How to use this code?
SharedPreferences prefs;
SharedPreferences.Editor edit;
prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
edit=prefs.edit();
edit.putString("yourKey", txnNo);
edit.commit();
String txnNo = prefs.getString("yourKey", null);
Firstly, declare these two variables
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int count;
Next add these in onCreate method
sharedPreferences = getApplicationContext().getSharedPreferences("counters", MODE_PRIVATE);
editor = sharedPreferences.edit();
count = sharedPreferences.getInt("counter", 0);
Finally modify populate_TxnNo methods
private void populate_TxnNo() {
int a = count++;
int lastNumber = Integer.valueOf(txn.getLastTxnNo());
lastNumber = lastNumber + a;
String stringLast = String.format("%04d", lastNumber);
String txnNo = txn.getUnit_Code() + stringLast;
D_Txn.setText(txnNo);
editor.putInt("counter", ++a);
editor.commit();
}
Try using Shared Preference
these two lines before onCreate()
SharedPreferences prefs;
SharedPreferences.Editor edit;
these two lines in onCreate()
prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
edit=prefs.edit();
and on onPause() save the string
#Override
protected void onPause() {
super.onPause();
edit.putString("yourKey", txnNo);
edit.commit();
}
and to access it back simply write in onStart
#Override
protected void onStart() {
super.onStart();
String txnNo = prefs.getString("yourKey", null);
}
simply add yourNumber to shared preferences
int yourNumber;
SharedPreferences number = getSharedPreferences("number", MODE_PRIVATE);
to save your number
number.edit.putInt("number",yourNumber).apply;
and read the number next time
int savedNumber = number.getInt("number",0);

can increase number for string using for loop? Android studio

is there any way can do a loop for string?
This is my Database data. I can't use Int because It won't allow 0 to be the first character.
This is my data. I have two tables. "Donation_Details" TxnNo data comes from "Information" 'unitcode + lastTxnNo'
How to increase the number to be '0012' after I click the button save? I have to check every single time when users click the button save, It will auto increase automatically, to make sure the user know how many transaction have been created.
this is my CODE.
BigDecimal paidAmt = new BigDecimal(D_Amount.getText().toString()).setScale(2, RoundingMode.HALF_UP);
Model txn = new Model(); // initialize your model class first
txn.setName(D_Name.getText().toString());
//txn.setTxnNo(D_Txn.getText().toString());
txn.setTxnDate(Select_Date.getText().toString());
txn.setAmount(paidAmt);
txn.setDescription1(D_Description.getSelectedItem().toString());
txn.setDescription2(Ds_Description.getText().toString());
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName()); // get the entered name here.
//cv.put("TxnNo", txn.getTxnNo());
cv.put("TxnDate", txn.getTxnDate());
cv.put("Amount", txn.getAmount().toPlainString());
cv.put("Description1", txn.getDescription1());
cv.put("Description2", txn.getDescription2());
db.insert("Donation_Details", null, cv);
db.close();
Toast.makeText(Donation_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Thanks in advance.
Try this
cv.put("TxnNo", String.format("%04d", txn.getTxnNo()));
It will have a zero-padding with a length of 4.
Edit
int i; // declare as global value
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
i = ++i;
txn.setTxnNo(i);
cv.put("TxnNo", String.format("%04d", txn.getTxnNo()));
}
});
To prevent the number back to 0 , you need to use SharedPreferences.
SharedPreferences app_preferences =PreferenceManager.getDefaultSharedPreferences(Activity1.this);
SharedPreferences.Editor editor = app_preferences.edit();
int i = app_preferences.getInt("key",0);
Button clickButton = (Button) findViewById(R.id.clickButton);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
i = ++i;
txn.setTxnNo(i+""); // set to Model class
cv.put("TxnNo", String.format("%04d", txn.getTxnNo())); // save to database and padding 0 to left
editor.putInt("key",i).commit();
}
});
you can do it using shared preference,
in your case, initialise an int value,
int id;
SharedPreferences sharedpreferences = getSharedPreferences("data-Info", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key",id++);
editor.commit();
now, to get that value using preference,
id=sharedpreferences.getInt("key", 0);
this way you don't need to care about your id.
in case you just want to increase the value of the integer just do this
String num = /*get the value from db*/;
int num1 = Integer.parseInt(num+"");
num = num1+"";
//then save the string num to the db.
but if u want to save the value in the device the sahred preferences is the way to go.
private SharedPreferences pref;
pref = getApplicationContext().getSharedPreferences("valuestorage", 0); // 0 - for private mode
String num = /*get the value from db*/;
int num1 = Integer.parseInt(num+"");
num = num1+"";
pref.edit().putString("lastno",num).apply();
//then save the string num to the db.
now you need not call the database everytime only call it if the pref value is null.
so now you'll check the value from pref increment it and save it in db again.
here is how:
considering the data is present in pref
String aa = pref.getString("lastno","");
if(!aa.equals(""))
{
String num = aa;
int num1 = Integer.parseInt(num+"");
num = num1+"";
pref.edit().putString("lastno",num).apply();
//then save the string num to the db.
}
https://developer.android.com/training/data-storage/shared-preferences

Save user input to SharedPrefernces and set Value to EdiText

I want to save user input to SharedPreferences when i click a button so that when a user launches the activity again the user input is set to the EditText and TextView. I already have a sharedPreferences File created that i save some text to in a previous activity.
I want update the SharedPreferences File with another details from this new activity that i created.
This is code for creating and saving to SharedPreferences
private SharedPreferences prefs;
public static final String PREF_FILE_NAME = "AuthUser";
prefs = this.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
txtDate = (TextView) findViewById(R.id.txtDate);
addIdButton = (Button) findViewById(R.id.btnAddId);
addIdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.apply();
}
});
This is my code to set the value from shared preferences to EditText and TextView
#Override
public void onStart(){
super.onStart();
File f = new File(PREF_FILE_NAME);
if (f.exists()){
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
}
}
File f = new File(PREF_FILE_NAME); just has the name of the preference so
f.exists() will always returns false
Solution : Remove
File f = new File(PREF_FILE_NAME);
if (f.exists()){
because if you don't have any value then simply use the default value
#Override
public void onStart(){
super.onStart();
//File f = new File(PREF_FILE_NAME); // not a right path
//if (f.exists()){ // false
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
//}
}
Alternatively you can use contains
To Achive your work:
First of all try to understand difference between onCreate() and onStart() method of Activity in android, follow following url: https://developer.android.com/guide/components/activities/activity-lifecycle.html
-: use onCreate() method instead of onStart() for setting ui variables;
secondly change in your code like:
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.commit();
}
just remove if (f.exists()) condition from Onstart() because File f = new File(PREF_FILE_NAME); just has the name of the preference so f.exists() will always returns false
like below code
#Override
public void onStart(){
super.onStart();
/* File f = new File(PREF_FILE_NAME);
if (f.exists()){*/
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
}

android storing values in array or list without overwrite

Am just wondering if there is a way to save data into a text file without being overwritten.
Currently i am using sharedpreferences and it overwrites the data which is okay but coinciding with this, i want somewhere where i can keep record of the value before being overwritten in a list or column form.
So it goes something like this:
60, 65, 70..etc
The values are stored one after another without being overwritten. I am thinking of doing this locally in a text file which can be read as well.
I am doing this so i can create a stats page or something like that.
I hope someone can help me find a solution.
My code:
public class workout extends Activity {
TextView weightresultText, newweightresultText, difficultyrating;
Boolean male, strength;
double newweight, newweight1;
int weight, age;
Button button, button4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
button = (Button) findViewById(R.id.button);
button4 = (Button) findViewById(R.id.button4);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
weight = Integer.parseInt(sharedPreferences.getString("storedweight", "Your Weight"));
age = Integer.parseInt(sharedPreferences.getString("storedage", "Your Age"));
male = sharedPreferences.getBoolean("is_male", false);
strength = sharedPreferences.getBoolean("is_strength", false);
weightresultText = (TextView) findViewById(R.id.weightresultLabel);
newweightresultText = (TextView) findViewById(R.id.newweightresultLabel);
difficultyrating = (TextView) findViewById(R.id.difficultylevel);
if (sharedPreferences.getBoolean("firstrun", true)) {AgeCalculation();
sharedPreferences.edit().putBoolean("firstrun", false).commit();}
AfterFirstLaunch();
}
public void SaveWeight(){
savePreferences("storednewweight", (Double.toString(newweight)));
}
//Should only happen on first launch.
public void AgeCalculation() {
if (strength == true){
if (male == true && age >= 18) {
newweight = (weight * 0.8);
}
if (male == true && age >= 30) {
newweight = (weight * 0.6);
}
if (male == true && age >= 50) {
newweight = (weight * 0.4);
}
if (male == true && age >= 70) {
newweight = (weight * 0.2);
}
if (male == true && age > 80) {
newweight = (weight * 0.1);
}
if (male == false && age >= 20 ){
newweight = (weight * 0.3 );
}
weightresultText.setText(Double.toString(newweight));
SaveWeight();
}}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
// On every other launch, it is based on button, the newweight is saved and loaded each time.
public void buttonClick1(){
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 5;
//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight1)));
//save to shared preference, and load value on new launch?
//also store into local database for review later.
difficultyrating.setText("1");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
public void buttonClick4(){
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 10;
//saves value into sharedpreference
//save to text file in array
savePreferences("storednewweight", (Double.toString(newweight1)));
difficultyrating.setText("2");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
//runs on every other launch
public void AfterFirstLaunch(){
buttonClick1();
buttonClick4();
//receive value on other launches and show on field.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
weightresultText.setText(newweight);
}
}
For something like this, where you're storing multiple entries of similar data, you'd really want to use an SQL database with a content provider. You'd just create new rows for each entry.
For writing into a textFile with overwritten use the following code
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
File logFile = new File(path + "filename.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append("Message");
buf.newLine();
buf.flush();
buf.close();
Make sure you have permission defined in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

Categories

Resources