Shared Preferences doesnt work - android

I need your help here..
I have the following code:
public class GameActivity extends Activity {
TextView test1;
String punkte, points;
#Override
public void onCreate(Bundle savedInstanceState) {
test1 = (TextView) findViewById(R.id.test1);
punkte = points;
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("punkte", punkte).commit();
}
But it still shows "0" if i restart the app.
What did I do wrong?

The first parameter of getSharedPreferences is its name, and you save it to a different shared preferences, indicated by the value of the punkte variable. Try this instead:
final private static String SHARED_PREF_ID = "My shared preferences";
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
// ...
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
save.edit().putString("punkte", punkte).commit();
}
Also, use constants to indicate the mode, not integer literals (MODE_PRIVATE, not 0)

Put mehrPunkte(); in onCreate()

Related

Cant save string with shared preferences

I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??
Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.
You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link

How to save TextView Values in SharedPreferences

How to save TextView values in SharedPreferences, see my code below and let me know how to store to SharedPreferences and retrieve in onCreate(..)
my code looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(strEventName);
txtOperative.setText(strOperativeName);
}
I want to show these values always in TextViews, whenever user comes back to this activity
Simple use this for save your TextView value in sharedpreference
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtEvent.getText().toString());
sedt.putString("txtopertaive", txtOperative.getText().toString());
sedt.commit();
Now after that retrieve it anywhere in your Activity class or any other Activity by
SharedPreferences sp = getSharedPreferences("key", 0);
String tValue = sp.getString("textvalue","");
String tOperative = sp.getString("txtopertaive","");
To save the data, Can't see any call for SharedPreferences - editor/ editor.commit()
Add those functions to your activity:
When you want to save data:
saveDataToPreferences(context, "strEventName", valueHere);
And in your activity,
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context=this;
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(getDataFromPreferences(context,"strEventName"));
txtOperative.setText(getDataFromPreferences(context,"strEventName"));
}
public static void saveDataToPreferences(Context context, String key,
String value) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDataFromPreferences(Context context, String key) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
return prefs.getString(key, Constants.BLANK);
}
To store in shared preferences your value use that code.
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("OPERATIVE", txtOperative.getText().toString());
editor.String("EVENT", txtEvent.getText().toString());
editor.commit();
Use
prefs.edit().putString(context.getString(R.string.NAME), name).commit();
in order to save data to shared preferences and
prefs.getString(context.getString(R.string.NAME), "");
to get data from shared preferences.
define Editor like below
private Editor editor;
and initialize it after initializing shared preference like
editor = prefs.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.commit();
And to retrieve this value just call
String value = prefs.getString("key1","");

Android SharedPreferences not loading and saving properly

I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}

How to use remember me function in my android login application

I am using the code for remember my username and password. i have tried a lot of hours for the code for remember my username name and password but i cant success in it.
Here is my code which i have download from internet but it didn't work for me.
I have declared this variable in the extends activity.
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS_PASS = "prefsPassword";
after that I have also declare different variable like below.
public String PREFS_USERS;
public String PREFS_PASS;
String username;
String upass;
and in the click listener i have given the following code.
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
username = etUsername.getText().toString();
upass = etPassword.getText().toString();
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_USERS, username)
.putString(PREFS_PASS, upass)
.commit();
and at the time at retry i have return the following code in the oncreate activity to retry my user name and password.
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USERS, "");
upass = pref.getString(PREFS_PASS, "");
But when I run the application i cant get the username and password.First time when i load the application i checked the remember me check box after log in and log out back from the application and close the application and when come back to it.it was not saved for me.
The problem is in declaring the variables
you have declared
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS_PASS = "prefsPassword";
public String PREFS_USERS;
public String PREFS_PASS; //assigned null here
.putString(PREFS_PASS, upass) //here value of PREFS_PASS is null
Use the following code
better do like the folowing
public String PREFS_USERNAME= "prefsUsername";
public String PREFS_PASSWORD="prefsPassword";
Store the data as using following code
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
passwordInString = password.getText().toString();
userNameInString = username.getText().toString();
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_USERNAME, userNameInString)
.putString(PREFS_PASSWORD, passwordInString)
.commit();
retrieve the data like the following
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String usernameName = pref.getString(PREFS_USERNAME, "");
String upassWord = pref.getString(PREFS_PASSWORD, "");
Thanks
Deepak
It should look something like this (obviously you can use global vars so you dont have to specify them in several places):
String PREFS = "MyPrefs";
SharedPreferences mPrefs;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPrefs = getSharedPreferences(PREFS, 0);
//check if the remember option has been check before
boolean rememberMe = mPrefs.getBoolean("rememberMe", false);
if(rememberMe == true){
//get previously stored login details
String login = mPrefs.getString("login", null);
String upass = mPrefs.getString("password", null);
if(login != null && pass != null){
//fill input boxes with stored login and pass
EditText loginEbx = (EditText)findViewById(R.id.login_box);
EditText passEbx = (EditText)findViewById(R.id.pass_box);
loginEbx.setText(login);
passEbx.setText(upass);
//set the check box to 'checked'
CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.remeber_cbx);
rememberMeCbx.setChecked(true);
}
}
}
private void saveLoginDetails(){
//fill input boxes with stored login and pass
EditText loginEbx = (EditText)findViewById(R.id.login_box);
EditText passEbx = (EditText)findViewById(R.id.pass_box);
String login = loginEbx.getText().toString();
String upass = passEbx.getText().toString();
Editor e = mPrefs.edit();
e.putBoolean("rememberMe", true);
e.putString("login", login);
e.putString("password", upass);
e.commit();
}
private void removeLoginDetails(){
Editor e = mPrefs.edit();
e.putBoolean("rememberMe", false);
e.remove("login");
e.remove("password");
e.commit();
}
You would probably call the saveLoginDetails() & removeLoginDetails() methods in the OnClick listener:
CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.remeber_cbx);
boolean isChecked = rememberMeCbx.isChecked();
if(isChecked){
saveLoginDetails();
}else{
removeLoginDetails();
}
I hope you can find it useful
U can do this.. create a boolean variable with default value "false" and set a boolean value to true when user choses for rememberMe and put an if condition before validating user password and other stuff.. and use the boolean value in this condition..
SharedPreferences myPrefs;
onCreate()
{
myPrefs=this.getSharedPreferences("PREF_NAME",Context.MODE_PRIVATE);
if(myPrefs.getBoolean("firstTime", false))
{
startActivity(new Intent(this,SeeRecordsActivity.class));
finish();
}
}
on signIn button:
boolean c=chkbox.isChecked();
if(c==true)
{
SharedPreferences.Editor editor=myPrefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}

NullPointerException using SharedPreferences

I am having a problem with my code here. I am using SharedPreferences in my code, and I am getting a NullPointerException at one line in the code. Here's the full code:
public class Exercise extends Activity {
String WEIGHT = "0";
String AGE = "0";
String FEET = "0";
String INCHES = "0";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt(WEIGHT, 0);
prefsEditor.putInt(AGE, 0);
prefsEditor.putInt(FEET, 0);
prefsEditor.putInt(INCHES, 0);
prefsEditor.commit();
final EditText weightField = (EditText) findViewById(R.id.EditTextWeight);
try {
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
prefsEditor.commit();
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
The NullPointerException appears at this line:
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
Thanks!
EDIT: Here's the activity that calls setContentView(R.layout.main):
public class CalorieIntakeCalculator extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void next(View view) {
Intent intentExercise = new Intent(view.getContext(), Exercise.class);
startActivityForResult(intentExercise, 0);
}
}
When the "next" button is pushed in main.xml, it sends next which switches Activities from CalorieIntakeCalculator to Exercise.
Since you successfully used prefsEditor several times above that line, it seems like weightField must be null. Have you checked its value in the debugger?
EDIT: I also just noticed that you never assigned a value to WEIGHT, nor any of the other Strings for the SharedPreferences keys, so they are all null. You need to fix that.
String WEIGHT = "weight";
String AGE = "age";
String FEET = "feet";
String INCHES = "inches";
For the weight field, make sure there is an EditText in your exercise layout that has the id R.id.EditTextWeight

Categories

Resources