I am having trouble storing data using shared preference.
If I have the following code and try to run it, it crashes. I don't know why though.
public class Favorites extends Activity{
private static final String TAG_NAME = "title";
private static final String TAG_URL = "href";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
Intent in = getIntent();
TextView favName = (TextView) findViewById(R.id.textView1);
String FILENAME = "settings";
String string = "hello world!";
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
editor.putFloat("keyFloat", 1.0f);
editor.putInt("keyInt", 1);
editor.putLong("keyLong", 1000000L);
editor.putString("keyString", "Hello Android");
editor.commit();
boolean dataFromPrefBool = pref.getBoolean("keyBoolean", false);
float dataFromPrefflaot = pref.getFloat("keyFloat", 0.0f);
int dataFromPrefInt = pref.getInt("keyInt", 0);
long dataFromPrefLong = pref.getLong("keyLong", 0);
String dataFromPrefString = pref.getString("keyString", null);
favName.setText(dataFromPrefInt);
}
Why is nothing happening? These are just dummy values but still nothing happens
change
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
to
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_WRITABLE);
Try this, maybe it is due to null pointer exception.I am not sure.
public class Favorites extends Activity{
private static final String TAG_NAME = "title";
private static final String TAG_URL = "href";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
Intent in = getIntent();
TextView favName = (TextView) findViewById(R.id.textView1);
String FILENAME = "settings";
String string = "hello world!";
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
editor.putFloat("keyFloat", 1.0f);
editor.putInt("keyInt", 1);
editor.putLong("keyLong", 1000000L);
editor.putString("keyString", "Hello Android");
editor.commit();
boolean dataFromPrefBool = pref.getBoolean("keyBoolean", null);
float dataFromPrefflaot = pref.getFloat("keyFloat", null);
int dataFromPrefInt = pref.getInt("keyInt", null);
long dataFromPrefLong = pref.getLong("keyLong", null);
String dataFromPrefString = pref.getString("keyString", null);
if(dataFromPrefInt==null)
{
favName.setText("");
}
else
{
favName.setText(dataFromPrefInt);
}
}
}
Related
String stored contains "1.0" in it. and I want to increase its value by 0.5, every time I press the button. But instead, my output becomes "1.00.5". How do I fix this?
String stored = userspeed.getText().toString();
String speedplus = stored + 0.5;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
UPDATE
public class ProgramActivity extends AppCompatActivity {
EditText userspeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
userspeed = (EditText) findViewById(R.id.userspeed);
//load values
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String stored = preferences.getString("user_speed", "1.0");//default
userspeed.setText(stored, TextView.BufferType.EDITABLE);
}
public void adduserspeed(View view) {
String stored = userspeed.getText().toString();
double storedValue = Double.parseDouble(stored);
String speedplus = String.valueOf(storedValue +0.5f);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
}
}
First, you need to convert your string value to a float value, then perfom the add operation and finally convert the result to a string so you can store as a string in shared preferences.
final String stored = userspeed.getText().toString();
final float storedValue = Float.parseFloat(stored);
final String speedplus = String.valueOf(storedValue + 0.5f);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
If you want to use a double value, simply replace first lines as the follows:
final String stored = "1.0";
final double storedValue = Double.parseDouble(stored);
final String speedplus = String.valueOf(storedValue + 0.5d);
UPDATE
Your problem is that within adduserspeed(View view) method your are not retrieving the stored value from preferences, your are retrieving from the EditText, and you are not updating that EditText value, so every time you execute adduserspeed(View view) method, the value you are storing on preferences is 1.0 + 0.5, because you EditText value is 1.0 until you re-open your app. When you re-open your app your EditText value is 1.5 and so on...
I have improved your code and now works well, anyway, do not just copy my code, try to understand it so you can learn.
public class MainActivity extends AppCompatActivity {
private EditText userSpeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.userSpeed = (EditText) findViewById(R.id.userspeed);
setUserSpeedText();
}
public void adduserspeed(View view) {
final String stored = getUserSpeedValue();
final double storedValue = Double.parseDouble(stored);
final String speedPlus = String.valueOf(storedValue + 0.5f);
setUserSpeedValue(speedPlus);
setUserSpeedText();
}
private String getUserSpeedValue() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString("user_speed", "1.0");
}
private void setUserSpeedValue(final String newSpeedValue) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", newSpeedValue);
editor.apply();
}
private void setUserSpeedText() {
if (null != this.userSpeed) {
this.userSpeed.setText(getUserSpeedValue());
}
}
}
You can also use double like:
String speedplus = (Double.parseDouble(stored)+0.5).toString();
Try parsing stored i.e. 1.0 as Double and then add 0.5d
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
Final code
String stored = userspeed.getText().toString();
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
String stored = userspeed.getText().toString();
float speedplus = Float.parseFloat(stored) + 0.5;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("user_speed", speedplus);
editor.apply();
Parse the string value to int and then do mathematical operation. Otherwise string concatenation will happen.
The quickest hack would be:
String speedplus = String.valueOf(Float.parseFloat(stored) + 0.5F);
However, your next question will no doubt be "Why is my result 1.499999999?", which is answered here in detail.
I want to calculate 2 values with key from SharedPreferences.
This is my code
This is my first activity
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A1, option_scoreA1);
editor.commit();
Intent intent = new Intent(QuestionActivity.this, SecondActivity.class);
startActivity(intent);
This is my second activity
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A2, option_scoreA4);
editor.commit();
Intent intent = new Intent(SecondActivity.this, TestFinalActivity.class);
startActivity(intent);
This is my final activity
protected QuestionActivity activity1;
protected SecondActivity activity2;
String c = activity1.A1;
String b = activity2.A2;
String A = c + b ;
#Bind(R.id.hasil)
TextView hasil;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
total();
}
public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(A);
}
I want to totalize each value from key A1 and A2. But what i got was the key, not the value when I totalize them.
Thank you
It is because you add or concatenate the keys into variable A. And you want to calculate the int so you should better put the total result into float or int data type, right?
Do something as shown below
very fist of all make two keys as your instance filed in QuestionActivity class
public static final String KEY_A = "ka";
public static final String KEY_B = "kb";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int a = sharedPreferences.getInt(QuestionActivity.KEY_A, 0);
int b = sharedPreferences.getInt(QuestionActivity .KEY_B, 0);
A = a+b;
total();
}
and since it is integer, you need to cast the result into string format.
public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(String.valueOf(A));
}
SharedPreference starting guide
access to value in SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int value1 = preferences.getInt("your key", default_value);
int value2 = preferences.getInt("your key", default_value);
First create sharedpreferences and then get values of your keys.
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
int c = pref.getInt(A1, 0) // here A1 is the key and 0 is default value
int b = pref.getInt(A2, 0) // here A2 is the key and 0 is default value
int A = c + b;
I saved more tasks, but while retrieving the tasks are displayed one by one. I need to display all the tasks.
This is my code to store the tasks.
public static int i=0;
task_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String prefs_name = null;
SharedPreferences remind = getApplicationContext().getSharedPreferences(prefs_name,0);
SharedPreferences.Editor taskedit=remind.edit();
taskedit.putString("taskname"+i, edit_task.getText().toString().trim());
taskedit.putString("taskdate"+i, edit_date.getText().toString().trim());
taskedit.putString("tasktime"+i, edit_time.getText().toString().trim());
taskedit.apply();
i++;
Toast.makeText(getApplicationContext(), "Task added", Toast.LENGTH_SHORT).show();
Intent ret_view=new Intent(Add.this,TaskActivity.class);
startActivity(ret_view);
}
});
This is the code for retreiving..
public static int i=0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
TextView tv=(TextView)findViewById(R.id.textView2);
String prefs_name = null;
SharedPreferences remind= getApplicationContext().getSharedPreferences(prefs_name,0);
remind.getAll();
String viewtask=remind.getString("taskname"+i, "");
String viewdate=remind.getString("taskdate"+i, "");
String viewtime=remind.getString("tasktime"+i, "");
tv.setText(new StringBuilder().append(viewtask).append(" ").append(viewdate).append(" ").append(viewtime));
i++;
try it like this
String taskname = ("taskname"+i);
String taskdate = ("taskdate"+i);
String tasktime = ("tasktime"+i);
taskedit.putString(taskname, edit_task.getText().toString().trim());
taskedit.putString(taskdate, edit_date.getText().toString().trim());
taskedit.putString(tasktime, edit_time.getText().toString().trim());
Retrieving
String taskname = ("taskname"+i);
String taskdate = ("taskdate"+i);
String tasktime = ("tasktime"+i);
String viewtask=remind.getString(taskname, "");
String viewdate=remind.getString(taskdate, "");
String viewtime=remind.getString(tasktime, "");
and do exactly same when you are retrieving data from sharePreference.
That code works for me . Hope this will help you as well
Cheers
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
Can anyone tell where i am wrong because its just a simple process but how its not retrieving the values i cant understand and do conditional check over the string variable...
Activity A:-
EditText e = (EditText) findViewById(R.id.editText1);
EditText e1 = (EditText) findViewById(R.id.editText2);
EditText e2 = (EditText) findViewById(R.id.editText3);
EditText e3 = (EditText) findViewById(R.id.editText4);
EditText e4 = (EditText) findViewById(R.id.editText5);
EditText e5 = (EditText) findViewById(R.id.editText6);
EditText e6 = (EditText) findViewById(R.id.editText7);
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("text", e.getText().toString());
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs1", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor1 = myPrefs1.edit();
editor1.putString("text1", e1.getText().toString());
SharedPreferences myPrefs2 = getSharedPreferences("myPrefs2", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor2 = myPrefs.edit();
editor2.putString("text2", e2.getText().toString());
SharedPreferences myPrefs3 = getSharedPreferences("myPrefs3", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor3 = myPrefs3.edit();
editor3.putString("text3", e3.getText().toString());
SharedPreferences myPrefs4 = getSharedPreferences("myPrefs4", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor4 = myPrefs4.edit();
editor4.putString("text4", e4.getText().toString());
SharedPreferences myPrefs5 = getSharedPreferences("myPrefs5", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor5 = myPrefs5.edit();
editor5.putString("text5", e5.getText().toString());
SharedPreferences myPrefs6 = getSharedPreferences("myPrefs6", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor6 = myPrefs6.edit();
editor6.putString("text6", e6.getText().toString());
Activity B:-In this activity i am accessing the values and doing the conditional check but only else condition is getting executed on both cases
public class CheckActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String restoredText = myPrefs.getString("text", "");
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs1",Context.MODE_PRIVATE);
String restoredText1 = myPrefs1.getString("text1", "");
SharedPreferences myPrefs2 = getSharedPreferences("myPrefs2",Context.MODE_PRIVATE);
String restoredText2 =myPrefs2.getString("text2", "");
SharedPreferences myPrefs3 = getSharedPreferences("myPrefs3",Context.MODE_PRIVATE);
String restoredText3 =myPrefs3.getString("text3", "");
SharedPreferences myPrefs4 = getSharedPreferences("myPrefs4",Context.MODE_PRIVATE);
String restoredText4 = myPrefs4.getString("text4", "");
SharedPreferences myPrefs5 = getSharedPreferences("myPrefs5",Context.MODE_PRIVATE);
String restoredText5 = myPrefs5.getString("text5", "");
SharedPreferences myPrefs6 = getSharedPreferences("myPrefs6",Context.MODE_PRIVATE);
String restoredText6 = myPrefs6.getString("text6", "");
Intent i1 = new Intent();
if((restoredText.length()>1)&&(restoredText1.length()>1)&&(restoredText2.length()>1)&&(restoredText3.length()>1)&&(restoredText4.length()>1)&&(restoredText5.length()>1)&&(restoredText6.length()>1))
{
i1.setClass(this,ShpoonkleActivity.class);
}
//if((restoredText.length()==0)||(restoredText1.length()==0)||(restoredText2.length()==0)||(restoredText3.length()==0)||(restoredText4.length()==0)||(restoredText5.length()==0)||(restoredText6.length()==0))
else
{
i1.setClass(this,Test.class);
}
startActivity(i1);
finish();
}
}
you should commit your data with editor.commit();
NB: in your case , there is no need to use a lot of instances of SharedPreferences , you need just one instance, and then put all your Strings into it , and commit
you should use
editor.commit();
for your changes to be preserved. and also, you need not use different files to store various strings, you can store all the strings in the same shared preferences file.
actually saving edittext's text was creating ambiguity and hence was not executing well so i did this as shown below:-
Activity B:-
protected void onPause() {
EditText ed = (EditText)findViewById(R.id.editText1);
EditText ed1 = (EditText)findViewById(R.id.editText2);
EditText ed2 = (EditText)findViewById(R.id.editText3);
EditText ed3 = (EditText)findViewById(R.id.editText4);
EditText ed4 = (EditText)findViewById(R.id.editText5);
EditText ed5 = (EditText)findViewById(R.id.editText6);
EditText ed6 = (EditText)findViewById(R.id.editText7);
super.onPause();
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("text", ed.getText().toString());
editor.putString("text1", ed1.getText().toString());
editor.putString("text2", ed2.getText().toString());
editor.putString("text3", ed3.getText().toString());
editor.putString("text4", ed4.getText().toString());
editor.putString("text5", ed5.getText().toString());
editor.putString("text6", ed6.getText().toString());
editor.commit();
}
Activity A:-
public class CheckActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String restoredText = myPrefs.getString("text", "");
String restoredText1 = myPrefs.getString("text1", "");
String restoredText2 =myPrefs.getString("text2", "");
String restoredText3 =myPrefs.getString("text3", "");
String restoredText4 = myPrefs.getString("text4", "");
String restoredText5 = myPrefs.getString("text5", "");
String restoredText6 = myPrefs.getString("text6", "");
Intent i1 = new Intent();
if((restoredText.length()>0)&&(restoredText1.length()>0)&&(restoredText2.length()>0)&&(restoredText3.length()>0)&&(restoredText4.length()>0)&&(restoredText5.length()>0)&&(restoredText6.length()>0))
{
i1.setClass(this,ShpoonkleActivity.class);
}
//if((restoredText.length()==0)||(restoredText1.length()==0)||(restoredText2.length()==0)||(restoredText3.length()==0)||(restoredText4.length()==0)||(restoredText5.length()==0)||(restoredText6.length()==0))
else
{
i1.setClass(this,Test.class);
}
startActivity(i1);
finish();
}
}
And it works awesome ...thnx..