How do i store a textview using Shared Preferences - java

So my question might have been asked many times but i couldnt find an answer anywhere on the internet to it .
. What i want to do is store a textview using sharedprefeences .
In my first class (xp) i,m sending the textview to another class (feedback)
Now the feedback is reciving the textview with no single problem , but never saves it. How can i store that textview in the (feedback) class even after closing the app ??
Here's the class which is intenting the textview
public class Xp extends Activity {
Button accept;
TextView textV;
TextView xbnum;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xp);
accept = (Button) findViewById(R.id.accept);
textV = (TextView) findViewById(R.id.textV);
xbnum = (TextView) findViewById(R.id.xpnum);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value1 = extras.getString("intent_xp");
final String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString(PREFS_NAME, value);
edit.putString(PREFS_NAME,value1);
textV.setText(value);
xbnum.setText(value1);
edit.commit();
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Xp.this, feedback.class);
i.putExtra("intent_extra", textV.getText().toString());
startActivity(i);
finish();
}
});
}
}
}
And here is the class which will recive the intent and save the textview (As supposed )
public class feedback extends Activity {
TextView test1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
test1 = (TextView) findViewById(R.id.test1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences("intent_pref", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("intent_pref",value);
test1.setText(value);
edit.apply();
}
}
}
The class is reciving the text , and everything is okay . Only when i close the app and open it , everything is cleared out ..

May be I'm wrong but it seems that you missunderstood how shared preferences works.
If you want to store several values in a preferences file an access it in others classes you have to create one instance of a SharedPreferences.
In your case it means create in both "feedback" and "Xp" a SharedPreferences instance like this :
SharedPreferences settings = getSharedPreferences("MyPrefsFile", SharedPreferences.MODE_PRIVATE);
and then use this instance to store your datas with an editor.
Be careful if you can't store several value for the same key.
You can also store your value in several files as you are actually doing. But if you want to set your textview with the value of your preferences file you have to get it with the getString("key_of_your_value") method on your shared preferences instance.

Related

How do I pass data between multiple pages using intent (Java) in Android studio?

I want to pass data from the MainActivity to all other activities in my App. I want to let the User type her name, and then on each following page, I want her name to show up there too.
So far I only manage to let the data show up in one more acitvity.
This is the code in the feedback class, where the user will type her name/userName etc.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
}
public void thanks_Click(View view) {
EditText nmeText = findViewById(R.id.txtNme);
String nme = nmeText.getText().toString();
Intent newPage = new Intent(this, thanksActivity.class);
newPage.putExtra("USERNAME", nme);
startActivity(newPage);
And this is the code in the page where the data will be visible:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thanks);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String userName = extras.getString( "USERNAME");
TextView thanks = findViewById(R.id.idThanks);
thanks.setText("Thanks for the Quiz idea " + userName);
}
I want the variable userName to show in my other pages as well. How do I do that?
You can keep passing that attribute as Extra for every activity - but is probably easier to save in in sharedPreferences:
So, in MainActivity:
public void thanks_Click(View view) {
EditText nmeText = findViewById(R.id.txtNme);
String nme = nmeText.getText().toString();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("USERNAME", nme);
editor.apply();
Intent newPage = new Intent(this, thanksActivity.class);
startActivity(newPage);
}
and every activity that wants to read that attribute:
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("USERNAME", "");

How to save textview when application is closed?

I'm trying to save textview from getIntent String. When I close the application, then open again, textview is null. I have used many methods like onSaveInstance, SharedPreference but all failed.
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
jamShubuh = findViewById(R.id.jamShubuhTextView);
jamDzuhur = findViewById(R.id.jamDzuhurTextView);
jamAshar = findViewById(R.id.jamAsharTextView);
getShubuh = getIntent().getStringExtra("getShubuh");
getDzuhur = getIntent().getStringExtra("getDzuhur");
getAshar = getIntent().getStringExtra("getAshar");
jamShubuh.setText(getShubuh);
jamDzuhur.setText(getDzuhur);
jamAshar.setText(getAshar);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("shubuh", getShubuh);
editor.putString("dzuhur", getDzuhur);
editor.putString("ashar", getAshar);
retriveData();
private void retriveData() {
SharedPreferences getData = getPreferences(Context.MODE_PRIVATE);
getData.getString("shubuh", null);
getData.getString("dzuhur", null);
getData.getString("ashar", null);
}
To use the shared preferences, I suggest you to make certain class to handle it. Maybe like this.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class MyPrefManager {
SharedPreferences sp;
SharedPreferences.Editor editor;
public void setPref(Context context, String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(context);
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public String getPref(Context context, String key){
sp = PreferenceManager.getDefaultSharedPreferences(context);
value = null;
String X = sp.getString(key, value);
return X;
}
}
Then use setPref method to set the value and getPref method to get the value. Assume now you are in MainActivity and you want to save values of getShubuh, getDzuhur, and getAshar to Preference Manager, you can do something like this :
MyPrefManager MPM = new MyPrefManager();
MPM.setPref(MainActivity.this,"keyShubuh",getShubuh);
MPM.setPref(MainActivity.this,"keyDzuhur",getDzuhur);
MPM.setPref(MainActivity.this,"keyAshar",getAshar);
And to get the value of keyShubuh, keyDzuhur, and keyAshar wherever you want, you can do something like this.
MyPrefManager MPM = new MyPrefManager();
MPM.getPref(AnyActivity.this,"keyShubuh");
MPM.getPref(AnyActivity.this,"keyDzuhur");
MPM.getPref(AnyActivity.this,"keyAshar");
Hope it can help.
To save text state
//Saving The Text Entered by User
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
editText = findViewById(R.id.editText);// getting the reference of editext from xml
CharSequence text = editText.getText();// getting text u entered in edittext
outState.putCharSequence("savedText", text);// saved that text in bundle object i.e. outState
}
and restore saved text
//Restoring the State
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
editText = findViewById(R.id.editText);// getting the reference of textview from xml
CharSequence savedText =
savedInstanceState.getCharSequence("savedText");// getting the text of editext
editText.setText(savedText);// set the text that is retrieved from bundle object
}
instead of EditText you can use TextView.

Load strings from sharedpreferences in EditText (two classes)

I have two different activity's. First one only showed to the user first time - to store phonenumber inside sharedprefs. I think the problem is my load from prefs method but just in case I will leave everything here to make it more relevant to future users. It looks like in both activitys the "mobilnummer" is saved - but I am having problem to display them.
The idea is it to be overwritten if user updates it - I think the method will do that?
OnStartUp.java
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
Profile
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
This is the issue/problem i think! (Code below)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
I think here is your error:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
But the correct way to get a value from shared preferences is something like this:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
Update: when you save the value in the shared preferences, you save only the editText, not it's value, so do something like this when saving:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
And everything else is still the same that I wrote above

Store Value in SharedPreference across Activities

I am new in Android, and got a task to develop a small project to submit in my college, i have tried my best but now i need some help
Let me tell you first, what i am trying to do ?
I have two Activities, MainActivity and AccountActivity
In MainActivity i am using button to switch to AccountActivity
In AccountActivity i am trying to store strBalance value in SharedPreference but whenever i do click on back button and then again come to AccountActivity always getting "1000" not that value which i have stored in SharedPreference.
Here is the complete code of AccountActivity.java:-
public class AccountActivity extends Activity {
EditText editAmount;
int strAmount;
Button btnPayment;
TextView textBalance;
int strBalance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
editAmount = (EditText) findViewById(R.id.editAmt);
btnPayment = (Button) findViewById(R.id.btnPay);
textBalance = (TextView) findViewById(R.id.textBalance);
strBalance = 1000;
textBalance.setText("Your current balance is: $ "+strBalance);
btnPayment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
strAmount = Integer.parseInt(editAmount.getText().toString().trim()); // user input
if(strAmount>strBalance) {
Toast.makeText(AccountActivity.this, "You don't have enough balance", Toast.LENGTH_SHORT).show();
}
else
{
strBalance = strBalance - strAmount; // 1000 - 500 = 500
textBalance.setText("Your current balance is: $ "+strBalance);
Log.v("strBalance", String.valueOf(strBalance)); // 500
editor.putInt("key_balance", strBalance);
editor.commit();
}
}
});
}
}
Do this,
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
int any_variable = sharedPreferences.getInt("key_balance", 0);
Remove initialisation and do this in your onCreate and then use the new variable as you strBalance.
-Check Both the preference and key name are same or not.
You did not retrieve data from SharedPreferences
Write your code in onResume() like this:
#Override
protected void onResume() {
super.onResume();
// SharedPreferences retrieval code
}
To know more about SharedPreferences check this link.
This should work fine:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
if (pref.getInt("key_balance", 1000) != null) {
strBalance = pref.getInt("key_balance",1000);
} else {
strBalance = 1000;
}
Instead of
strBalance = 1000;

Android: SharedPreferences. How to implement them properly

I'm trying to store a user entry into an EditText field however when I exit the application it does not appear.
So for example a user types in his/her name and then exits the application. When the user returns and launches the Application the users name appears in the EditText field. However I can't get this to work. I believe its to do with sharedPreferences but I'm not sure where I'm going wrong.
I'm quite new to android and java so finding this quite difficult. Any help would be much appreciated.
public class MainActivity extends Activity {
public final static String EXTRA_FROM = "com.example.assignment1.FROM";
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = emailFrom.getText().toString();
outState.putString(EXTRA_FROM, from);
}
#Override
protected void onRestoreInstanceState(Bundle savedState)
{
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = savedState.getString(EXTRA_FROM);
emailFrom.setText(from);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void emailSend (View sendButton)
{
Intent intent = new Intent(this,DisplayEmailActivity.class);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = emailFrom.getText().toString();
intent.putExtra(EXTRA_FROM,from);
SharedPreferences saveFrom = getSharedPreferences(EXTRA_FROM, MODE_PRIVATE);
Editor editor = saveFrom.edit();
editor.putString(EXTRA_FROM, from);
editor.commit();
String storedfrom = saveFrom.getString(EXTRA_FROM, from);
emailFrom.setText(storedfrom);
startActivity(intent);
}
Second Activity
public class DisplayEmailActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_email);
Intent intent = getIntent();
String from = intent.getStringExtra(MainActivity.EXTRA_FROM);
TextView textFrom =(TextView)findViewById(R.id.displayEmailFrom);
textFrom.setText(from);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_display_email, menu);
return true;
}
Ok, so after you store value in your EditText emailFrom, you have to save it in SharedPreferences like this:
String from = emailFrom.getText().toString(); // Getting String value from EditText and storing it in "from" String
SharedPreferences settings = getSharedPreferences("MyPreferencesFile", 0); // Opening SharedPreferences
SharedPreferences.Editor editor = settings.edit(); // Opening editor for SharedPreferences
editor.putString("exampleName", from); // You are putting here a String "from" and give it a "exampleName" name. Later you will use this name to restore data.
And then when you launch your application, you need to load data from SharedPreferences:
SharedPreferences settings = getSharedPreferences("MyPreferencesFile", 0); // Again opening SharedPreferences
String from = settings.getString("exampleName", ""); // The second argument is the default value. The default value will be set if there wasn't saved any data with "exampleName" name
if(from != "") // If "from" is not empty, it means that the data was stored in SharedPreferences
emailFrom.setText(from); // Setting text in your EditText
You are using onSaveInstanceState() and onRestoreInstanceState() to save and restore the content of the EditText. However, this methods are called only when the application is being terminated by the OS to be immediatlly recreated (i.e. device rotation).
If you want to preserve values when the application is terminated by the user, you need to store it somewhere, a file, a database or in your case I would suggest SharedPreferences.
I've posted an answer to a similar question in: SharePreferences
Good luck.

Categories

Resources