NullPointerException on SharedPreferences in Button OnClick - java

I'm trying to update a shared preference of whether or not a user has checked a box to not display a welcome screen anymore. I access my shared preferences my onClick listener for a button. I'm getting a Null Pointer Exception and I don't know how to fix it?
Here is my code....
public class WelcomeScreenActivity extends Activity {
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomescreen);
final Button button = (Button) findViewById(R.id.welcomecontinue);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) findViewById(R.id.welcomecheckbox);
if(cb.isChecked()){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
Intent intent = new Intent(WelcomeScreenActivity.this, MainActivity.class);
startActivity(intent);
} else if(!cb.isChecked()){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, false);
editor.commit(); // Very important to save the preference
Intent intent = new Intent(WelcomeScreenActivity.this, MainActivity.class);
startActivity(intent);
}
}
});
}
}
Can anyone shed some light into this?

SharedPreferences mPrefs;
You have never initialized it. Although you are using it
mPrefs.edit();
Do do something like:
SharedPreferences mPrefs = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
Before using it.

You are never setting mPrefs to anything s calling mPrefs.edit() will throw a NullPointerException

Related

How can I display info from sharedPreferences after the activity or app gets closed?

I have put some information that I want to be displayed even after my app or activity gets closed. I have a function display and if I call it in onCreate() or onStart() my app crashes.
public void display() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
mText1.setText(sharedPref.getString("mText1", ""));
}
Here's how the data gets saved
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
This is the line that does not fit in the picture:
java.lang.RuntimeException: Unable to start activity ComponentInfo{corina_holom.com.medplannerapp/corina_holom.com.medplannerapp.Reminder}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This is my first time programming in java and android studio and I'm having trouble finding tutorials that help. I'm not sure how I should change this or if I should use onStart()
This is the Code from the activity in which I want the info displayed:
public class Reminder extends AppCompatActivity {
public TextView mText1, mText2, mText3;
private EditText addMed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
defineButtons();
}
public void defineButtons() {
findViewById(R.id.mB1).setOnClickListener(buttonClickListener);
findViewById(R.id.mB2).setOnClickListener(buttonClickListener);
//findViewById(R.id.mB3).setOnClickListener(buttonClickListener);
}
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.mB1:
addMed = (EditText) findViewById(R.id.addMed);
mText1 = (TextView) findViewById(R.id.mText1);
mText1.setText(addMed.getText());
savemMed1();
break;
case R.id.mB2:
addMed = (EditText) findViewById(R.id.addMed);
mText2 = (TextView) findViewById(R.id.mText2);
mText2.setText(addMed.getText());
break;
}
}
};
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
}
The problem is that by the time you use setText your textview is not initialised. Make sure you do findViewById before you do setText. The best way is to do it first thing in onCreate. And of course make sure that the id is the same as in the layout.

Check activation code on first app run

I created an android app that when it runs for the first time an activation page loads with these codes .
Button btnInput = (Button) findViewById(R.id.send);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText m = (EditText) findViewById(R.id.editText);
String strInput = m.getText().toString();
if (strInput.equals("123") || strInput.equals("456"))
startActivity(new Intent(ActiveCode.this, MainActivity.class));
else
startActivity(new Intent(ActiveCode.this,ActiveCode.class));
finish();
}
});
}
And Main activity code like this :
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
startActivity(new Intent(MainActivity.this,ActiveCode.class));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit();// Very important to save the preference
}
}
the problem is that when on first run user closes the app completely without entering code and open it again they don't need to enter code and it goes directly to main activity , so basically it's a bug of my app .
I want help to change codes in a way that activation page disappear only when user enters code.
Try to initialize preference like this,
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
instead of,
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Because your preference is not binding with your activity.

Shared preference not saved or loop does'nt work

Some help would be most thankful for. I have two activities. MainActivity and SharedPrefs. I want the app on open to look if there is some saved preferences. If not it must go to another activity which ask for some detail. Then on pressing the submit button it must save the shared preference and go to the MainActivity. But it doesn't, it just jumps back to the SharedPrefs activity. Now I don't know if my shared preference is not being saved (I thought "editor.commit" will do the job), or is there something wrong with my loop. I did change my loop around, and it is working the other way around, but I can have the whole thing wrong since I'm quite new to Android and Java. Like I said, some help will be appreciated.
Here is my MainActivity with my loop:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
boolean check = sharedPreferences.getBoolean("Check",false);
if(!check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
brands.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent brandsIntent = new Intent(MainActivity.this, brands.class);
startActivity(brandsIntent);
}
});
}
}
And here is my SharedPrefs where I try to get some info to add to the shared preferences:
public class SharedPrefs extends AppCompatActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
Intent BackToMainIntent = new Intent(SharedPrefs.this, MainActivity.class);
startActivity(BackToMainIntent);
}
});
}
Please add "Check" key value to SharedPreferences after setting your desired values as it's always return false on MainActivity.
You may also use .apply() instead of .commit().
It doesn't look like you are saving a Boolean Check anywhere in the second activity. So in your first activity, this Boolean never exists and you are getting the default value which you have set to false. You need a preference called `Check' to be set to true in your second activity.
In your SharedPrefs Activity
Change your this piece of code
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
With
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.putBooleon (Check,true);
editor.commit();
Then It will work as you want.
Happy coding :)

Checkbox passing of action on reopening of the app

I have stored the checkbox value(check/uncheck) using shared preference,but I face problem while passing the action of checkbox on/after closing and reopening the app.Explantion: A button in different actvity hides/shows on clicking the checkbox(i.e check=shows & uncheck= hides) working correctly. when I close the app and reopen the checkbox stays checked but button is not appearing
checkbox code saved using shared preference
final CheckBox checkBox = (CheckBox) findViewById(R.id.add_fb);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
checkBox.setChecked(preferences.getBoolean("checked",false));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
editor.putBoolean("checked", isChecked);
editor.apply();
}
});
}
I tried to implement onStart() for passing data by providing if-else condition
#Override
protected void onStart() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
super.onStart();
if(checkBox.isChecked()) {
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
This is where i am passing the data once the checkbox is checked
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
Instead of sending 'isCheckedValue' in 'onBubbleClickMethod'
try this -
in.putExtra("yourBoolName",preferences.getBoolean("checked",false));

How to save user input from EditText to a variable to be used on a different Activity

I have an edit text in Android Studio which I want a user to enter a name which can then be stored as a variable. I then want to add this variable to a textview in my main activity.
Right now all a have is a blank activity with an edit text and button to save the user input as a variable.
Edit
Ok, I am going to change my approach. In my main activity, I have two text views. If I changed them to edit texts, then how would I save them from the main activity without a save button so that what the user typed would still be there?
Save it in Shared Preferences and then retrieve it from the other activity.
To save a String in shared preferences, you can create a method like the following:
public static void setUsername(Context context, String username) {
SharedPreferences prefs = context.getSharedPreferences("myAppPackage", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.commit();
}
To retreive it :
public static String getUsername(Context context) {
SharedPreferences prefs = context.getSharedPreferences("myAppPackage", 0);
return prefs.getString("username", "");
}
Edited:
In the activity which contains the EditText, you can call the method as follows:
setUsername(this,myEditText.getText().toString());
And in the Activitiy that contains the TextView:
myTextView.setText( getUsername(this) );
you ça use edit.getText().toString() tout get the user input.
To launch new activity and pass the string to it use
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("key", theString);
startActivity(intent);
EDIT
To be more easy you should add a button to your layout so when the user press that button you can launch the next activity with the string.
This should go into your activity
public class BlankActivity implements OnClickListener {
private EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//find editText
mEditText = (EditText) findViewById(R.id.your_edit_text_id);
//listen button
findViewById(R.id.your_button_id).setOnClickListener(this);
}
#Override
public void onClick(View v) {
String theString = mEditText.getText().toString();
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("key", theString);
startActivity(intent);
}
}

Categories

Resources