How to save time that Tick in Chronometer with SharedPreferences - java

As we know to save something like int value's we use this
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Something", "Value");
editor.commit();
}
now my question how to save something like chronometer time with sharedpreferences? as we know chronometer code like this
focus = (Chronometer) findViewById(R.id.chronometer1);
focus.setOnChronometerTickListener(new OnChronometerTickListener(){
#Override
public void onChronometerTick(Chronometer cArg) {
long time = SystemClock.elapsedRealtime() - cArg.getBase();
int h = (int)(time /3600000);
int m = (int)(time - h*3600000)/60000;
int s= (int)(time - h*3600000- m*60000)/1000 ;
String hh = h < 10 ? "0"+h: h+"";
String mm = m < 10 ? "0"+m: m+"";
String ss = s < 10 ? "0"+s: s+"";
cArg.setText(hh+":"+mm+":"+ss);
}
});
to start the chronometer, put this in a button called "Button Start"
focus.setBase(SystemClock.elapsedRealtime());
focus.start();
to stop the chronometer, put this in a button called "Button Stop"
focus.stop();
Ok, so my question is how to save the chronometer time/tick if "Button Stop" was pressed? Thank's

Using your terminology, you have to put this piece of code:
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Something", "Value");
editor.commit();
into your 'Button Stop' OnClickListener
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//here
}
});

Related

How to show dialog box once in a three days in application

Here is my code it is working please tell me code button for "no thanks" if user tap on this button then dialog box never show at all
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid,url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id,version,ver;
ImageView mega4,todayTips,latstnews,sportquiz,tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+"since you have already used it %totalLaunchCount% times! "
+"It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
Here is my code actually i want to implement app rating dialog box in application that should display once in three day
You have to initialize your SharedPreferences and Editor Object like this:
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
UPDATE
Just save a boolean when user cliks on no thanks and check it before showing the dialog. If it true then it will not show the dialog box.
//Saving a boolean on no thanks button click
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true));
editor.apply();
Access it in your dialog showing method.
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
if (prefs.getBoolean("NO THANKS", false)) {
return;
}else {
SharedPreferences.Editor editor = prefs.edit();
//YOUR CODE TO SHOW DIALOG
editor.apply();
}
FULL CODE
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid, url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id, version, ver;
ImageView mega4, todayTips, latstnews, sportquiz, tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
if (sharedPrefs.getBoolean("NO THANKS", false)) {
return;
} else {
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
//YOUR CODE TO SHOW DIALOG
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
prefsEditor.apply();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
//Saving a boolean on no thanks button click
SharedPreferences prefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true);
editor.apply();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+ "since you have already used it %totalLaunchCount% times! "
+ "It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
here is my code as a function for 10 days.
I made the initial value current time - 11 days to make sure it will run first time app launches
public void dialogEvery10Days() {
Long duration = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getLong("duration", System.currentTimeMillis()-TimeUnit.DAYS.toMillis(11));
if (System.currentTimeMillis()-duration > TimeUnit.DAYS.toMillis(10)) {
// inflateDialog is a function containing the functionality of popping up the dialog
Dialog dialog = inflateDialog(R.layout.dialog_layout);
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putLong("duration", System.currentTimeMillis())
.apply();
}
}

SharedPreferences not working/saving data from EditText field

I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?
My main java activity(relevant bit of code) is:
public class MainActivity extends AppCompatActivity {
private String s;
public static final String subjectKey = "SubjectID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);
TextView calc_monday = (TextView) findViewById(R.id.monday_calc);
calc_monday.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.show();
TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);
String text = sharedPreferences.getString(subjectKey, " ");
if(text != " ")
{
text1.setText(text); /* Edit the value here*/
}
TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
text2.setText("6 (SEECS)");
TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
text3.setText("09:00am - 09:50am");
}
}
);
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
SDC.show();
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
return true;
}
}
);
Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)
Please see the 2 methods: onClick and onLongClick to understand.
The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.
What's wrong with the code
When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
SDC.dismiss();
}
});
SDC.show();
return true;
}
}
);
I think it's should be :
String text = sharedPreferences.getString("Name", " ");
Try these methods for saving and loading Strings with preferences:
//save prefs
public void savePrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
//get prefs
public String loadPrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString(key, value);
return data;
}
You can call the load method like this:
subjectKey = loadPrefs("YouCanNameThisAnything", subjectKey);
And you can call the save method like this:
savePrefs("YouCanNameThisAnything", subjectKey);
More details on how to use shared preferences is also available in the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
//create and initialize the intance of shared preference
SharedPreferences sharedPreferences = getSharedPreferences("Session", MODE_PRIVATE);
//save a string
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(subjectKey , texii.getText().toString());
edit.commit();
//retrieve the string
String subject = sharedPreferences.getString(subjectKey, "");

Store Value in SharedPreference across Activities

I am new in Android, and got a task to develop a small project to submit in my college, i have tried my best but now i need some help
Let me tell you first, what i am trying to do ?
I have two Activities, MainActivity and AccountActivity
In MainActivity i am using button to switch to AccountActivity
In AccountActivity i am trying to store strBalance value in SharedPreference but whenever i do click on back button and then again come to AccountActivity always getting "1000" not that value which i have stored in SharedPreference.
Here is the complete code of AccountActivity.java:-
public class AccountActivity extends Activity {
EditText editAmount;
int strAmount;
Button btnPayment;
TextView textBalance;
int strBalance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
editAmount = (EditText) findViewById(R.id.editAmt);
btnPayment = (Button) findViewById(R.id.btnPay);
textBalance = (TextView) findViewById(R.id.textBalance);
strBalance = 1000;
textBalance.setText("Your current balance is: $ "+strBalance);
btnPayment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
strAmount = Integer.parseInt(editAmount.getText().toString().trim()); // user input
if(strAmount>strBalance) {
Toast.makeText(AccountActivity.this, "You don't have enough balance", Toast.LENGTH_SHORT).show();
}
else
{
strBalance = strBalance - strAmount; // 1000 - 500 = 500
textBalance.setText("Your current balance is: $ "+strBalance);
Log.v("strBalance", String.valueOf(strBalance)); // 500
editor.putInt("key_balance", strBalance);
editor.commit();
}
}
});
}
}
Do this,
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
int any_variable = sharedPreferences.getInt("key_balance", 0);
Remove initialisation and do this in your onCreate and then use the new variable as you strBalance.
-Check Both the preference and key name are same or not.
You did not retrieve data from SharedPreferences
Write your code in onResume() like this:
#Override
protected void onResume() {
super.onResume();
// SharedPreferences retrieval code
}
To know more about SharedPreferences check this link.
This should work fine:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
if (pref.getInt("key_balance", 1000) != null) {
strBalance = pref.getInt("key_balance",1000);
} else {
strBalance = 1000;
}
Instead of
strBalance = 1000;

how to save a dynamic string?

In my app I get the current time and convert it to a string.
as you see this string will be changed every time I open the activity But I want to save this time string in a static string which if I went back to this activity I could show it to user.
This is my code so far:
Time now = new Time();
now.setToNow();
String str = now.toString().substring(0, 15);
textview.setText(str);
Actually I have a listview that has items.
this time string is in listview.onitemclicklistener and I want to whenever that item is created I save the time and when users clicked on that I show that time in second activity.
For example if user created the item in listview in two days ago, when clicks on that Item I show two days ago date and time:
This my code with more details:
first activity:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Time now = new Time();
now.setToNow();
String timedate = now.toString().substring(0, 15);
Intent intent = new Intent(Albums.this, AlbumPage.class);
intent.putExtra("extra", timedate);
startActivity(intent);
}
second activity:
String str = getIntent().getExtras().getString("extra");
textview.setText(str);
in this way when I click on each Item it just shows the current time not the time that Item is created (my listview is dynamic an user can add or delete items).
Try below code:
SharedPreferences sharedpreferences = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
Editor editor = pref.edit();
Time now = new Time();
now.setToNow();
String str = now.toString().substring(0, 15);
editor.putString("key_name", str);
editor.commit();
textview.setText(str);
use this code in your Activity's onPause or onDestroy
SharedPreferences sharedpreferences = getSharedPreferences("PREF",
Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
Time now = new Time();
now.setToNow();
String str = now.toString().substring(0, 15);
editor.putString("time", str);
editor.commit();
then to Retrieve it use the following code in onStart() method
SharedPreferences sharedpreferences = getSharedPreferences("PREF",
Context.MODE_PRIVATE);
String time = sharedpreferences.getString("time" "default_value");
Add below code where you want to save current time.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//declare pref editor
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String savedTime=prefs.getString("time", "");
//now check the value of shared pref and apply the condition like this
if(savedTime.isEmpty()) {
//set time if time is not set
prefsEditor = prefs.edit();
Time now = new Time();
now.setToNow();
String str = now.toString().substring(0, 15);
prefsEditor.putString("time", str);
prefsEditor.commit();
Intent intent=new Intent(this, class2.class);
startActivity(intent);
}
else {
//perform your action here if time is already set
Intent intent=new Intent(this, class2.class);
startActivity(intent);
}
}

Adding to SharedPreference value with multiple onclicklistener

I have multiple on click listeners implemented in the code. But, I want each click from seperate images to be saved in a "ticker" in shared preferences. So, if there are 2 clicks on image 1, 4 clicks on image 2, and 6 clicks on image 3, it totals up to be 12 "clicks" counted in shared prefs. The problem is, every onClickListener seems to overwrite the other, instead of stacking. Any ideas on how to accomplish this?
Image1.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View v) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
Image2.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View w) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
Image3.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View x) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
You are keeping track of the numclicks 3 times (inside each OnClickListener), so it makes sense for them to override each other.
For starters you could create your OnClickListener only once, and assign it to each image. This should solve it:
View.OnClickListener imageClickedListener = new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View v) {
numClicks++;
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
}
Image1.setOnClickListener(imageClickedListener);
Image2.setOnClickListener(imageClickedListener);
Image3.setOnClickListener(imageClickedListener);
EDIT:
I've added a reply to your comment here cause I find it clearer.
The sharedPreferences instances were not the problem. They all talk to the same saved data ("ActivityPREF"). The problem was that you had 3 instances of OnClickListener, and all 3 of them were holding the integer numClicks. So they all started at 0 (or previously saved amount), and only increased the local numClicks. So if I tapped image1 twice, the numClicks inside that listener would be on 2. While the other ones would still be at 0.
It would have worked if you would have added the following to the onClick methods, before increasing the numClicks:
numClicks = pref.getInt("Total_Clicks", 0);
Since it would then reload it from the saved value. Only the code inside the onClick method is called each time a click is made, not the code you add when instantiating an OnClickListener.

Categories

Resources