I have a page in my application where the user can enter a product name and it's calorie count, which it then removes from a daily calorie count which comes from another class. This works perfectly I wanted to make it so that it doesn't reset to the original value each time the page is opened (unless its a fresh install / manual reset via a button).
I came across SharedPreferences and tried to implement this, but it always comes up with the default value in my onResume method and I am not too sure why and need some assistance to figure out what I am doing wrong and how to fix it, as I will need to use this in several other classes also.
My Class:
public class CalorieTracker extends AppCompatActivity {
protected String age, calorieCount;
protected EditText itemName, kCal;
protected TextView remainingCalories;
protected Button submitBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_tracker);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
calorieCount = extras.getString("calories");
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount = Integer.parseInt(remainingCalories.getText().toString());
int enteredAmount = Integer.parseInt(kCal.getText().toString());
calorieCount = String.valueOf(currentCount - enteredAmount);
remainingCalories.setText(calorieCount);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sessionCalories",remainingCalories.getText().toString());
editor.commit();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
}
http://prntscr.com/me99dp
Image of what it looks like when I boot the application, even though the initial calorieCount value should be 2100 which I get from the previous page using the Bundle extras.
If I change the
line remainingCalories.setText(mPrefs.getString("sessionCalories","")); in my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3")); then it shows 3 initially.
Make sure that your data is updated in shared preference correctly. In Activity life cycle after onviewCreated only onResume called .
so if your current activity will go to foreground or rotate then only onResume will call again.
so solution ,in button click after set the value and get value from sharedpreference and display like this
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// first time save data
setvalueFromSharedpreference()
}
});
public setvalueFromSharedpreference()
{
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
when I boot the application, even though the initial calorieCount
value should be 2100 which I get from the previous page using the
Bundle extras.
If I change the line
remainingCalories.setText(mPrefs.getString("sessionCalories","")); in
my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3"));
then it shows 3 initially.
Reason editText remainingCalories always have default (sharedpreference value) is because onResume method is called after onCreate in activity's lifecycle. Thats why, Bundle extras value is being overwritten by sharedpreference value.
You can achieve this in onCreate method by checking if Intent extras has value. If yes, then set that value otherwise set the sharedPrefrence's value as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
calorieCount = mPrefs.getString("sessionCalories","");
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
if(!calorieCount.isEmpty)
remainingCalories.setText(calorieCount);
else
{
calorieCount = extras.getString("calories");
}
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
}
And remove the sharedPreference setting from onResume.
Hope it helps cheers:)
Related
I'm developing an app where I have many activites. And when the user ends interacting with the content of each activity it launchs an Activity called WellDone! where the user can see the average of the lessons (it's a course). 100% completed and it has a button for the next lesson. I want to get the name of the previous activities for example activity_lesson1, activity_lesson2 to show in a TextView to have a Title.
When ends the lesson1 it launchs the WellDone! Activity and I want to set in a TextView (title) the name of the lessons that have just learned.
package com.flixarts.ar.**;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class welldone extends AppCompatActivity {
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pantallanextsesion);
title = (TextView)findViewById(R.id.tituloActivity);
title.setText() //Here the title of the previous activity that have come from intent
}
}
My impression is that the answer to the literal question is "no" - you cannot get the name of previous activity. But there's probably another way to accomplish what you need.
If these are all your activities, why not put an extra in the Intent (when going in the forward direction) which says which activity it is coming from.
You can then decide what name of the activity to display based on checking that extra, which should tell you what the previous activity was.
Maybe you could use SharedPreferences, which allow you to easily save some String value in one activity and read it in another. In previous activity e.g activity_lesson1 you could override method onPause (or onDestroy if you finish your activity while proceeding to next one by calling finish() method) and save the name of activity as String like this:
#Override
public void onPause() {
super.onPause();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("LAST_ACTIVITY_NAME", this.getClass().getSimpleName());
editor.apply();
}
Then you can read saved value inside WellDone activity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("LAST_ACTIVITY_NAME", "default_value");
title.setText(lastActivityName);
}
Two ways to pass previous activity name
Use Intent
FirstActivity
String TAG=FirstActivity.class.getSimpleName();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name=nameEt.getText().toString();
mobile_number=mobileEt.getText().toString();
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("Last_Activity_Name",TAG);
startActivity(intent);
}
});
SecondActivity
String lastActivityName;
lastActivityName=getIntent().getStringExtra("Last_Activity_Name");
**use SharedPreferences **
FirstActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Last_Activity_Name", TAG);
editor.apply();
SecondActivity
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String lastActivityName = sharedPref.getString("Last_Activity_Name",
"default_value");
title.setText(lastActivityName);
I would like to store a few values from an Activity so that when I navigate away from the activity, they still appear there.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
}
});
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
You can store these values by using SharedPreferences.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
// You can store these values here
// ...
}
});
protected void onResume() {
// And read these values here and set to your ResultTxtView.
// ...
}
You can use shared preferences in your app for saving the data and for using the same data later as mentioned below:
SharedPreferences sp = getSharedPreferences("Data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name", "Alex");
editor.putString("Email", "alex#gmail.com");
editor.commit();
And then if you want to get the same data in another activity you do this as mentioned below:
SharedPreferences sp= ActvivityA.this.getSharedPreferences("Data",Context.MODE_PRIVATE);
String name = sp.getString("Name");
String email = sp.getString("Email");
This data will be saved till you will not clear the cache of the application or you will not install a new update of the app so in this way you can use this data anywhere in the app.
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
When you need the values to be persisted across app launches, then Shared Preferences or a data store like SQLite/Room would be the way to go.
Shared Preferences : If the values stored are key value pairs and are limited in size and does not have to scale, then Shared Preference would suit your need.
SqLite : If the data that you store would scale and would become larger in time, then you need to look at a data store like SQLite where you can do Async operations.
create on class which extends Application and create variable to hold specific value and register that class in manifest
in manifest in application tag specify your application class name
public class MyApplication extends Application {
private MyApplication sInstance;
int result;
//write getter setter for result variable same for num1 and num2
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static MyApplication getInstance() {
return sInstance;
}
}
in onClick set that variable value like MyApplication.getInstnce().setResult();
and in onCreate of set textview value with MyApplication.getInstance().getResult();
Use Following methods for save/retrieve string using SharedPreferences
public static int getIntPreferences(Context context,String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
int savedPref = sharedPreferences.getInt(key, null);
return savedPref;
}
public static void saveIntPreferences(Context context,String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
Save num1,num2 and result using saveIntPreferences when you leave 1st Activity.
After getting back on 1st Activity, you can get saved value using getIntPreferences
I am trying to create a method that saves a score in my app. It was previously in the onCreate method, and I thought that was why every time I started the app the users score was set Back to 0. I have since then changed it to an onStart method (line 14-19) which does the exact same thing. Should I be using a different method? I have successfully saved the score, but would I need to call it back within the onStart method?
public class MainActivity extends Activity implements OnClickListener {
TextView textView1;
EditText editText1;
Button button1;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);}
public void onStart(){
super.onStart();
SharedPreferences score = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = score.edit();
editor.putInt("key", counter);
editor.commit();
textView1 = (TextView)findViewById(R.id.textView1);
editText1 = (EditText)findViewById(R.id.editText1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);}
public void onClick(View v){
if (v == button1){
counter++;
editText1.setText(Integer.toString(counter));
}
}
}
You can use:
1. SharedPreferences or store highscores in a file in storage.
2. Alternately, you can use firbase to store highscores online.
3. Use both of these while keeping in mind internet availability
i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();
I have an issue with my app where if I navigate to the about activity while I'm in the result activity,the TextView values are cleared.I have tried so far by setting the about activity to finish() when I navigate back to result activity but that didn't work.I'm wondering if there is a way to store the values so they don't get wiped when I navigate away? I have shown in screenshots below what I'm talking about.
Just save this into Temporary preferences. then retrieve whenever you want
To save
SharedPreference preferenece = getSharedPreference("File Name", MODE_PRIVATE);
preference.edit().putString("Mark1").commit();
To Retrieve
SharedPreference preferenece = getSharedPreference("Pref File Name", MODE_PRIVATE);
String mark1 = preference.getString("Mark1");
then pass it back to TextView or whatever
I do so (meing mark# string variables or arrMark an array of strings):
#Override
protected final void onSaveInstanceState(final Bundle outState)
{
// Save variables.
outState.putString("mark1", mark1);
outState.putString("mark2", mark2);
outState.putString("mark3", mark3);
// ...
// or better, if you have your values in a string array:
outState.putStringArray("marks", arrMarks);
}
#Override
protected final void onRestoreInstanceState(final Bundle outState)
{
// Restore saved variables and reshow activities if they were open.
mark1 = outState.getString("mark1", "");
mark2 = outState.getString("mark2", "");
mark3 = outState.getString("mark3", "");
// ...
// or better, if you have your values in a string array:
arrMarks = outState.getStringArray("marks");
}