Shared Preference Force close - android

My Program gets Force closed when i execute this code.. can anyone tell me..whats the solution..
package com.test.sharedPreferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Sharedpreference extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
TextView tv = new TextView(this);
tv.setText(dataFromPrefInt);
setContentView(tv);
}
}

I would use Context.MODE_PRIVATE

When you write getInt....that means you are opening the editor.
So first open the editor and den write the getInt code.
SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
int dataFromPrefInt = pref.getInt("keyInt", 0);

Here's your problem. You're opening up the shared preferences using MODE_WORLD_READABLE (ie, read-only mode) here:
SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
and then following that up by trying to EDIT the shared preferences here:
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
...
editor.commit();
Doesn't something about that seem incorrect to you? If not, here's the documentation to clarify things.

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

SharedPreferences doesn't save value

I have this code:
public class Register extends Activity {
private LinearLayout layout;
private TextView debug;
public static final String USER_CONFIG = "UserConfigs";
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
SharedPreferences settings = getSharedPreferences(USER_CONFIG, MODE_PRIVATE);
boolean registered = settings.getBoolean("registered", false);
layout = (LinearLayout) findViewById(R.id.layoutRegister);
if (!registered) {
debug = new TextView(this);
debug.setText("You have to register");
layout.addView (debug);
//TO DO user registration
settings.edit().putBoolean("registered", true);
settings.edit().commit();
} else {
debug = new TextView(this);
debug.setText("You have already registered");
layout.addView (debug);
//TO DO skip to next screen
}
}
}
But I'm always getting registered as "false" when I restart my app. I have tried to commit it on the onStop() as well and got the same result. I have seen other topics with this problem here but none of them had the same problem as I do.
Any ideas?
You can't do this:
settings.edit().putBoolean("registered", true);
settings.edit().commit();
You need to get the editor object, then make the changes:
Editor editor = settings.edit();
editor.putBoolean(...);
editor.commit();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor edit = prefs.edit();
edit.putBoolean("registered", true);
edit.commit();
use this
The other answers are also correct.
You can also use this
settings.edit().putBoolean("registered", true).commit();

save variables after quitting application?

I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game)
How can I do this?
EDIT: Here my code:
TextView test1;
String punkte = "15";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("score", punkte);
SharedPreferences load = getSharedPreferences(punkte, 0);
String points = load.getString("score", "0");
test1 = (TextView) findViewById(R.id.test1);
test1.setText(points);
}
You should be using SharedPrefences. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there.
Here is a code sample.
To access variables:
SharedPreferences mPrefs = getSharedPreferences("label", 0);
String mString = mPrefs.getString("tag", "default_value_if_variable_not_found");
To edit the variables and commit (store) them:
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("tag", value_of_variable).commit();
Make sure both "tag" fields match!
Use SharedPreference, this is a better option.
To see this tutorial.
sample code:
save:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString("statepara1", ts);
editor.commit();
get:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
String ret = settings.getString("statepara1", "0");

Passing multiple strings to SharedPreferences

I want to store three strings as user preferences for my app. I have a nice layout already set up, it's just a matter of saving the strings to the SharedPreferences. I would also like to know how I can retrieve these strings in the next activity. Below is my current code, I would greatly appreciate it if someone could show me how I can add this functionality to the code. This is a roadblock in my app I have been trying to get past for a few days now.
Code for main activity:
package com.amritayalur.mypowerschool;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
String str;
String username;
String password;
String url;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
// TODO Auto-generated method stub
//Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//startActivity(i);
}
};
});}}
Just set up these class variables in the Activities you want to use SharedPreferences:
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
And then to store string values:
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");
editor.commit(); // persist the values
To read them in another Activity/class:
mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);
This is not hard to look up and find examples of. By going to the documentation in Android Developers you will find a link to this useful site on how to use data storage on Android phones.
Somehow define your preference fields names. It is common practive to do it via final static field. It can be done in your activity class in some separate class. Give them some uniq names.
public static final String MY_PARAM_1 = "com.amritayalur.mypowerschool.PARAM_1";
public static final String MY_PARAM_2 = "com.amritayalur.mypowerschool.PARAM_2";
Get shared preference instance
// "this" is your activity or context
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
To put your strings in preferenes you need to create an editor
SharedPreferences.Editor editor = prefs.edit();
Then put your values
editor.putString(MY_PARAM_1, "First string");
editor.putString(MY_PARAM_2, "Second string");
Then you are done, commit your changes
editor.commit();
To get your values back use the getString method
// specify default value in case if preferences are empty or current key is not set
prefs.getString(MY_PARAM_1, "default value");
You can add multiple values like this:
preferences.edit()
.putLong(DAYS_LEFT, premiumStatus.getDaysLeft())
.putString(KEY, premiumStatus.getKey())
.putString(ID, premiumStatus.getId())
.apply();
First setup shared preference. For this, set this line before on create :
private Context mContext;
then put this in oncreate :
mContext = this;
Then store your value on SharedPreferece:
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(mcontext);
SharedPreferences.Editor editor = settings.edit();
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
editor.putString("kye1", url);
editor.putString("kye2", username);
editor.putString("kye3", password);
Then retrieve your Value from another class (or from any where ) :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mcontext);
String value1=settings.getString("key1",""); // for url
String value2=settings.getString("key2",""); // for name
String value3=settings.getString("key3",""); // for password
Then set this "value1/2/3" any where.

Using shared preferences editor

I'm slowly working through an Android learning book and was given the following code to assign user data:
package com.androidbook.triviaquiz;
import android.app.Activity;
import android.content.SharedPreferences;
public class QuizActivity extends Activity {
public static final String GAME_PREFERENCES = "GamePrefs";
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefeditor.putString("UserName", "John Doe"); //**syntax error on tokens**
prefEditor.putInt("UserAge", 22); //**syntax error on tokens**
prefEditor.commit();
}
However, I get an error (lines indicated with comments) that underlines the period and says "misplaced construct" and also that underlines the arguments saying "delete these tokens". I have seen this done in other applications in the same format, I don't understand what is wrong.
Edit: Of course! Those statements cannot be put directly into the class at that level and must be inside a method, something like this:
public class QuizActivity extends Activity {
public static final String GAME_PREFERENCES = "GamePrefs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("UserName", "John Doe");
prefEditor.putInt("UserAge", 22);
prefEditor.putString("Gender", "Male");
prefEditor.commit();
}
}
I think you may missed up OnCreate() method ,let be sure you should place the shared preference in your OnCreate() method... i just edited your code go through it
please go through the code...below
public class A extends Activity {
static SharedPreferences settings;
public static final String PREFS_NAME = "YourPrefName";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
Log.v("UserName"," - "+settings.getString("username","android"));
SharedPreferences.Editor editor = settings.edit();
editor.putString("username","Change Android");
editor.commit();
Log.v("UserName after changed editing preference key value"," - "+settings.getString("username","android"));
}
}
SharedPreferences will work out side a onCreate() method as long as it has a context:
SharedPreferences settings = getAplicationContext().getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);

Categories

Resources