Saving the score using shared preferences - android

Hey guys I know there are already many posts for the same and I have followed each of them.
Here I am facing a problem and need to know the sloution.
I am releasing my app tomorrow so need help with this.
I have tried to use it with string as well as int but none of them are working and giving error.
Thanks
My Code :
package com.droidacid.apticalc.tys;
import com.droidacid.apticalc.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.TextView;
public class HighScores extends Activity {
TextView tvHighScore;
private static String SCORE_KEY = "savedScore";
String myScore;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tys_high_score);
tvHighScore = (TextView) findViewById(R.id.tv_tys_score);
getScore();
}
private void getScore() {
Bundle getScore = getIntent().getExtras();
score = getScore.getInt("score");
myScore = Integer.toString(score);
setScore(score);
getScore(score);
}
private void setScore(int score) {
SharedPreferences saveScore = getSharedPreferences("saveScores", MODE_PRIVATE);
SharedPreferences.Editor editor = saveScore.edit();
editor.putString(SCORE_KEY, myScore);
editor.commit();
}
SharedPreferences saveScore = getSharedPreferences("saveScores", MODE_PRIVATE);
tvHighScore.setText(saveScore.getString(SCORE_KEY, ""));
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}

It's because that these two lines are not in any method.
SharedPreferences saveScore = getSharedPreferences("saveScores", MODE_PRIVATE);
tvHighScore.setText(saveScore.getString(SCORE_KEY, ""));
Try to put these two lines in your on create method and you will see that this error will stop.
Tell me how it goes.

Related

Continue from the last counter when reopen the android application

I am new in Android programing. I want to make an application. The button text increase whenever the user click on it. My counter is reseted when the application is closed. How can I store the last counter value and call it again when the application is reopened?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
}
EDIT:
I try to use this Shared Preferences but I got eror about "setSilent" and "mSilentMode". Help please
My new code
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
It depends, are you asking how to preserve a variable across an app's lifespan or between different lifespans?
If it's across different lifespans, you can write it to disk and then read it onCreate.
If you need to do it across one lifespan, it depends on your use case, but generally putting it in a global, static variable would do the trick!
If this is unclear and you'd like some sample code, please, don't be afraid to ask! : )
You can save your c value in the Preference when your activity is going to be closed, and when you rise up your activity you set your c variabile to the previous value
Use this snippet out of your onClickListener: To get the int if there is any
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
int ca = hhii.getInt("c_value2", 0);
button.setText(ca+"");
Use this in your onClickListener: To save the int as the user clicks the button-much better than saving it in onBackPressed or OnDestroy or whatever
c++;
button.setText(Integer.toString(c));
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
hhii.edit().putInt("c_value2",c).commit();
Regards from Iran,
Gabriel

How can I set save and load a password with sharedPreference?

I am doing an android app which would save the password for the next time the user wants to use this app. when I try to run my application, the password is entered,but there is a pop-up said the application has stopped?
package com.wheresmyphone;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Check extends Activity {
String StringPreference;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
Button b = (Button)findViewById(R.id.Button01);
final EditText preferences = (EditText)findViewById(R.id.txt12345);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText sharedPreferences = (EditText)findViewById(R.id.txt12345);
String StringPreference = preferences.getText().toString();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check, menu);
return true;
}
/**
* Method used to get Shared Preferences */
public SharedPreferences getPreferences()
{
return getSharedPreferences(null, 0);
}
/**
* Method used to save Preferences */
public void savePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences();
SharedPreferences.Editor editor = preferences.edit();
String StringPreference = sharedPreferences.toString();
editor.putString("sharedString", StringPreference);
editor.commit();
}
/**
* Method used to load Preferences */
public String loadPreferences(String key)
{
try {
SharedPreferences sharedPreferences = getPreferences();
String strSavedMemo = sharedPreferences.getString(key, "");
return strSavedMemo;
} catch (NullPointerException nullPointerException)
{
Log.e("Error caused at TelaSketchUtin loadPreferences method",
">======>" + nullPointerException);
return null;
}
}
/**
* Method used to delete Preferences */
public boolean deletePreferences(String key)
{
SharedPreferences.Editor editor=getPreferences().edit();
editor.remove(key).commit();
return false;
}
{
}
}
I'm not sure, but i think you missed something at this point:
return getSharedPreferences(null, 0);
Look here:
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29
Parameters
name
Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
If you set "name" to null, he cant create a file.
Might be the solution, add this on top
private final String KEY_SHAREDPREFS = "tmpsharedprefs";
and then use it
return getSharedPreferences(KEY_SHAREDPREFS, 0);
See your are trying to get string from preference, first you have to get password from edittext like this code
EditText passwordText = (EditText)findViewById(R.id.txt12345);
String password = passwordText.getText().toString();
and then store this password in shared preferences
Use SharedPreferences as,
To Save:
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "app_pref";
public static final String KEY_p_id = "KEY_test";
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString(Login_screen.KEY_test, values.get(0));
editor.commit();
To Remove:
editor.remove("KEY_test").commit();
To Get:
settings = getSharedPreferences(PREFS_NAME, 0);
String TestId = settings.getString("KEY_test", null);

Android Seek Bar Saved Preferences

Hi there I am trying to get an integer that will be given by a SeekBar using the .getprogress to go into an Integer which will get saved by the preference and will go to my toast code at another side of my application to make things easier heres my code already.
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import tk.mizzeeboy.freestorageconverter.R;
public class SettingsActivity extends Activity{
SeekBar cl;
TextView t;
String lolly , finlly;
int hehe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.333);
cl = (SeekBar) findViewById(R.id.seekB3r1);
t = (TextView) findViewById(R.id.textV3w1);
cl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
t.setTextSize((cl.getProgress()) * getResources().getDisplayMetrics().density);
hehe = cl.getProgress();
finlly.valueOf(hehe);
SharedPreferences mypreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mypreferences.edit();
editor.putString("TeamName", finlly);
editor.commit();
}
});
}
}
and in my other activity I want to open and read it heres the code for that
SharedPreferences mypreferences = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
String teamnamestring = mypreferences.getString("TeamName", "Please Enter :)");
Toast andEggs = Toast.makeText(BitActivity.this, teamnamestring , Toast.LENGTH_SHORT);
andEggs.show();
But my problem is that it I am getting the Please Enter Sign everytime and it will not pick up my integer can someone help?
What TGMCians is saying is that you put hehe as Int in the preferences (editor.putInt("TeamName", hehe);), in first Activity then get it as String in the other Activity (mypreferences.getString("TeamName",...). This will cause ClassCastException. Either, you put it as a String from the begining or get it as an Int in the second Activity.
Try:
int val=mypreferences.getInt("TeamName",-1);
String teamnamestring="";
if(val==-1){
teamnamestring="Please Set Up Your Custom Text Size!";}
else {teamnamestring=String.ValueOf(val);}
Toast andEggs = Toast.makeText(BitActivity.this, teamnamestring , Toast.LENGTH_SHORT);
andEggs.show();

Android Using SharedPreferences to save and retrieve values - Counter

Hello I am new to android and actually i am developing a application whereby the user would be clicking on a button and the button should record the click event - the counter should be incremented at each time the button is clicked. The button would be displayed in one activity and once the user has clicked the button, another activity would be displayed whereby the results would be shown.
Actually i am having problems in assigning the sharedPreferences to the button and then displaying it into the next activity hence having the number of clicks.
The code i am using is as follows:
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/** Declare the variables being used */
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
int counter;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
Intent openClickActivity2 = new Intent("com.android.jay.Results");
startActivity(openClickActivity2);
}
});
}
}
Results.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Results extends MainActivity{
public void onCreate(Bundle savedInstanceState) {
SharedPreferences mGameSettings;
super.onCreate(savedInstanceState);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
}
}
}
Any help to guide me would be much appreciated.Thank you
You will have to set GAME_PREFERENCES_SCORE in MainActivity. Do something like this after counter++:
getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE).edit().setInt(GAME_PREFERENCES_SCORE, counter). commit();
Simply make a Preferences class
public class Preferences {
String MASTER_NAME = "mysticmatrix_master";
SharedPreferences mysticMatrixPref;
Preferences(Context context) {
mysticMatrixPref = context.getSharedPreferences(MASTER_NAME, 0);
}
public void setAddCount(int count) {
SharedPreferences.Editor prefEditor = mysticMatrixPref.edit();
prefEditor.putInt("count", count);
prefEditor.commit();
}
public int getAddCount() {
return mysticMatrixPref.getInt("count", 0);
}
}
and in your MainActivity.java put this code
public class MainActivity extends Activity implements OnClickListener {
ImageButton add;
Preferences cpObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = new Preferences(getApplicationContext());
/*
* getting the count variable and adding 1 in that to check the condition of showing rate activity and adds
*/
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cpObj = new Preferences(getApplicationContext());
cpObj.setAddCount(cpObj.getAddCount() + 1);
}
});
}
}
And in your result activity just get the count's value
import android.content.Context;
public class Results extends MainActivity{
Preferences cpObj;
public void onCreate(Bundle savedInstanceState) {
preferences = new Preferences(getApplicationContext());
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
DisplayResults.setText(cpObj.getAddCount());
}
} }
By this you will get the default value of result as '0' and you can set that in your Preferences class
Use a method like this:
public static void SavePreference(Context context, String key, Integer value) {
SharedPreferences.Editor editor = PreferenceManager
.getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE)
.edit();
editor.putInt(key, value);
editor.commit();
}
and in you onclick after counter++ add this:
SavePereference(context, "GAME_PREFERENCES_SCORE", counter);

How do you save the data of an int, and then edit the number onclick of a button?

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

Categories

Resources