NullPointerException using SharedPreferences - android

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

Related

how to maintain session using Shared Preferences

I am developing an app,in that i am maintaining Session using Shared Preferences.I that when user login,i am using their email id for further use.But when i tried to use that email in another activity, it is showing null.
Below in my code for mainActivity:
public class main extends AppCompatActivity {
public Button submit;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String email = "emailkey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
submit = (Button) findViewById(R.id.btn_login);
ImageView i1 = (ImageView) findViewById(R.id.imgLogo);
String checkBoxText = "I agree to all the";
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
checkBox.setText(Html.fromHtml(checkBoxText));
checkBox.setMovementMethod(LinkMovementMethod.getInstance());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText e1 = (EditText) findViewById(R.id.input_email);
EditText p1 = (EditText) findViewById(R.id.input_password);
String e = e1.getText().toString();
final String password = p1.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(email, e);
editor.commit();
Here is my code for another activity:
String e,email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internshipsdetails);
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
sharedpreferences.getString(email,e);
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
AQuery mAQuery = new AQuery(InternShipsDetails.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
You can manage session by changing shared preference values after doing logout action and check preference again at the time of login also. You can save current time also in a string at login and logout action. Make sure to use private shared preferences.
You are passing the wrong key to shared Pref because of that you are getting null.
Following is the updated code of yours which will give you the stored email address:
SharedPreferences sharedpreferences = getSharedPreferences(main.MyPREFERENCES, Context.MODE_PRIVATE);
e = sharedpreferences.getString(main.email,"");
String url = "url?COMP_REQ_ID=" + title + "&StuEmail=" + e;
Happy coding !!!
getString (String key, String defValue) method returns a String. So, you need to catch the output in a string variable.
Also, you are passing a nullkey. You need to pass the same key using which you saved the value.
So, in your case it would be
e = sharedpreferences.getString("emailkey","nodata");

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

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

Best way to save arraylist to androids memory

I have a bundle passed from one activity to another. That contains String n (the length is max 30), String ID and String color. I need to save these values to an ArrayList as an array (n, ID, color) and then to save ArrayList to androids memory. I was looking for a best way of doing that.. I've tried database but its to complicated for me at the moment and I don't think I need such a complex thing. I've tried FileOutputStream (as it explained here: http://developer.android.com/guide/topics/data/data-storage.html#pref?) but it's not working for me, probably because I'm doing something wrong. Do I actually need to create an arraylist of arrays or may be i could use arraylist of bundles, or any other way..? Whats the best way...? Please help..
Thanks every one...Was trying all this time but no luck.. I'm posting the code hoping that someone could give me a hand on that:
public class MainActivity extends Activity
{
String gotNotes;
String n;
String gotDOW;
String gotID;
public String clrs;
public String id;
public String nts;
String gotHour;
String gotColor;
TextView notes;
public static String FILENAME = "allevents";
String[] newevent;
String[] events;
SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button settings = (Button)findViewById(R.id.settings);
Bundle gotPackage = getIntent().getExtras();
if (gotPackage != null){
gotNotes = gotPackage.getString("AddedNote");
if (gotNotes.equals(" "))
{
n = "Empty";
}
else
{
n = gotNotes;
}
//gotDOW = gotPackage.getString("Day");
//gotHour = gotPackage.getInt("Hour");
gotID = gotPackage.getString("ID");
gotColor = gotPackage.getString("color");
initialize();
}
else{}
settings.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(v.getContext(),Settings.class);
startActivityForResult(i,0);
}
});
}
private void initialize()
{
// TODO Auto-generated method stub
String[] newevent = {n, gotID, gotColor};
ArrayList<String[]> events = new ArrayList<String[]>();
events.add(newevent);
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", events.toString());
editor.commit();
String allData = sharedPref.getString("yourKey", null);
String[] playlists = allData.split(",");
/* for (int number=0;number<events.lastIndexOf(sharedPref);number++)
{
notes = (TextView)findViewById(getResources().getIdentifier(playlists[number], getString(0), allData));
notes.setText(number+1);
}*/
notes = (TextView)findViewById(getResources().getIdentifier(gotID, "id",getPackageName()));
notes.setText(n);
notes.setGravity(Gravity.CENTER_HORIZONTAL);
notes.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
if (gotColor.equals("Blue")){
notes.setBackgroundColor(Color.rgb(99, 184, 255));}else
if(gotColor.equals("Green")){
notes.setBackgroundColor(Color.rgb(189, 252, 201));}else
if(gotColor.equals("Yellow")){
notes.setBackgroundColor(Color.rgb(238, 233, 191));}else
if(gotColor.equals("Grey")){
notes.setBackgroundColor(Color.LTGRAY);}else
if(gotColor.equals("Aqua")){
notes.setBackgroundColor(Color.rgb(151, 255, 255));}else
if(gotColor.equals("White")){}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Simply use SharedPreferences to save your application's data.
SharedPreferences sharedPref = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = activity.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("yourKey", yourArray.toString());
editor.commit();
To get your array as String do the following:
String arrayString = sharedPref.getString("yourKey", null);
You can save array into shared preferences and retrieve it back. Here is a good example with fully functional code.

Shared Preferences doesnt work

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

Categories

Resources