Shared preference not saved or loop does'nt work - java

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

Related

How to make users come back to a particular activity after they kill the app

I am working on an app, so basically, when the user launches the app for the first time, activity A comes up, which asks the user for a bunch of data. Now, that I have the data, I take the user to activity B. Here, if the user kills the app completely, and relaunches it, the app reopens activity A, instead of B... Is there a way to control this behaviour? I want to be able to control what activity the app should open after a particular action by the user... Note : I am a complete newbie, so I have no idea how to do this.. I tried to ask this up on a google search, but couldn't find anything proper ig.
You can store boolean by shared preference to do that. Here your AcitivityA class. Store user provided data before user land to ActivityB.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
//Store user data here
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
The easiest way to use user data in all over the app. Make a separate class for storing user data and make the getter and setter to get and set the data.
public class UserSharedPrefs {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
#SuppressLint("CommitPrefEdits")
public UserSharedPrefs(Context context) {
sharedPreferences = context.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean("isLogin", isLogin);
editor.apply();
}
public boolean getIsLogin() {
return sharedPreferences.getBoolean("isLogin", false);
}
In Activity A makes the reference of that class and get the data and use it as your need. And send the user to desired Activity
if(userSharedPrefs.getIsLogin()){
moveToActivityB()
}

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.

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

Why does the code run a command, even if its if statement isn't fulfilled?

When I run my code in debug mode, I can see, that for the value "ooy" another content is set (and it would be correct like this) than for the value "skii". But the code still starts the Activity "Game.class", and the Activity "Tutorial.class" too but only in background. How can I solve this?
MainScreen:
public class MainScreen extends Activity implements OnClickListener {
public static final String PREFS_NAME = "MyPrefsFile1";
String ooy;
String skii;
super.onCreate(savedInstanceState);
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main_screen);
SharedPreferences tutoask = getSharedPreferences(PREFS_NAME, 0);
ooy = tutoask.getString("skipMessage", "NOT checked");
skii = "checked";
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_start) {
startActivity(new Intent(this, Tutorial.class));
if (ooy.equals(skii)){
startActivity(new Intent(this, Game.class));
}
}
Tutorial:
public class Tutorial extends Activity implements OnClickListener {
Button btn;
public CheckBox checkBox1;
String checkBoxResult = "NOT checked";
public static final String PREFS_NAME = "MyPrefsFile1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
btn = (Button) findViewById(R.id.startut);
btn.setOnClickListener( this);
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
}
#Override
public void onClick(View v) {
if (checkBox1.isChecked()){
checkBoxResult = "checked";
SharedPreferences tutoask = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = tutoask.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
}
startActivity(new Intent(this, Game.class));
finish();
}
}
Are you saying that the two variables have different values? Sorry, your sentence is difficult to understand.
If the variables are not equal it would execute what is inside the if command since you have the NOT (!) command.
If they are NOT equal execute the command:
startActivity(new Intent(this,Game.class));
I am not sure what you want to do and what the actual problem is. You have two variables with not equal values; when you check the two, they are not equal, so the command inside the if is executed. As it should since you have the not statement.
Look at the equals method of the ooy and skii objects. They are probably implementhed wrong.

NullPointerException on SharedPreferences in Button OnClick

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

Categories

Resources