getString from a few SharedPreferences file and create listView - android

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

Related

I am trying to pass the values in shared preference from one Activity to another

I am trying to pass the values from one activity to another using shared preference but am getting null value.In the first activity i printed values in console and its getting printed but in that i couldn't retrieve the values.please help me to come out of this error
First activity: values are passed
sharedpreferences.edit().putString("CHECKPASS","changepass").commit();
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
Second Activity: where I am retrieving
Log.d("succ", "reached");
String yourpass = sharedpreferences.getString("CHECKPASS","changepass");
Log.d("succ", "yournext" + yourpass);
if (yourpass.equals("changepass")) {
{
final String foodshared = sharedpreferences.getString("FOOD","NULL");
Log.d("succ", "foodshared" + foodshared);
final String colorshared = sharedpreferences.getString("COLOR", "NULL");
Log.d("succ", "colorshared" + colorshared);
final String buyshared = sharedpreferences.getString("BUY", "NULL");
Log.d("succ", "buyshared" + buyshared);
final String placeshared = sharedpreferences.getString("PLACE", "NULL");
Log.d("succ", "placeshared" + placeshared);
}
Use this code
//For writing data
SharedPreferences.Editor
editor=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE).edit();
editor.putString("CHECKPASS","changepass");
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.apply();
//For Reading Data
SharedPreferences sharedPreferences=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE);
String foodshared = sharedPreferences.getString("FOOD","NULL");
String colorshared = sharedPreferences.getString("COLOR", "NULL");
final String buyshared = sharedPreferences.getString("BUY", "NULL");
final String placeshared = sharedPreferences.getString("PLACE", "NULL");
Also while writing data don't use editor.commit() instead use editor.apply() because it handles data in background.
UPDATE:
in your first activity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);//or MODE_PRIVATE
Editor editor = pref.edit();
editor.putString("CHECKPASS","changepass")
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
IN your secondActivity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
final String foodshared = pref.getString("FOOD",null);
Log.d("succ", "foodshared" + foodshared);
final String colorshared = pref.getString("COLOR",null);
Log.d("succ", "colorshared" + colorshared);
final String buyshared = pref.getString("BUY",null);
Log.d("succ", "buyshared" + buyshared);
final String placeshared = pref.getString("PLACE",null);
Log.d("succ", "placeshared" + placeshared);
edit:
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
STORE THE DATA
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getBoolean("key_name", null); // getting boolean

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.

How to save and fetch integer value in Shared Preference in android?

I want to save and fetch the static integer value of Snow Density in Shared Preferences and change when user select another value in the Single choice.
My Code :
public static int mSnowDensity;
AlertDialog.Builder mABuilder = new AlertDialog.Builder(AAA.this);
final CharSequence mCharSequence[] = { "Low", "Medium", "High" };
mABuilder.setTitle("Set Density of Snow");
mABuilder.setSingleChoiceItems(mCharSequence,
WallpaperServices.mDensitySnow,
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 2) {
mSnowDensity = 90;
/*I Want to save mSnowDensity Value In Shared Preferences */
} else if (which == 1) {
mSnowDensity = 60;
} else {
mSnowDensity = 30;
}
dialog.dismiss();
}
});
You can use shared preferences as follows
//To save
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("SNOW_DENSITY",mSnowDensity);
editor.commit();
//To retrieve
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("SNOW_DENSITY", 0); //0 is the default value
getSharedPreferences() is a method of the Context class. If you are inside a Activity or a Service (which extend Context) you can use it like in this snippet. Else you should get the context using getApplicationContext() and then call getSharedPreferences() method.
For more options you can refer to the documentation at http://developer.android.com/guide/topics/data/data-storage.html#pref
To save in the SharedPreferences:
private final String PREFS_NAME = "filename";
private final String KEY_DENSITY = "den";
Context ctx = getApplicationContext();
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_DENSITY, mSnowDensity);
editor.commit();
To get the value:
Context ctx = getApplicationContext();
String strSavedValue = null;
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
strSavedValue = sharedPreferences.getInt("den", anyDefaultValue);
Save the value in prefrence
private void SavePreferences(String key, int value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
get the value from preference
private void showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int savedPref = sharedPreferences.getInt(key, 0);
}
You can use the key as the shared preference name
Initialization
We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 :- for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true);
editor.putString("key_name", "string value");
editor.putInt("key_name", "int value");
editor.putFloat("key_name", "float value");
editor.putLong("key_name", "long value");
editor.commit();
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
Saving preference is not a troubling task. But if you have a lot of such configurable options you could use a PreferenceActivity and override onSharedPreferenceChanged.
More details here http://developer.android.com/guide/topics/ui/settings.html

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

Show the highscore with shared preferences?

So I'm trying to save the highest score with sharedPreferences but I am running into trouble. I don't know how I would set it up to only take the highest score and display it.
What I have now will only display the current score that the player recieves. Here is what I have so far that doesnt work:
public class GameOptions extends Activity {
int theScore;
TextView highScore;
public static String filename = "MyHighScore";
SharedPreferences spHighScore;
int dataReturned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.in_game_menu);
TextView tvTheScore = (TextView) findViewById(R.id.textView2);
TextView highScore = (TextView) findViewById(R.id.high_score);
Bundle gotScore = getIntent().getExtras();
theScore = gotScore.getInt("scoreKey");
//String thisIsTheScoreToDisplay = theScore.toString();
tvTheScore.setText("SCORE: "+theScore);
spHighScore = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = spHighScore.edit();
editor.putInt("highScoreKey", theScore);
editor.commit();
int dataReturned = spHighScore.getInt("highScoreKey", 0);
highScore.setText("" + dataReturned);
by this you can save your score
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_SCORE_KEY, HIGHEST_SCORE);
prefsEditor.commit();
and get like this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String highestScore = myPrefs.getString(MY_SCORE_KEY, "nothing");
I hope this will help you..
Just before Saving the high score, Fetch the current high score which is saved in the preferences and check whether it is less than the highscore or not. if it is less then save the new one in to Shared preferences or else just leave the past one as highest.

Categories

Resources