I want to save the value of a string at exit of my application(process kill) in last activity , so that when I start that application again I can retrieve that value in first activity.
I tried the sharedpreferences but that does not solve my problem. Here is the code snippet.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent int1 = getIntent();
String pth = prefs.getString("pathreturned", "true");
to retrieve in the first activity.
and this one to save it in the previous activity:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = myPrefs.edit();
e.putString("pathreturned", path);
e.commit();
In your previous Activity, use the same code as the one you used before...
Instead of
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Here is a complete Example of Saving Strings Via SharedPreferences
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SharedPrefs extends Activity implements OnClickListener{
private EditText dataInput;
private TextView dataView;
private SharedPreferences sharedString;
public static final String myFile = "MySharedDataFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
setUpVariables();
sharedString = getSharedPreferences(myFile, 0);
}
public void setUpVariables(){
dataInput = (EditText) findViewById(R.id.dataToUse);
dataView = (TextView) findViewById(R.id.showDataView);
Button save = (Button) findViewById(R.id.savedataButton);
Button load = (Button) findViewById(R.id.loadDataButton);
save.setOnClickListener(this);
load.setOnClickListener(this);
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.savedataButton:
String dataToSave = dataInput.getText().toString();
Editor storeData = sharedString.edit();
storeData.putString("key", dataToSave);
storeData.commit();
break;
case R.id.loadDataButton:
sharedString = getSharedPreferences(myFile, 0);
String savedData = sharedString.getString("key", "No data Found");
dataView.setText(savedData);
break;
}
}
}
Unless you know which Activity is going to be "last" you should save your value at the close of each activity. Override the onStop method and save it there.
Related
I am working with SharedPreference but I cannot save info.
These is my code:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SharedPrefApp extends Activity implements View.OnClickListener {
Button buton1 , buton2 ;
EditText etv1 , etv2 ;
TextView tv1;
private static SharedPreferences sharedPref;
protected void onCreate(Bundle bambam){
super.onCreate(bambam);
setContentView(R.layout.sharedpref_xml);
buton1 = ( Button) findViewById(R.id.button12);
buton2 = ( Button) findViewById(R.id.button13);
etv1= (EditText) findViewById(R.id.editText4);
etv2= (EditText) findViewById(R.id.editText5);
tv1 = (TextView) findViewById(R.id.textView12);
buton1.setOnClickListener(this);
buton2.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.button12:
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("isim" , etv1.getText().toString());
editor.putString("sifre" , etv2.getText().toString());
editor.apply();
Toast.makeText(this , "Kaydedildi" , Toast.LENGTH_SHORT).show();
break;
case R.id.button13:
sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE);
String a = sharedPref.getString("isim", "olmadı");
String b = sharedPref.getString("sifre" , "olmadı");
tv1.setText(a + " " + b);
Toast.makeText(this, "Gosterildi" , Toast.LENGTH_SHORT).show();
break;
}
}
}
It returns olmadı olmadı in application. Why it doesn't work?
You have a typo in your code. You spelled name as nama, resulting in that you are trying to store and fetch values from two different preferences.
Your first button (R.id.button12) call to get shared preferences is:
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
change it to:
sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE );
Why are you using editor.apply() method
try to using commit() method
For example
editor.commit()
Try the below code
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
sharedprefs.edit.putString("isim" , etv1.getText().toString()).commit();
Oh Boy... Your getString shouldb like the follows..
String a = sharedPref.getString("isim", null);
String b = sharedPref.getString("sifre" , null);
I'm developing a simple game in Android and even i followed the steps found in the net, the highscore of my app is never saved. I'm using SharedPreferences to store, but I'm quietly sure the problem is in there, because I don't understand at all how to use it.Hope you guys can help me, thanks.
package com.example.memory;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Final extends Activity implements OnClickListener{
TextView levelReachedText;
TextView bestScoreText;
int levelReached, bestScore;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finals);
levelReachedText = (TextView) this.findViewById(R.id.nivel);
bestScoreText = (TextView) this.findViewById(R.id.best);
Button menu = (Button) findViewById(R.id.inicio);
menu.setOnClickListener(this);
intent = getIntent();
levelReached = intent.getIntExtra("nivel", 1);
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
int savedScore = preferences.getInt("selectedScore", 0);
levelReachedText.setText("You reached level "+levelReached );
if(savedScore>levelReached){
bestScore = savedScore;
}else{
bestScore = levelReached;
}
bestScoreText.setText("Maximum level reached "+levelReached);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.inicio:
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
preferences.edit().putInt("selectedScore", bestScore).commit();
this.finish();
break;
}
}
}
you are saving score value in mejorScore and trying to get it from bestScore.So either change
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
to
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
or vice-versa.
A simple task remainder application.
I have to save and retrieve the three edit text values in this app using shared preferences.
Which storage option is best for this app,
1.shared preferences
2.internal storage
Storing
EditText Task = (EditText)findViewById(R.id.ettask);
EditText date = (EditText)findViewById(R.id.etdate);
EditText time = (EditText)findViewById(R.id.ettime);
String taskstr = Task.getText().toString();
String datestr= date .getText().toString();
String timestr= time .getText().toString();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_task", taskstr);
edit.putString("pref_date", datestr);
edit.putString("pref_date", timestr);
edit.commit();
Retrieving
pref_task = preferences.getString("pref_task", "n/a");
pref_date = preferences.getString("pref_date","n/a");
pref_time = preferences.getString("pref_date","n/a");
Complete example:
package com.example.logindemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class LoginPage extends Activity {
EditText name = null, pwd = null;
SharedPreferences login_pref = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
name = (EditText) findViewById(R.id.name_edt);
pwd = (EditText) findViewById(R.id.pwd_edt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_page, menu);
return true;
}
public void loginMethod(View v) {
login_pref = this.getSharedPreferences("login_pref",
MODE_WORLD_READABLE);
SharedPreferences.Editor login_pref_editor = login_pref.edit();
login_pref_editor.putString("Name", name.getText().toString());
login_pref_editor.commit();
startActivity(new Intent(this, WelcomeScreen.class));
}
}
Hope it helps. I feel Shared preference will be a better way
Use below code to Store data into SharedPreferences.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = myPrefs.edit();
editor.putString("Date", mEdttxtDate.getText().toString());
editor.commit();
For Retrive data from SharedPreferences.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String mDate = myPrefs.getString("Date","nothing");
it will solve your problem.
for inserting
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_empId", _empid);
edit.putString("pref_userType", _usertype);
edit.commit();
for getting shared preferences
pref_empId = preferences.getString("pref_empId","n/a");
pref_userType = preferences.getString("pref_userType","n/a");
// I declared myPrefs globally in the lass
SharedPreferences myPrefs = null;
// this is called in my do draw function
public void doDraw() {
myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("MYHIGHSCORE", score);
editor.commit();
}
Whenever I call SharedPreferences.Editor editor = myPrefs.edit();, my program crashes. What I'm doing wrong? I'm trying to store an int for a high score system. And SharedPreferences was suggested a lot for a mini high score system like mine.
Edit:
package com.example.logindemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class LoginPage extends Activity {
EditText name = null, pwd = null;
SharedPreferences login_pref = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
name = (EditText) findViewById(R.id.name_edt);
pwd = (EditText) findViewById(R.id.pwd_edt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_page, menu);
return true;
}
public void loginMethod(View v) {
login_pref = this.getSharedPreferences("login_pref",
MODE_WORLD_READABLE);
SharedPreferences.Editor login_pref_editor = login_pref.edit();
login_pref_editor.putString("Name", name.getText().toString());
login_pref_editor.commit();
startActivity(new Intent(this, WelcomeScreen.class));
}
}
Try this. I think your shared pref object was not fetched properly.
Note: Edited post to add whole class's code.
If you intend to have only one preference file, try to use this code to retrieve the SharedPreference.
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
I guess the problem is not at edit() but when u apply() your changes. Look at the solution here
I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));