I have been trying to setting up a function, which is getting the time since the window is appearing for the viewer.
I have been using a handler, timer, currenttimemillis.
That i have succeeded in doing. The window is showing the ongoing time since the window has been shown for the user - update frequency of 40fps, and i love how it looks and works..
BUT!
When going backwards and forwards into the window, the time restarts.
I want the window to show the (running) time since the initial view for the user and i don't want the time "broken" even if the program is stopped.
I am using sharedpreferences for saving strings and i have tried to saving the initial System.currentTimeMillis(); as a sharedpreference (as a long) and loading it again on oncreate with this if statement
SharedPreferences sData14;
private final int REFRESH_RATE = 25;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orderwaiting);
setupVariables();
sData14 = getSharedPreferences(filename, 0);
}
private void setupVariables() {
mHandler.removeCallbacks(startTimer);
mHandler.postDelayed(startTimer, 0);
if (sData14 == null) {
starttime = System.currentTimeMillis();
sData14 = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = sData14.edit();
editor.putLong("sharedString14", starttime);
editor.commit();
};
if (sData14 != null) {
Long value_long = sData14.getLong("sharedString14", 1000000);
starttime = value_long;
};
EDITED ADDED
I don't use onresume and onpause.
Do i have to do that ?
I would expect the if statement handles the "case".. and i need a function that handles the case in which the program has been "closed", but the function is still needed to track how far we have reached in time.
Is it better to doinbackground, and be able to call it from another place as well ?
It just doesn't load the shared data...
In other words, i need a dynamic number to use from when the user first is viewing this window. Maybe there are other ways i could do this as well ??
I guess it should be working "this way".. but i can't seem to make it work..
I hope i have set up my problem in an simple way.
SOLUTION
long startTime;
private final int REFRESH_RATE = 25;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orderwaiting);
setupVariables();
}
private void setupVariables() {
SharedPreferences sData14 = getSharedPreferences(filename, 0);
startTime = sData14.getLong("sharedString14", -1);
**starttime = startTime;**
if(startTime == -1){
//startTime not previously saved
starttime = System.currentTimeMillis();
SharedPreferences.Editor editor = sData14.edit();
editor.putLong("sharedString14", starttime);
editor.commit();
}
mHandler.removeCallbacks(startTimer);
mHandler.postDelayed(startTimer, 0);
i added the starttime = startTime, since it would else not load any starttime on the second view..
Thanks to David.. You saved my day :-)
Ah Ok, I missunderstood your initial question. The way you are checking your prefenences isn't quite right, you can also simplify it quite a bit. The code below should fix your problems:
long startTime;
private final int REFRESH_RATE = 25;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orderwaiting);
setupVariables();
}
private void setupVariables() {
SharedPreferences sData14 = getSharedPreferences(filename, 0);
startTime = sData14.getLong("sharedString14", -1);
if(startTime == -1){
//startTime not previously saved
starttime = System.currentTimeMillis();
SharedPreferences.Editor editor = sData14.edit();
editor.putLong("sharedString14", starttime);
editor.commit();
}
mHandler.removeCallbacks(startTimer);
mHandler.postDelayed(startTimer, 0);
}
Related
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
}
});
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;
when I'm launching my application and the onResume() method is being run, something goes wrong when reading from my SharedPreferences. This is how the code looks.
static double cowCount = 197, income, cowMult = 1;
...
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getSharedPreferences("com.example.cowcount", Context.MODE_PRIVATE);
cowCount = sharedPref.getFloat("cowCount", 0);
cowMult = sharedPref.getFloat("cowMult", 0);
income = sharedPref.getFloat("income", 0);
}
...
When the code is like this, the application is being frozen. The application consists of a counter, and when I push the button that is supposed to count up, nothing happens.
However, when i comment out the line where i assign a value to the cowMult double from the SharedPreferences, the application doesn't freeze.
cowCount = sharedPref.getFloat("cowCount", 0);
// cowMult = sharedPref.getFloat("cowMult", 0);
income = sharedPref.getFloat("income", 0);
To be clear, the above works fine.
This is the method called when pushing the button (that is supposed to higher the value of cowCount by one):
public void addCow (View view) {
cowCount = cowCount + cowMult;
refresh();
}
...
public void refresh () {
TextView myTextView = (TextView)findViewById(R.id.myText);
myTextView.setText("You Have " + String.valueOf((nf.format(cowCount)) + " Cows!"));
}
Change your code as follows:
static float cowCount, income, cowMult;
...
protected void onResume()
{
super.onResume();
SharedPreferences sharedPref = getSharedPreferences("com.example.cowcount", Context.MODE_PRIVATE);
cowCount = sharedPref.getFloat("cowCount", 197);
cowMult = sharedPref.getFloat("cowMult", 1);
income = sharedPref.getFloat("income", 0);
}
...
The second parameter in SharedPreferences.getFloat() is a default value that the method will return if the key is not found. With the code you've supplied, If you've not saved the values to SharedPreferences properly, those variables will be assigned a value of 0. This is why nothing changes when you press the button; you're adding 0. Check to make sure you are saving to SharedPreferences correctly.
Also, there's no point in initializing the variables when you declare them, as they all get assigned a value in the onResume method, be it a saved value or a default value.
And, as pointed out by Martin, assign your TextView in your onCreate method.
A couple of things are strange with the code you have posted
1 why are you calling
SharedPreferences sharedPref = getSharedPreferences(null, Context.MODE_PRIVATE);
and not
SharedPreferences sharedPref = getSharedPreferences( "com.myname.myapp", Context.MODE_PRIVATE);
2 your onResume should be the following
super.onResume();
SharedPreferences sharedPref = getSharedPreferences(null, Context.MODE_PRIVATE);
cowCount = Double.longBitsToDouble(sharedPref.getLong("cowCount", 0));
cowMult = Double.longBitsToDouble(sharedPref.getLong("cowMult", 0));
income = Double.longBitsToDouble(sharedPref.getLong("income", 0));
calling the super.onResume() first before your code (same with all life cycle methods)
EDIT
3. Why are you not just setting your values to be an int (from what you said above they seem to be) or a float which will give you possibly all the precision then you can just get your values using
getInt(String key, int defValue)
of
getFloat(String key, float defValue)
Seconded Edit
There are a few strange ways you are doing things in the code that I can see. try the following code and let me know if it fixed the problem (though I can't see how the sharedPreferences would be causing it ). i am presuming the addCow method is being called from an onClickListener
//get a reference for your myTextView in the onCreate() method, after declaring your variable
//outside the onCreate method i.e
TextView myTextView;
...
// int onCreate()
myTextView = (TextView)findViewById(R.id.myText);
//you don't need to pass a view parameter, so don't
public void addCow () {
cowCount = cowCount + cowMult;
refresh();
}
...
public void refresh () {
//the way you are getting a string value is also not what I would do either use
//Float.toString(cowCount) or just
myTextView.setText("You Have " + cowCount + " Cows!"));
}
Hope the issue is gone.
I'm creating a simple click counter android app, sound is played when a button is clicked and the count is also saved when leaving the count screen and then returning to it.
I have encountered a problem with the mute button. When I click it, it mutes the whole application rather than just that particular gui screen (activity).
First issue is that the mute button mutes the sound for the whole app, and I only need to mute for that activity.
Second issue is that when you click mute button and come out of the screen, then go back, then try to unmute - it does not unmute the sound.
Was thinking the resolution to this is that we take the mute button out of the SharedPreferences save instance state - if this is possible...
Here is my code so far, if you can guide me on how to achieve the above that would be great. Thanks.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count = 0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
AudioManager audioManager;
public static boolean mutestatus = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
audioManager =
(AudioManager) getSystemService(Context.AUDIO_SERVICE);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
image = (ImageView) findViewById(R.id.imageview);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button) findViewById(R.id.wreset);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button) findViewById(R.id.wclick);
wmute = (Button) findViewById(R.id.wmute);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
if (count > 50) count = 0;
image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
mpButtonClick.start();
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);
;
txtCount.setText("0");
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
});
wmute.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mutestatus) {
mutestatus = true;
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
Log.v("'test....", "" + mutestatus);
} else {
mutestatus = false;
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
Log.v("'test....", "" + mutestatus);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
}
You are saving the preferences on the application level, make it Activity specific, i.e. Implement mute functionality for the activity not the application.
Edit
See your objective is some what to mute and unmute (loquent) the audio, Preferences can be saved in three ways.
1) Preferences can be retrieved only by a single activity.
2 )Preferences can be shared and retrieved among all activities within the application.
3)Preferences can be shared and retrieved through all applications on the device.
In your case, Saving Activity-level preferences:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putString("pref 1", "some text");
editor.commit();
We get a SharedPreferences object by calling getPreferences(int mode) method which takes an integer value as a parameter, the mode value can be one of the following:
Context.MODE_PRIVATE (0): a file creating mode that makes the created file only accessible by applications with the same user ID (access the file from the same application context, will desctribe later).
Context.MODE_WORLD_READABLE (1): file mode makes the file readable from other applications.
Context.MODE_WORLD_WRITEABLE (2): file mode allows other applications to write to the file.
Then we get an instance of SharedPreferences.Editor and write the preference value with editor.putString(String key, String value) method.
shared preferences allows you to insert preferences using the following methods:
editor.putBoolean(String key, boolean value).
editor.putFloat(String key,float value).
editor.putInt(String key, int value).
editor.putLong(String key, long value)
editor.putString(String key, String value)
Then we call edit.commit() to save the preferences to the file. commit returns a boolean indicating the result of saving, true if successful and false if failed.
Reading preferences values:
To read preferences values:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
String val=prefs.getString("pref 1", "some text");
We use sharedpreferences.getString(String key, String defaultValue) (or get boolean/float/int) to return the value stored with a specific key or defaultValue if not found.
Source
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Making data persistent in android
Edited:
I am building an android app which works on the principle of a simple counter.
public class TasbeehActivity extends Activity {
/** Called when the activity is first created. */
int count;
ImageButton imButton;
TextView display;
static String ref = "Myfile";
static String key = "key";
SharedPreferences myPrefs;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imButton = (ImageButton) findViewById(R.id.bCount);
display = (TextView) findViewById(R.id.tvDisplay);
myPrefs = getSharedPreferences(ref, 0);
if(check){
String dataReturned = myPrefs.getString(key, "0");
count = Integer.parseInt(dataReturned);
display.setText(""+count);
}
imButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random rand = new Random();
display.setTextColor(Color.rgb(rand.nextInt(255),
rand.nextInt(255), rand.nextInt(255)));
count++;
display.setText("" + count);
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
String data = display.getText().toString(); SharedPreferences.Editor
editor = myPrefs.edit(); editor.putString(key, data);
editor.commit();
check = true;
}}
I want to save the value of count so that when my app restarts after closing it should have the value of count before closing app.
Also when I change orientation of the emulator i.e. from portrait to landscape or vice versa count gets set to 0.
Is there any solution for both of these problems?
You should use SharedPreferences to save your variable, and Override OnConfigurationChange because it's probably calling your oncreate method (don't forget to add android:configChanges="orientation|keyboardHidden|screenSize" in your manifest)
I Hope this will help you.
1. use sharedpreferences for saving or retrieving value of count when app is restarts after closing
2. see handle orientation change in android count gets set to 0 when I change orientation of the emulator i.e. from portrait to landscape or vice versa
Try these....
android:configChanges="orientation" , This will prevent your Activity to again restart when orientation changes.
Use Bundle, but thats only for small amount of data. Serialization and Deserialization will be needed.
You can also use onRetainNonConfigurationInstance(), and getLastNonConfigurationInstance(), for storing and retrieving data.
See this link for further details:
http://developer.android.com/guide/topics/resources/runtime-changes.html