sharedpreferences - getInt when button is clicked - android

scenario during a simple ball game i click exit and return to the menu and then exit out of the app,once i launch the app again I can click 'Continue" from the main menu and return to the game where i had left off or click New game and start again.
My problem is get sharedprefs are on onCreate, so even if i click 'New game' it continues from where i had left off.
I tried various onclick, findviewbyid methods and none of them worked, for example.
public class GActivity extends ActionBarActivity {
private int RWIDTH = 70;
// + a whole bunch of other unrelated stuff that i cut-out to make viewing easier.
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button CntButton = (Button) findViewById(R.id.ConGame);
CntButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
RWIDTH = settings.getInt("RWIDTH", RWIDTH);
}
});
}
protected void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("RWIDTH", RWIDTH);
editor.commit();
}

Related

Android SharedPreferences does not save after app reopening

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

How to put score from one activity into another activity without going to that activity?

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"

SharedPreferences Android - Saving and editing one string only using two activities

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)

User setup activity of android app

I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()

save the state when back button is pressed

I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used finish() ?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s1=(Button)findViewById(R.id.sn1);
s1.setOnClickListener(this);
LoadPreferences();
s1.setEnabled(false);
}
public void SavePreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", s1.isEnabled());
}
public void LoadPreferences()
{
System.out.println("LoadPrefe");
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
s1.setEnabled(state);
}
#Override
public void onBackPressed()
{
System.out.println("backbutton");
SavePreferences();
super.onBackPressed();
}
What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}
you can use this way
public void onBackPressed() {
// Save settings here
};
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
save your application state in this method.

Categories

Resources