I have a single string which the user will edit and will be displayed back to him when he uses the app. He can edit the string at any time. I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better. However, after following two different tutorials, I am unable to get it so save the data. In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities. Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {
TextView textSavedMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_view);
textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);
LoadPreferences();
textSavedMem1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
return;
}});
};
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
textSavedMem1.setText(strSavedMem1);
}
}
Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {
EditText editText1;
Button buttonSaveMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_edit);
editText1 = (EditText)findViewById(R.id.editText1);
buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
viewStatement();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
protected void viewStatement() {
Intent i = new Intent(this, MissionOverviewActivity.class);
startActivity(i);
}
}
If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks
getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
"yourfilename", Context.MODE_PRIVATE);
and use the same method when you want to reload it. here the doc for getPrerences(int)
Related
I'm trying to use SharedPreferences with a very simple app
it is just a TextView with number 0 and one button to increment this number, but after reopening the app and press the button it resets to 0
Here is the code:
public class MainActivity extends AppCompatActivity {
public TextView t1;
public Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
t1=(TextView)findViewById(R.id.textView);
SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
int n=mypref.getInt("n",0);
String s=""+n;
t1.setText(s);
SharedPreferences.Editor editor=mypref.edit();
editor.putInt("n",0);
editor.apply();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add();
}
});
}
The add method:
private void add() {
SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
SharedPreferences.Editor editor=mypref.edit();
int n=mypref.getInt("n",0);
n++;
String s=""+n;
t1.setText(s);
editor.putInt("n",n);
editor.apply();
}
You have this code every time your activity is created (same goes when you open the app):
SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
int n=mypref.getInt("n",0);
String s=""+n;
t1.setText(s);
// here you reset the counter to 0
SharedPreferences.Editor editor=mypref.edit();
editor.putInt("n",0);
editor.apply();
// the problem ends here
So, to fix the problem simply remove the code between comments
i am kind of new to android programming , i am designing a program that has login page and main page.When i sign in for the first time with a username and password, i created a sharedpreferences to remember that username and whenever i enter program , it skips login page and redirects me to main page.What i want to do is, when i press logout button in login page ,i want sharedpreferences forget the value of username in my database(it wont delete it from database) and force me to login me again with the same or different username and password , and i dont want to be redirected to main page when i enter application.I found something like SharedPreferences.Editor.remove() , SharedPreferences.Editor.clear(),commit() ,etc.. But code didnt work.Can you help?
public static class SaveSharedPreference {
static final String PREF_USER_NAME = "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx) {
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Button btnSignIn, btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uye_kayit_giris);
if (SaveSharedPreference.getUserName(UyeKayitGirisActivity.this).length() == 0) {
Intent i = new Intent(UyeKayitGirisActivity.this, MainActivity.class);
startActivity(i);
// finish();
}
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Refference Of Buttons
btnSignIn = (Button) findViewById(R.id.buttonSignIN);
btnSignUp = (Button) findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP = new Intent(getApplicationContext(), SignUPActivity.class);
startActivity(intentSignUP);
}
});
Button btn_exit;
// super.onCreate(savedInstanceState);
// setContentView(R.layout.main1);
btn_exit = (Button) findViewById(R.id.buttonLogOUT);
btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WHAT SHOULD I WRITE IN HERE?????????????
Toast.makeText(UyeKayitGirisActivity.this, "ÜYE GİRİŞİ TEKRAR ZORUNLU HALE GETİRİLDİ!!!", Toast.LENGTH_LONG).show();
}
});
}
Try like this
SharedPreferences pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
Here is the Method
private void removePreference(Context context, String prefsName, String key) {
SharedPreferences preferences = context.getSharedPreferences(prefsName, Activity.MODE_PRIVATE);
android.content.SharedPreferences.Editor editor = preferences.edit();
editor.remove(key);
editor.apply();
}
You can call it like:
public void removeUser() {
removePreference(context, FILENAME, KEY_USER);
}
Since you have mentioned that you do NOT want to delete the value of login from shared preference but only ask for login page each time, I believe you are looking for something where you want to clear application cache programatically.
Please check, Clear Cache in Android Application programmatically and Clear Application's Data Programmatically
It is also worth reading this wonderful answer - Don't delete database or shared Preference on clear app
To remove them all SharedPreferences.Editor.clear() followed by a commit()
I am making a game like logo quiz. I have the question activity and the levels activity so when users answer correctly they score 1. Then I want to put the score in the levels activity so in that way users could unlock the next level, but I don't want users leave the question activity and until now I have only found this method:
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.putExtra("score", score);
startActivity(resultIntent);
However, with this method the user goes to the levels activity.
I will leave my code for reference:
public class Big extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_big);
init();
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true); }
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), Level1.class);
startActivityForResult(myIntent, 0);
return true;
}
private Button buttonSaveMem1;
private EditText escrive;
private TextView respuest;
private String [] answers;
int score=0;
int HighScore;
private String saveScore = "HighScore";
private int currentQuestion;
public void init()
{
answers = new String[]{"Big"};
buttonSaveMem1 = (Button)findViewById(R.id.button1);
respuest = (TextView) findViewById(R.id.textView2);
escrive = (EditText) findViewById(R.id.editText1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
checkAnswer();
// TODO Auto-generated method stub
SavePreferences();
LoadPreferences();
}};
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(answers[currentQuestion]));
}
public void checkAnswer() {
String answer = escrive.getText().toString();
if(isCorrect(answer)) {
update();
respuest.setText("You're right!" + " The Answer is " + answer + " your score is:" + score +" " +
"HighScore: " + HighScore);
score =1;
}
else {
respuest.setText("Sorry, The answer is not right!");
}
}
private void update() {
if (score > HighScore)
{ HighScore = score; }
}
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", respuest.getText().toString());
sharedPreferences.edit().putInt(saveScore, HighScore).commit();
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
HighScore = sharedPreferences.getInt(saveScore, 0);
respuest.setText(strSavedMem1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here is the levels activity:
public class Level extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
Button salir = (Button) findViewById(R.id.button3);
salir.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, MainActivity.class)); }
}
)
;
Button leve2 = (Button) findViewById(R.id.button1);
leve2.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, Level2.class)); }
}
)
; }
Button leve1 = (Button) findViewById(R.id.button1);
leve1.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, Level1.class)); }
}
)
;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level, menu);
return true;
}
}
Thanks for the help!
In your questions activity, store the score of the user in the SharedPreferences
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
prefs.edit.putLong(USER_SCORE, score).commit();
And then when you return to your level's activity, you can fetch from the preferences.
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
long userScore = prefs.getLong(USER_SCORE, 0);
USER_SCORE is just a string key like USER_SCORE = "user_score" to allow the device to find the date you stored in the prefs.
Shared preferences are saved to the phone and not accessible except through the app that they belong to. So upon starting the app again, you can get the User's score that was saved last time they used the app.
You can make make the score as static and then modify it from the other activity class. IT would automatically change it in the original.
Store the score in a SharedPreferences instead of passing it to Level in an intent. You can then retrieve that score within the levels Activity (or any other for that matter), whenever the user may navigate there. You already use SharedPreferences in your code with:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
However that returns a Shared Preference using the calling Activity's class name as the Shared Preference name, i.e. those preference values are private to your Activity 'Big'. To use preference values that have application scope, use getSharedPreferences(), providing a Shared Preferences name:
SharedPreferences sharedPreferences = getSharedPreferences("MYPREFS", Activity.MODE_PRIVATE);
Create an Editor from that and store the value of 'score'. Then retrieve it your Level activity, most likely in its onCreate().
After looking here and there, I've finally found out my answer to this question by following other answers and I basically used the following combination of codes to do so.
In a first activity:
import:
import android.content.Context;
import android.content.SharedPreferences;
declare:
public static int totalCount;
and add onCreate():
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);`
totalCount++;`
editor.putInt("counter", totalCount);`
editor.apply();`
Then, on a second activity:
import:
import static com.example.myapp.totalCount
and add onCreate():
((TextView) findViewById(R.id.text_view_id)).setText(String.valueOf(totalCount));
In the layout for the second activity:
place a TextView with:
android:id="#+id/text_view_id"
And pay attention to what the documentation says about naming shared preferences.
When naming your shared preference files, you should use a name that's
uniquely identifiable to your app. An easy way to do this is prefix
the file name with your application ID. For example:
"com.example.myapp.PREFERENCE_FILE_KEY"
I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)
I have only one edittext in my app from which I want to store strings array on button click. Just like history of any browser. I want to show the stored strings when my app starts. I have been trying to use shared preferences with single textview. I have attached the code for my activity.
public class MainActivity extends Activity {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT)
.show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
}
My only one textview is populating, I want to show last five search history using this. Please give me some idea regarding this.
Serialize your data. Array -> String and String can be saved to the preference, maybe use JSON to encode / decode your data.
http://developer.android.com/reference/org/json/JSONObject.html
http://www.json.org/