setText() method resetting after user exits activity - android

So when the user clicks the button i want it to set the text to a future time. It works but when the user closes the activity the buttons reset. Also if someone could also guide me on creating a method that resets the button text after time is reached. Heres my code to setText on the button.
private void setReloadTime(int reload, Button btn) {
int minutes = (reload/1000/60)%60;
int hours = reload/1000/60/60;
Calendar c = Calendar.getInstance();
int min = c.get(Calendar.MINUTE);
int hr = c.get(Calendar.HOUR_OF_DAY);
if (reload ==0){
btn.setTextColor(R.color.colorAccent);
btn.setText("Ready Again In 24 Hours");
return;
}
if (minutes+min>60) hr++;
int finMin = (minutes + min) %60;
int finHr= (hours + hr)%24;
String fin = "Ready again at " +finHr + ":";
if (finMin<10){
fin = fin +"0"+finMin;
} else{
fin = fin + finMin;
}
btn.setTextColor(R.color.colorAccent);
btn.setText(fin);
}

Use shared preference
Eg:
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString(Name, fin);
editor.commit();
if (sharedpreferences.contains(Name))
{
btn.setText(sharedpreferences.getString(Name, ""));
}
http://www.tutorialspoint.com/android/android_shared_preferences.htm

You should save that state of your application (Button, time etc) in SharedPreferences. On Reloading activity read from that

Related

WearOS watch that records and sends stepCounts as message via Bluetooth to Phone. The phone app's textview for step update is not syncing instantly

I am trying to debug the slow sync between wearOS watch that records and sends step counts as messages via Bluetooth to its companion Android App? It has a delay when storing it to SharedPreferences and sometimes it doesn't even update until the next message is sent by watch and received by phone. When logging the results received and stored in the app it shows the most up-to-date one, but the view does not refresh to update the UI with the new data that came in.
The steps view needs to be updated with this class. I thought that UI is not being updated even though the step count is being received.
public class ActivityRecord extends Activity {
TextView step_count;
TextView sitting_duration,sitting_title;
TextView distance_cover;
TextView walk_value;
ImageView walk, step,distance_covr,sitting;
ImageView maintenence, men_badge;
TextView men_text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_updated);
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
SharedPreferences pref = getApplicationContext().getSharedPreferences("StoreTodayDate", MODE_PRIVATE);
String dateNow=pref.getString("todayDate",null);
walk=(ImageView) findViewById(R.id.progress_walk);
step=(ImageView) findViewById(R.id.progress_step);
distance_covr=(ImageView) findViewById(R.id.progress_distance);
sitting=(ImageView) findViewById(R.id.progress_sit);
Picasso.with(this).load(R.drawable.progress_walk).into(walk);
Picasso.with(this).load(R.drawable.progress_step).into(step);
Picasso.with(this).load(R.drawable.progress_distance).into(distance_covr);
Picasso.with(this).load(R.drawable.progress_sedentary).into(sitting);
walk_value=(TextView) findViewById(R.id.walking_val);
step_count=(TextView) findViewById(R.id.step_count_val);
sitting_duration=(TextView) findViewById(R.id.sitting_val);
distance_cover=(TextView)findViewById(R.id.distance_covered_val);
step_count.invalidate();
if(date.equals(dateNow)){
// setting walk_value
SharedPreferences sharedPreferencesForActivityRecord = getSharedPreferences("activity_val",MODE_PRIVATE);
float testWalk= sharedPreferencesForActivityRecord.getFloat("walk_duration", 0);
float testStepCount=sharedPreferencesForActivityRecord.getFloat("step_count_value", 0);
float testSitting=sharedPreferencesForActivityRecord.getFloat("sitting_duration", 0);
int heartRateToStore=sharedPreferencesForActivityRecord.getInt("heart_rate", 0);
int Sit_sec = (int) testSitting % 60;
int Sit_min = (int) ((testSitting / 60));
Log.d("Phone: "," Walk Value Before Calculation: "+testWalk);
int Walk_sec = (int)testWalk % 60;
int Walk_min =(int)(testStepCount/110); //(int)((testWalk / 60));
// walk value
// String valueToPutWalk=String.format("%d Min %d Sec",Walk_min,Walk_sec);
String valueToPutWalk=String.format("%d min",Walk_min);
if(stepValuetoSet!=0){
walk_value.setText(valueToPutWalk);
}else{
walk_value.setText("0");
}
//setting sitting duration;
String sitting_value=String.format("%d min",Sit_min);
sitting_duration.setText(sitting_value);
float in_mile=(float) (testStepCount/2000);
String dis_in_mile=String.format("%.2f miles",in_mile);
distance_cover.setText(dis_in_mile);
}else {
SharedPreferences.Editor editor2 = pref.edit();
editor2.putString("todayDate", date);
editor2.commit();
SharedPreferences.Editor editor21 = getSharedPreferences("activity_val", MODE_PRIVATE).edit();
editor21.putFloat("walk_duration",0);
editor21.putFloat("sitting_duration",0);
editor21.putFloat("step_count_value",0);
editor21.commit();
walk_value.setText("0 Min");
step_count.setText("0");
sitting_duration.setText("0 Min");
distance_cover.setText("0 miles");
SharedPreferences.Editor editor = getSharedPreferences("set_goal", MODE_PRIVATE).edit();
editor.putInt("walk_target", 0);
editor.commit();
}
}
public void refreshScreen(View view){
Intent intent=new Intent(this, ActivityRecord.class);
intent.putExtra("from","ActivityRecord");
startActivity(intent);
}
public void timeRemainButtonClicked(View view) {
Intent intent=new Intent(this,RemainingActivity.class);
intent.putExtra("from","intervention");
startActivity(intent);
}

SharedPreferences not saving all the data after restart

I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");

save and call Stringbuilder from Sharedpreference [duplicate]

This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 6 years ago.
I 'm testing with some iteration with the coding below, with help of Stringbuilder and want to directly save the outcome to Sharedpreference.
save2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
int i;
int n = 10;
StringBuilder outoutcome = new StringBuilder();
for (i = 0; i <= n; i++) {
outoutcome.append(i + "\n");
}
SharedPreferences sharedPreferences = getSharedPreferences("data1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("outcome1", outoutcome.toString());
}
}
*I also tried editor.putString("outcome1", String.valueOf(outoutcome)); but unfortunately cannot.
for the retrieve of data in another activity, I had tried using coding below :
public static final String DEFAULT = "";
final SharedPreferences sharedPreferences = getSharedPreferences("data1", Context.MODE_PRIVATE);
final String out1 =sharedPreferences.getString("outcome1", DEFAULT);
resultout.setText("Saved data is " + out1 );
but the coding above not working. Then, I searched and found this , tried the code as below but still not working.
final String[] getout1= out1.split(",");
resultout.setText("Saved data is " + getout1 );
Can anyone help here? Thank you in advanced !
You have to use apply() or commit() to save the changes.
editor.apply();
or
editor.commit();

Strange behaviour with Fragment UI on load

Okay, so I have a Android App that uses the built in NavigationDrawer Activity with Fragments for each view. One of the views pulls some data from a web service, but since the data doesn't change during a single day I store the values in the preferences as well as a timestamp for the day the tab was opened so that web service method isn't called every time the user opens that tab. The problem that I'm having though is that when the timestamp section just moves to the part of the code that updates the view some items aren't being drawn correctly (some are squished down while others aren't showing the correct placement on the screen). If I click the refresh button to call the web service methods and then update the view that way it always draws them correctly. I don't know where I'm messing up, but I'm sure it's me since Android is pretty new to me.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sales, container, false);
thisActivity = this.getActivity();
mtdHeaderTextView = (TextView)rootView.findViewById(R.id.mtdHeaderText);
mtdSeekBar = (SeekBar)rootView.findViewById(R.id.mtdSeekBar);
mtdTopSeekBar = (SeekBar)rootView.findViewById(R.id.mtdTopSeekBar);
mtdValueTextView = (TextView)rootView.findViewById(R.id.mtdValueTextView);
mtdGoalTextView = (TextView)rootView.findViewById(R.id.mtdGoalTextView);
mtdDateTextView = (TextView)rootView.findViewById(R.id.mtdDateTextView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
CheckTimeStamp();
}
public static void CheckTimeStamp() {
SharedPreferences preferences = HelperClass.PreferenceFileName(thisActivity);
String timeStamp = preferences.getString(Constants.keySalesTimeStamp, "");
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String currentTime = HelperClass.GetSimpleDateFormat(date);
if (currentTime.equals(timeStamp)) {
foundMTDValue = preferences.getString(Constants.keyMTDValue, "");
foundYTDValue = preferences.getString(Constants.keyYTDValue, "");
UpdateMTDProgress();-->this is the method that adds values to the textviews and seekbars
}
else {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constants.keySalesTimeStamp, currentTime);
editor.apply();
GetMTDValue(); -->this calls the web service to get values and then calls UpdateMTDProgress like above
}
}
Below is the code from the UpdateMTDProgres section
public static void UpdateMTDProgress() {
//First update Header Text View
SharedPreferences preferences = HelperClass.PreferenceFileName(thisActivity);
int mtdGoal = preferences.getInt(Constants.keyMonthlyGoal, 0);
double percentage = Double.parseDouble(foundMTDValue) / mtdGoal;
NumberFormat format = NumberFormat.getPercentInstance();
String percentageString = format.format(percentage);
mtdHeaderTextView.setText("MTD Commissions (" + percentageString + ")");
//Get Current Date and Number of Days in Month
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
int totalDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//Get Daily Goal for Rep based on mtdGoal and number of days
int dailyGoal = mtdGoal/totalDays;
//Get current day goal
int currentDayGoal = dailyGoal * currentDay;
//Check if current mtd value against currentdaygoal
if (Double.parseDouble(foundMTDValue) >= currentDayGoal) {
mtdSeekBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.seekbar_green));
}
else {
mtdSeekBar.setProgressDrawable(thisActivity.getResources().getDrawable(R.drawable.seekbar_red));
}
//update progress seekbar values
mtdSeekBar.setMax(mtdGoal);
mtdSeekBar.setProgress((int) Double.parseDouble(foundMTDValue));
//update indicator seekbar values
mtdTopSeekBar.setMax(totalDays);
mtdTopSeekBar.setProgress(currentDay);
//Update Current Value and Goal TextViews
String currentValueString = HelperClass.ConvertStringToCurrency(foundMTDValue);
mtdValueTextView.setText(currentValueString);
String goalValueString = HelperClass.ConvertStringToCurrency(String.valueOf(mtdGoal));
mtdGoalTextView.setText(goalValueString);
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd");
String shortDate = dateFormat.format(date);
mtdDateTextView.setText(shortDate);

How to save value in SharedPeference in the actitvity and access it all other classes

I want to save totalBalance in this activity to SharedPreferances and the retrive it in another class.
so i want totalbalance to be displayed in another activities in same application...
if possible also edit it in other activites...
please help... thanks
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
// Genrating random number Random number
Random rn = new Random();
randomNumber = (int) rn.nextInt(9) + 1;
// changes textView1 equals to random number
textView1.setText("Random Number is "
+ Integer.toString(randomNumber));
button1.setText("Play Again");
// Matching random number to ArrayList
if (positive_IDs.contains(randomNumber)) {
// if matched then changes textView2 to Matched Number
textView2.setText("Number: "
+ Integer.toString(randomNumber) + " Matched");
totalBalance = totalBalance + winingPrize;
textView5.setText("Total Balance = Rs: "
+ String.format("%.2f", totalBalance));
}
}
try this,
public void saveValue(String lock, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("Value", lock);
editor.commit();
}
public String getValue(Context context) {
SharedPreferences savedvalue = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedvalue.getString("Value", "");
}
Save Value as Following
int Value;
private void saveValues(){
SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE);
SharedPreferences.Editor editor = readSP.edit();
editor.putString("String", Value);
editor.commit();
}
Retrive value in any of your Class As following
int value;
private void getSavedValue()
{
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE);
value=settings.getString("String", "");
}
// try this
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("balance", String.format("%.2f", totalBalance));
editor.commit();
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
String total = sharedPreferences.getString("balance");
Use following code to retrive your value from SharedPreference,write this in other class where you want to retrive value of total balance
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
Editor edit1 = remembermepref.edit();
edit1.putInt("totalbalance_key",totalBalance);
edit1.commit();
and to store total balance into ShardPreference use in your activity:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int totalbalance = pref.getInt("totalbalance_key");
Now use totalbalance way you want.
Most important thing is to check whether you have used same key to restore as well as tostore the value in SharedPreference
Hope this helps..

Categories

Resources