put default data to edittext in Android - android

Get data from edittext e_1, e_2 to sum up those things, but it rarely put those things together. For instance, I wrote 0 in e_1, and 1 in e_2, pref KEY says '1', but when I wrote nothing in e_1, and 1 in e_2, it makes error and down. So although he/she wrote nothing in e_1, it also have to put '0' in a. What I Have TO DO?
a = Integer.parseInt(e_1.getText().toString());
b = Integer.parseInt(e_2.getText().toString());
SharedPreferences.Editor editor = pref_time.edit();
editor.putInt(KEY, a+b));
editor.commit();

Try this out
String editText1=e_1.getText().toString().trim();
String editText2=e_1.getText().toString().trim();
if((editText1!= null || !editText1.equals("")) && (editText2!=null || !editText2.equals("")))
{
a = Integer.parseInt(editTextData1);
b = Integer.parseInt(editTextData2);
SharedPreferences.Editor editor = pref_time.edit();
editor.putInt(KEY, a+b));
editor.commit();
}

If e_2 is empty, in this line:
b = Integer.parseInt(e_2.getText().toString());
you will get an error because e_2.getText().toString() returns empty string, and it can't be parsed to Integer.
You have to check if it is empty first:
String aText = e_1.getText().toString();
String bText = e_2.getText().toString();
a = TextUtils.isEmpty(aText)? 0 : Integer.parseInt(aText);
b = TextUtils.isEmpty(bText)? 0 : Integer.parseInt(bText);

when edittext is empty it return null to e_1.getText().toString() so first check if edittext is empty or not like this :
String editTextData1 = e_1.getText().toString().trim();
String editTextData2 = e_1.getText().toString().trim();
trim(); is to avoid blank spaces and then check like this to avoid any Exception :
if(editTextData1!="" || editTextData2!=""){
a = Integer.parseInt(editTextData1);
b = Integer.parseInt(editTextData2);
SharedPreferences.Editor editor = pref_time.edit();
editor.putInt(KEY, a+b));
editor.commit();
}

Related

android adding value to sharedpreference string set from null

I am currently trying to save and retrieve array of string into the shared preference in my android apps. The problem is, I haven't add any string into my "set of string", so basically when I tried to retrieve it, it will return null. The problem is, after I get the Set of string, I want to add a string to the set. But it shows error that I can't add a string to a null object. Can someone help me? thanks..
pref = getSharedPreferences("save", MODE_PRIVATE);
Set<String> setId = pref.getStringSet("id", null);
setId.add("admin");
Editor editor = pref.edit();
editor.putStringSet("id", setId);
editor.commit();
You should just return an empty implementation of Set as your default value. For example, an empty ArraySet should work fine:
Set<String> setId = pref.getStringSet("id", new ArraySet<>());
SharedPreferences pref = getSharedPreferences("save", MODE_PRIVATE);
Set<String> setId = pref.getStringSet("id", null);
//The second argument 'null' means if there is no value for key "id", it will return null
if(setId == null){
setId = new HashSet<String>();
}
setId.add("admin");
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet("id", setId);
editor.commit();

How do I update a sharedpreference variable in this way?

I have a sharedpreference var with values like these:
key0,value
key1,value
key3,value
key5,value
key6,value
key7,value
key10,value
What I want to do is to get a new sharedpreference value with items sorted sequentially like these:
key0,value
key1,value
key2,value
key3,value
key4,value
key5,value
key6,value
How do I do this?
Thank you in advanced.
You can use a workaround like this:
SharedPreferences shp = context.getSharedPreferences("yourSHP", MODE_PRIVATE);
//begin & end are to integers. For your case: 0 and 6 to get form key0 to key6
for(int i=begin;i<=end;i++){
String value = shp.getString("key"+i, "defaultValue");
//.....Here you can do whatever you want with your values
}
I hope this would help!!
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry<String, String> entry : testMap.entrySet() )
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();
I did the following workaround. I don't know if there is another faster way to do it:
SharedPreferences shpTH = mContext.getSharedPreferences("PrefsTH", ListadoImagenesSubidasMain.MODE_PRIVATE);
Map<String,?> keysTH = shpTH.getAll();
List<String> imgTH = new ArrayList<String>();
for(Map.Entry<String,?> entry : keysTH.entrySet()){
imgTH.add(entry.getValue().toString());
}
SharedPreferences newPrefsTH = mContext.getSharedPreferences("PrefsTH", ListadoImagenesSubidasMain.MODE_PRIVATE);
newPrefsTH.edit().clear().commit();
int contTH = 0;
for(String item : imgTH){
SharedPreferences.Editor editorTH = newPrefsTH.edit();
editorTH.putString("urlTH" + contTH, item);
editorTH.commit();
contTH++;
}
Firstly I copy all the values to a list. Then I empty the sharedpreferences var and finally I put all the values got from the list filled previously in the empty sharedpreferences.

SharedPreferences string Array not working

I got two Activitys where I want to save and to load a two String[] Array (Sizes are same).
Code in Activity 1 looks like this (load)
SharedPreferences data = getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0;i<array_question.length;++i)
{
array_question[i] = data.getString("FAE"+i, array_question[i]);
array_answer[i] = data.getString("ATW"+i, array_answer[i]);
}
Activity two (save)
SharedPreferences data = getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0;i<Main.array_question.length;++i)
{
editor.putString("FAE"+i,Main.array_question[i]);
editor.putString("ATW"+i,Main.array_answer[i]);
}
editor.commit();
I got no error or crash but also no result.When I want to load them there is nothing... What is my fault ?

Using Shared Preferences for High Score saving

Hell I am trying to make highscore for my project but my code is only saving last value not highest value
How can I store only highest value? here is my code .
This is saving process ->
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView)findViewById(R.id.textscore);
CharSequence textData = outputView.getText();
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
This is Reading process
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");
TextView outputView = (TextView) findViewById(R.id.textread);
You need to check the previously saved value to see which is highest else it you will just save the latest value, not the highest
E.g.
if (textData != null) {
int score = Integer.parseInt(textData.toString());
if(score > prefs.getInt(TEXT_DATA_KEY, 0)) // Or get String, with parse Int.
{
//editor.putString(TEXT_DATA_KEY, textData.toString()); // Should be saved as int
editor.putInt(TEXT_DATA_KEY, score);
editor.commit();
}
}
You need to store a new value only if the existing value in shared preferences is lesser than the new value.
You don't seem to be having this value check in your code
Replace
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
with
if (textData != null) {
if(Integer.parseInt(prefs.getString(TEXT_DATA_KEY, "0")) < Integer.parseInt(outputView.getText())) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
}
First of all why are you saving high scrore as string, use int or float (if you must).
The simplest way is to read high score before saving it and compare to the one you try to save.
You'll want to keep track of your in-game high score. That's easiest done using a number rather than using a text view's string:
int hiScore = 0;
In your startup, perhaps in onCreate(), you'll want to obtain the previous high score:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
When a new score is obtained, you'll want to record it if it's higher than the previous high score:
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}

Check if key exists in Shared Preferences

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);
}

Categories

Resources