i am new android developer.& i am learning by developer.android.com
when i run a project about SharedPreferences.my app close with this error "the application has stopped unexpectedly.please try again"
in my project there is a edittext control.user write something on it & press save button & close the app.when user open it again there is that text in edittext.
this is my code:
SharedPreferences infor = getSharedPreferences( "information", 0 );
txtNumber.setText( infor.getInt( "number", 032 ) );
btnSave.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences infor = getSharedPreferences( "information", 0 );
SharedPreferences.Editor editor = infor.edit();
editor.putInt( "number", Integer.parseInt( txtNumber.getText().toString() ) );
editor.commit();
}
} );
Change here from
txtNumber.setText(infor.getInt("number", 032));
to
txtNumber.setText(infor.getInt("number", 032)+"");
OR
int my = infor.getInt("number", 032);
txtNumber.setText(my+"");
This gives you as a String. And if you want convert int to String using String class then you can use this way.
int my = infor.getInt("number", 032);
String myNumber = String.valueOf(my);
txtNumber.setText(myNumber);
If you want the value of the int as your text, make it a String first.
txtNumber.setText(String.valueOf(infor.getInt("number", 032)));
Related
I'm trying to make "add favorites" button in my app. I can send and get value with sharedpreferences properly, but when I restart the app, favorites are empty again. I guess I need override OnPause method, but I couldn't apply properly. I need help, thanks in advance.
PLAYING RADIO FRAGMENT
public static int incrementedValue = 0;
add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
add_favorites_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("radio_link"+ incrementedValue, radio_play_link);
editor.putString("radio_name" + incrementedValue, radio_name);
editor.putString("listener_number" + incrementedValue, listener_number);
//editor.clear();
editor.commit();
incrementedValue++;
}
});
FAVORITES FRAGMENT
final List<String> radio_name_list = new ArrayList<>();
final List<String> radio_link_list = new ArrayList<>();
final List<String> listener_numbers = new ArrayList<>();
for (int i=0; i<PlayRadioFragment.incrementedValue; i++) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
radio_name_list.add(settings.getString("radio_name" +i, ""));
radio_link_list.add(settings.getString("radio_link" +i, ""));
listener_numbers.add(settings.getString("listener_number" +i, ""));
}
...
then I show them in listview
...
for (int i=0; i<PlayRadioFragment.incrementedValue; i++)
After restarting the app (or Fragment), this incrementedValue will be back to what it was initialized with, probably 0, so you won't load anything from SharedPreferences (not entering the for-loop at all).
Try something like
for (int i=0; i<Integer.MAX_VALUE; i++) {
String s = settings.getString("radio_name" +i, "")
if (TextUtils.isEmpty(s))
break;
} else {
radio_name_list.add(s);
}
You probably also want to avoid overwriting the old favorites after the app restart, so you have to set the incrementedValue after loading the favorites like
incrementedValue = radio_name_list.size();
This is happening because on restarting app the variable named incrementedValue gets value once again as 0 and in for loop conditional statement is not full filling and that's why loop is not executing as expected. To resolve this issue you can do one more thing you need to save the value of incrementedValue in shared preference as well and in for loop testing statement get the updated value from shared preference. Hope that helps you
I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");
This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 6 years ago.
I 'm testing with some iteration with the coding below, with help of Stringbuilder and want to directly save the outcome to Sharedpreference.
save2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
int i;
int n = 10;
StringBuilder outoutcome = new StringBuilder();
for (i = 0; i <= n; i++) {
outoutcome.append(i + "\n");
}
SharedPreferences sharedPreferences = getSharedPreferences("data1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("outcome1", outoutcome.toString());
}
}
*I also tried editor.putString("outcome1", String.valueOf(outoutcome)); but unfortunately cannot.
for the retrieve of data in another activity, I had tried using coding below :
public static final String DEFAULT = "";
final SharedPreferences sharedPreferences = getSharedPreferences("data1", Context.MODE_PRIVATE);
final String out1 =sharedPreferences.getString("outcome1", DEFAULT);
resultout.setText("Saved data is " + out1 );
but the coding above not working. Then, I searched and found this , tried the code as below but still not working.
final String[] getout1= out1.split(",");
resultout.setText("Saved data is " + getout1 );
Can anyone help here? Thank you in advanced !
You have to use apply() or commit() to save the changes.
editor.apply();
or
editor.commit();
I want to save totalBalance in this activity to SharedPreferances and the retrive it in another class.
so i want totalbalance to be displayed in another activities in same application...
if possible also edit it in other activites...
please help... thanks
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
// Genrating random number Random number
Random rn = new Random();
randomNumber = (int) rn.nextInt(9) + 1;
// changes textView1 equals to random number
textView1.setText("Random Number is "
+ Integer.toString(randomNumber));
button1.setText("Play Again");
// Matching random number to ArrayList
if (positive_IDs.contains(randomNumber)) {
// if matched then changes textView2 to Matched Number
textView2.setText("Number: "
+ Integer.toString(randomNumber) + " Matched");
totalBalance = totalBalance + winingPrize;
textView5.setText("Total Balance = Rs: "
+ String.format("%.2f", totalBalance));
}
}
try this,
public void saveValue(String lock, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("Value", lock);
editor.commit();
}
public String getValue(Context context) {
SharedPreferences savedvalue = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedvalue.getString("Value", "");
}
Save Value as Following
int Value;
private void saveValues(){
SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE);
SharedPreferences.Editor editor = readSP.edit();
editor.putString("String", Value);
editor.commit();
}
Retrive value in any of your Class As following
int value;
private void getSavedValue()
{
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE);
value=settings.getString("String", "");
}
// try this
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("balance", String.format("%.2f", totalBalance));
editor.commit();
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
String total = sharedPreferences.getString("balance");
Use following code to retrive your value from SharedPreference,write this in other class where you want to retrive value of total balance
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
Editor edit1 = remembermepref.edit();
edit1.putInt("totalbalance_key",totalBalance);
edit1.commit();
and to store total balance into ShardPreference use in your activity:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int totalbalance = pref.getInt("totalbalance_key");
Now use totalbalance way you want.
Most important thing is to check whether you have used same key to restore as well as tostore the value in SharedPreference
Hope this helps..
I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.
Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if
the preference exists in the preferences, otherwise false.
Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}
Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}
I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.
preferences = getSharedPreferences("text", 0);
Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
Set<String> keys = entries.keySet();//set all key entries into an array of string type
//first option
if(keys.isEmpty()){
//do your staff here
}
//second option
if(keys.size()==0){
//this shows that it is empty as well
//do your staff here
}
//Below is extra
//If you want to get the names of each keys also, you can use
//For each loop as well
//Go through the set of keys
for (String key : keys) {
String keyName = key;//get each key name
}
LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);
public void SaveRuns(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}