SharedPreferences automatically save text from TextView without a Save button - java

I have a problem that should remember-save the text from the TextView that the user inputs through his voice, but I have enabled the Night mode, at the time when the day mode passes into the night mode, the text entered at that moment disappears. I know that it needs to be SharedPreferences, I tried this code, but I can not record anything. I emphasize that there is no Save button. It is necessary to return the text already entered when refreshing the Activity. I ask for help please
/*...*/{
//...
myText = (TextView) findViewById(R.id.textView);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (!TextUtils.isEmpty(restoredText)) {
myText.setText(restoredText);
}
//...
}
public void loadData() {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", myText.getText().toString());
editor.commit();
}

It sounds like your activity is getting killed. If this is the case, then you should implement the android activity lifecycle methods onSaveInstanceState and onRestoreInstanceState.
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(bundle);
state.putString("text", myText.getText().toString());
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myText.setText(savedInstanceState.getString("text"));
}

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 to save users' last read Page Number

I am building an android app which displaying a specific pdf through https://github.com/barteksc/AndroidPdfViewer with lots of pages, and now i was just implementing a method to re-open the pdf from the last opened page of the user.
I am using SharedPreferences to store the current page, and then after reloading the app, the app will re-open the pdf where user left.
Here is my Shared Preferences method to store and retrieve the data
private void storepreferences () {
PDFView pdfView = findViewById(R.id.pdfView);
savedpage=pdfView.getCurrentPage();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("key_name2", savedpage);
editor.apply();
}
private void getpreferences () {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
pageNumber = pref.getInt("key_name2", 0); // getting Integer
}
And then i am using onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
storepreferences();
getpreferences();
Also for a test i am displaying the
TextView txt = findViewById(R.id.textView2);
txt.setText(String.valueOf(pageNumber));
But Still i am getting the default value, What i am doing wrong can anyone tell me?
In StorePreference, First, try putting this code.
editor.commit()
and then,
editor.apply().
Finally I achieved this, I was using (storepreferences) on OnCreate before but now On I am using at BackPressed
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
storepreferences();
super.onBackPressed();
}
}
After that I am retrieving saved data on OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getpreferences();
}
I am using the above technique because I thought It is actually not storing my data, because When i use Toast to display the current Page, it was showing exactly the page number where user is
public void pagestorebutton (){
PDFView pdfView = findViewById(R.id.pdfView);
savedpage = pdfView.getCurrentPage();
Toast myToast = Toast.makeText(this,(String.valueOf(savedpage) ), Toast.LENGTH_SHORT);
myToast.show();
storepreferences();
}
And in onCreate i am using above function after clicking a Floating Button
FloatingActionButton fab4 = findViewById(R.id.fab4);
fab4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pagestorebutton();
}
});
Is my Method is achieving my Goal through right path, or is there something more to do??

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.

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

SharedPreferences not working. Always show the same value

This is my MainActivity.java's onCreate method:
protected void onCreate(Bundle savedInstanceState) {
loadSavedPreferences();
savePreferences("storedAddress", userAddress.getText().toString());
}
These 2 are the methods inside the class
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String address = sharedPreferences.getString("storedAddress", "YourAddress");
userAddress.setText(address);
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
Here's the flow. First time user uses the app has to enter their address in the EditText field. I want the same address to be stored there when the user returns.
The problem with the code above: It always shows "YourAddress" in the EditText field. There's no login required for this application. Just a simple form.
Use your savePreferences() method in any action the user can do after typing his address,a button click or whatever.
The way it is now, it's saving only when the activity gets created and after you load the preferences with the default value YourAddress. That's why you always get the same value.

Categories

Resources