Activity calling itself -: Shared Preferences being cleared on pressing back button - android

I am using the following activity that keeps on calling itself. Things are working fine when I go in the forward direction but as soon as I click the back button, the shared preferrences is cleared.
SharedPreferences userLocalDatabase;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paper_dashboard);
userLocalDatabase = PreferenceManager.getDefaultSharedPreferences(this);
name = userLocalDatabase.getString("name", "");
subject = userLocalDatabase.getString("subject", "");
timeLeft = userLocalDatabase.getInt("timeLeft", -1);
quesNo = userLocalDatabase.getInt("quesNo", -1);
no_of_ques = userLocalDatabase.getInt("no_of_ques", -1);
score = userLocalDatabase.getInt("score", -1);
currentLine = quesNo+1;
Log.i("TAG2", "Krishna the score returned from Shared Preferences is -: " +score);
myQuesTitle = (TextView)findViewById(R.id.myQuesTitle);
myTimer = (TextView)findViewById(R.id.myTimer);
myQuestion = (TextView)findViewById(R.id.myQuestion);
myFinish = (ImageButton)findViewById(R.id.myFinish);
myPrevious = (ImageButton)findViewById(R.id.myPrevious);
myAnswer = (ImageButton)findViewById(R.id.myAnswer);
myHint = (ImageButton)findViewById(R.id.myHint);
myNext = (ImageButton)findViewById(R.id.myNext);
myAnswer1 = (CheckBox)findViewById(R.id.myAnswer1);
myAnswer2 = (CheckBox)findViewById(R.id.myAnswer2);
myAnswer3 = (CheckBox)findViewById(R.id.myAnswer3);
myAnswer4 = (CheckBox)findViewById(R.id.myAnswer4);
String line = setLayout(name, timeLeft, quesNo, no_of_ques);
Log.i("TAG2", "Krishna the line returned is -: " + line);
}
this is the method for calling -:
public void clickPrevious(View v){
calculateScore();
SharedPreferences.Editor spEditor = userLocalDatabase.edit();
spEditor.putString("name", name);
spEditor.putString("subject", subject);
spEditor.putInt("timeLeft", timeLeft);
spEditor.putInt("no_of_ques", no_of_ques);
spEditor.putInt("quesNo", 0);
spEditor.putInt("score", 0 );
spEditor.commit();
Log.i("TAG2", "Baladeva score is -: " + score);
finish();
startActivity(new Intent(paper_dashboard.this, paper_dashboard.class));
}
posting the Next method-:
public void clickNext(View v){
calculateScore();
SharedPreferences.Editor spEditor = userLocalDatabase.edit();
spEditor.putString("name", name);
spEditor.putString("subject", subject);
spEditor.putInt("timeLeft", timeLeft);
spEditor.putInt("no_of_ques", no_of_ques);
spEditor.putInt("quesNo", quesNo+1);
spEditor.putInt("score", score);
spEditor.commit();
Log.i("TAG2", "Baladeva score is -: " + score);
Intent intent = new Intent(new Intent(this, paper_dashboard.class));
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}

Related

How to calculate a key with integer value from SharedPreferences

I want to calculate 2 values with key from SharedPreferences.
This is my code
This is my first activity
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A1, option_scoreA1);
editor.commit();
Intent intent = new Intent(QuestionActivity.this, SecondActivity.class);
startActivity(intent);
This is my second activity
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A2, option_scoreA4);
editor.commit();
Intent intent = new Intent(SecondActivity.this, TestFinalActivity.class);
startActivity(intent);
This is my final activity
protected QuestionActivity activity1;
protected SecondActivity activity2;
String c = activity1.A1;
String b = activity2.A2;
String A = c + b ;
#Bind(R.id.hasil)
TextView hasil;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
total();
}
public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(A);
}
I want to totalize each value from key A1 and A2. But what i got was the key, not the value when I totalize them.
Thank you
It is because you add or concatenate the keys into variable A. And you want to calculate the int so you should better put the total result into float or int data type, right?
Do something as shown below
very fist of all make two keys as your instance filed in QuestionActivity class
public static final String KEY_A = "ka";
public static final String KEY_B = "kb";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int a = sharedPreferences.getInt(QuestionActivity.KEY_A, 0);
int b = sharedPreferences.getInt(QuestionActivity .KEY_B, 0);
A = a+b;
total();
}
and since it is integer, you need to cast the result into string format.
public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(String.valueOf(A));
}
SharedPreference starting guide
access to value in SharedPreferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int value1 = preferences.getInt("your key", default_value);
int value2 = preferences.getInt("your key", default_value);
First create sharedpreferences and then get values of your keys.
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
int c = pref.getInt(A1, 0) // here A1 is the key and 0 is default value
int b = pref.getInt(A2, 0) // here A2 is the key and 0 is default value
int A = c + b;

SharedPreferences have some problems

I create a mini game . The User need to answer my question in 2 seconds, if user answer true , the score will increase 1 , and if user answer wrong - Game over and the score become to 0.
I want to use SharedRefences so that I can save the score when the user play again . But it's not working .
My CountDownTimer:
public void start_game() {
flag = false;
btnTrue.setClickable(true);
btnWrong.setClickable(true);
a = (int) (Math.random() * 6);
b = (int) (Math.random() * 6);
sum = (int) (Math.random() * 11);
tvDetails.setText(a + " + " + b + " = " + sum);
proTime.setSecondaryProgress(0);
timer = new CountDownTimer(3000, 10) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
btnTrue.setClickable(false);
btnWrong.setClickable(false);
if (flag) {
tmp++;
tvScore.setText("" + tmp);
start_game();
} else {
ShowDialogs();
tmp = 0;
tvScore.setText("" + tmp);
}
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
proTime.setSecondaryProgress(proTime.getSecondaryProgress() + 10);
}
};
timer.start();
}
public void ShowDialogs() {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(false);
tvNowScore = (TextView) dialog.findViewById(R.id.NowScore);
tvHighScore = (TextView) dialog.findViewById(R.id.HighScore);
ImageView btnRep = (ImageView) dialog.findViewById(R.id.Rep);
ImageView btnExit = (ImageView) dialog.findViewById(R.id.Exit);
ResPreferences();
int HighScore = Integer.parseInt(tvHighScore.getText().toString());
int Score = Integer.parseInt(tvScore.getText().toString());
if (Score > HighScore) {
HighScore = Score;
SavingPreferences();
}
tvNowScore.setText("" + Score);
tvHighScore.setText("" + HighScore);
btnExit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.exit(0);
}
});
btnRep.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
if (timer != null) {
timer.cancel();
timer = null;
}
start_game();
}
});
dialog.show();
}
I can't save a score when the game finish.
This is my Save Preferences
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
editor.putString("HighScore", HighScore);
editor.commit();
}
This is Restrore Pre:
public void ResPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = pre.getString("HighScore", "0");
tvHighScore.setText(score);
}
Try this :
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = null;
if(pre.contains("HighScore")){
score = pre.getString("HighScore", "0");
}
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
if(score != null && Integer.parseInt(score) > Integer.parseInt(HighScore )){
editor.putString("HighScore", score);
} else {
editor.putString("HighScore", HighScore);
}
editor.commit();
}

Variable Stays Null

I'm trying to pass a String between activities, From YtAdapter to Favorites.
YtAdapter:
mHolder.mVideoFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//////////////////////////////////////////////////////////////
// Need to send SearchResult result from here to favorites //
////////////////////////////////////////////////////////////
AppUtils.showToast(result.getSnippet().getTitle() + " Was added to favorites.");
Intent intent = new Intent(mActivity,Favorites.class);
String vidId,vidTitle,vidThumbnail;
vidId = result.getId().getVideoId(); //Video ID
vidTitle = result.getSnippet().getTitle(); //Video Title
vidThumbnail = result.getSnippet().getThumbnails().getMedium().getUrl(); //Video Thumbnail
intent.putExtra("id",vidId);
intent.putExtra("title",vidTitle);
intent.putExtra("thumbnail",vidThumbnail);
}
});
And try to get it in Favorites:
/*Getting video information from YtAdapter*/
vidID = getIntent().getStringExtra("id"); <--- Stays null
vidTitle = getIntent().getStringExtra("title"); <--- Stays null
vidThumbnail = getIntent().getStringExtra("thumbnail"); <--- Stays null
I'm accessing Favorties from 3rd activity, not straight from YtAdapter.
try this in your main class:
Intent i = new Intent(ListViewActivity.this, EditContact.class);
Bundle bundle = new Bundle();
bundle.putInt("index", itemId);
bundle.putBoolean("AddContact", false);
i.putExtras(bundle);
startActivity(i);
and you can get your data in the other class like this:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Int index = bundle.getInt("index");
Boolean bool = bundle.getBoolean("AddContact");
if (bool ) {
setTitle("Add Contact");
} else {
setTitle("Edit Contact");
}
I hope it will help.
you can force all of your parameter be a string value:
intent.putExtra("id",vidId +"");
intent.putExtra("title",vidTitle+"");
intent.putExtra("thumbnail",vidThumbnail+"");
probally they aren't and you are getting with "getStringExtra".
but the better options is you use te correct "getter" of extra.
---Edit---
you can check in your activity the keys and values this way:
for(String key : getIntent().getExtras().keySet()){
Log.d("TEST", "key: " + key);
Log.d("TEST", "value: " + getIntent().getExtras().get(key));
}

getIntent() not capturing data properly

I am passing row id with the help of intent. The calling method being a custom adapter -
holder.text.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "TEXT CLICKED" + pos , Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,ReminderModificationActivity.class);
long longPos = (long)pos;
intent.putExtra(TasksDBAdapter.KEY_ROWID, pos);
Log.i(TAG, "row clickd --> " + longPos);
((Activity) context).startActivityForResult(intent, ACTIVITY_EDIT);
}
});
OnCreate() method of ReminderModificationActivity try to retrieve the data.Code -
protected void onCreate(Bundle savedInstanceState){
dbHelper = new TasksDBAdapter(this);
//set current theme
settingsDBAdapter = new SettingsDBAdapter(this);
settingsDBAdapter.open();
setSettingsTheme();
setContentView(R.layout.reminder_modify);
mCalendar = Calendar.getInstance();
Log.i(getLocalClassName(), "VALUE of Button--->" + findViewById(R.id.SetDateButtonId));
mDateButton = (Button) findViewById(R.id.SetDateButtonId);
mTimeButton = (Button) findViewById(R.id.SetTimeButtonId);
mConfirmButton = (Button) findViewById(R.id.SaveButtonId);
mTitleText = (EditText) findViewById(R.id.TitleEditTextId);
mBodyText = (EditText) findViewById(R.id.DescriptionEditTextId);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(TasksDBAdapter.KEY_ROWID) : null ;
registerButtonListenersAndSetDefaultText();
Log.i(TAG, "getIntent-->" + getIntent() + mRowId);
//code to check what row id have been passed
if(getIntent() != null) {
---->>>MAIN CODE
Log.i(TAG, "mRowId in getintent-->" + mRowId + "row id passed-->" + getIntent().getLongExtra(TasksDBAdapter.KEY_ROWID, -1));
mRowId = getIntent().getLongExtra(TasksDBAdapter.KEY_ROWID, -1);
// Do stuff with the row id here
if(mRowId != -1){
//code if RowId valid
}
}
super.onCreate(savedInstanceState);
Log.i(TAG, "mROwId in onCreate ReminderNotification again-->" + mRowId);
}
line marked as MAIN CODE captures the intent data but Log.i gives value of
getIntent().getLongExtra(TasksDBAdapter.KEY_ROWID, -1))
as -1.Can sumone please help me out on this.Thanks in advance,Ray
Seeing as you cast pos to longPos, you should be using longPos in your intent extra, but you use pos.
if you were to change your code to:
Intent intent = new Intent(context,ReminderModificationActivity.class);
long longPos = (long)pos;
intent.putExtra(TasksDBAdapter.KEY_ROWID, longPos); //<< changed to longPos
It should work

android shared preferences implementation

hi i have tried to implement a shared preference and everything i try doesn't seem to work. i'm wanting when someone clicks on an item in a list view it stores data about that selection in a shared prerference. when the app loads up i want it to check for a shared preference ie: if there are no preferences go to this activity else go to another activity. i also would like to know if there are some preferences when i get sent to another activity how to retrieve them. its not the first time i have asked this question but i thought id re ask as i wasn't very clear
heres what i have tried so far
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
try {
Log.v("lc", "try1");
JSONObject singleTeamDictionary = teamNamesArray.getJSONObject(position);
Log.v("lc", "dictionary:" + singleTeamDictionary);
Log.v("lc", "try2");
ChosenTeam = (String) singleTeamDictionary.get("name");
ChosenTeamId = (String) singleTeamDictionary.get("team_id");
ChosenLeagueId = (String) singleTeamDictionary.get("league_id");
ChosenDivisionID = (String) singleTeamDictionary.get("division_id");
Log.v("lc", "try3");
Log.v("lc", "ChosenTeam: " + ChosenTeam);
Log.v("lc", "ChosenTeamId: " + ChosenTeamId);
Log.v("lc", "ChosenLeagueId: " + ChosenLeagueId);
Log.v("lc", "ChosenDivisionID: " + ChosenDivisionID);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("lc", "catch");
}
String curPos = Integer.toString(position);
Log.v("lc", "teamPos: " + curPos);
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ChosenMethod", "Team");
editor.putString("ChosenTeam", ChosenTeam);
editor.putString("ChosenTeamId", ChosenTeamId);
editor.putString("ChosenLeagueId", ChosenLeagueId);
editor.putString("ChosenDivisionID", ChosenDivisionID);
editor.commit();
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
then in the intro activity
public void checkPreferences(){
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
String ChosenMethod = preferences.getString("chosenTeam", ChosenTeam);
//String ChosenMethod = preferences.getString("ChosenMethod", null);
//getPWDFromSP()
//SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//Log.v("myapp", "prefs = " + preferences);
//String ChosenMethod = preferences.getString("ChosenMethod", chosenMethod);
Log.v("myapp", "ChosenMethod = " + ChosenMethod);
if (ChosenMethod != null){
Intent intent = new Intent(TheEvoStikLeagueActivity.this,Activity.class);
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
checkPreferences();
"chosenTeam" is not the same as "ChosenTeam".
hope this code helps you
private SharedPreferences sp;
private Editor e;
//create methods
//save method(string)
private void savePreferences(String key,String val){
sp = getSharedPreferences("prefs", 0);
e = sp.edit();
e.putString(key , val);
e.commit();
}
//get method
private String getPreferences(String key){
sp = getSharedPreferences("prefs", 0);
String value = sp.getString(key, "");
return value;
}
//save String
savePreferences("yourKey","yourString");
//get Preferences
getPreferences("yourKey")
//check value saved or not
if(getPreferences("yourKey").equals(null)){
//do something
Log.i("value","null");
}
else{
//do something
Log.i("value","exists");
}
if you want to save integers or boolean,you can edit methods
and let return values as you wish.

Categories

Resources