How to calculate a key with integer value from SharedPreferences - android

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;

Related

How to change value of a string?

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.

Parsing error in Android

I am storing an array of numbers as string(I get the string from shared preferences) and then trying to parse it.
But when I use parseInt my app crashes. The activity Second is called by Main class.
public class Second extends Activity {
public int[] x = new int[50];
public int[] y = new int[50];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
SharedPreferences data= getSharedPreferences("data",0);
SharedPreferences.Editor editor= data.edit();
StringBuilder str = new StringBuilder();
str.append(data.getString("val", "0")).append(",").append(getIntent().getExtras().getString("thetext"));
String end = str.toString();
editor.putString("val", end);
editor.commit();
//EditText et1= (EditText) findViewById(R.id.editText2);
//et1.
String savedString = data.getString("val", "0");
savedString.replaceAll("\\s","");
String[] st = savedString.split(",");
int i;
for(i=0;i<st.length;i++){
st[i].trim();
Log.d("Debug" , "st["+i+"] = "+st[i]);
x[i] = Integer.valueOf(st[i]);
y[i]=i;}
}
public void lineGraphHandler (View view)
{
LineGraph line = new LineGraph();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
}
Where is it going wrong?
Add a line between these
st[i].replaceAll("\\s","");
Log.d("Debug" , "st["+i+"] = "+st[i])
x[i] = Integer.parseInt(st[i]);
and see that if that is a convertible string or there are some letters accidently inserted that can't be converted to int?

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

Shared Preference Android Storing data

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

getString from a few SharedPreferences file and create listView

First - sorry for my english;) I'am writing profile manager for Android and i want getString from a few SharedPreferences file and create listView. It's part of my code:
private static final String PN = "profile_name";
private EditTextPreference editText;
private SharedPreferences preferences;
public class Profile_Preferences extends PreferenceActivity {
...
private void SavePreferences() {
String text= editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE); //Here we created SharedPreferences file with name "Profile_"+ this what user write in editText
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
preferencesEditor.commit();
Ok. The user was doing a few profile, so we have file for example: Profile_home.xml, Profile_work.xml, Profile_something.xml. Now i wan't create listView with profile name from this file. It's my next Activity:
public class Tab_profiles extends ListActivity {
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
...
public void LoadList() {
//It's a good idea to getString "profile_name" form every xml file with name "Profile_" + "" ?
preferences = getSharedPreferences("Profile_"+ "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
listItems.add(take_profile_name );
adapter.notifyDataSetChanged();
}
But this doesn't work... logcat log:
FATAL EXCEPTION: MAIN
java.land.Null.PointerException
at android.widget.ArrayAdaper.createViewFromResource(ArrayAdapter.java:355)
...
I don't now whoat it's wrong...
Please help my:) Thank you for any answers and sorry for my errors in writing and code;)
There are a few problems in your code:
String text = editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
If a user types "home" in the EditText, you create a preference file called "Profile_home" and save its name in the same file? You need to save the user generated file names in a different file which has a name you know, so you can access it in your code.
Second problem:
preferences = getSharedPreferences("Profile_" + "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
You're trying to open "Profile_" settings. This file does not exist(?). The second parameter of getString must not be null, otherwise you'll add a null-reference to your list of string, which fails. Replace it with an empty string "".
Edit: Here's a little workaround to get all custom named preferences:
private void SavePreferences() {
String text = editText.getText().toString();
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
// increment index by 1
preferencesEditor.putInt("profile_count", preferences.getInt("profile_count", 0) + 1);
// save new name in ProfileNames.xml with key "name[index]"
preferencesEditor.putString("name" + (preferences.getInt("profile_count", 0) + 1), editText.getText());
preferencesEditor.commit();
}
public void LoadList() {
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
List<String> profileNames = new LinkedList<String>();
int profileCount = preferences.getInt("profile_count", 0);
for (int i = 1; i <= profileCount; i++) {
profileNames.add(preferences.getString(name + i, ""));
}
listItems.addAll(profileNames);
adapter.notifyDataSetChanged();
}

Categories

Resources