I have a broadcast receiver class that successfully runs when the phone is rebooted. My problem is that when I try to retrieve info from the SharedPreferences, the code stops running and nothing continues. This is the start of the onReceive method:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if(sp.getBoolean("alarmRunning", false)) {
Log.d("test", "Fixing alarms1");
String name = sp.getString("currentName", "");
String description = sp.getString("currentDescription", "");
long exactTriggerTime = sp.getLong("exactTriggerTime", 0);
long offsetTriggerTime = sp.getLong("offsetTriggerTime", 0);
String intentNameExtra = sp.getString("intentNameExtra", "");
String intentDescriptionExtra = sp.getString("intentDescriptionExtra", "");
boolean runOnce = sp.getBoolean("runOnce", true);
long interval = sp.getLong("interval", 0);
long totalOffset = sp.getInt("totalOffset", 0);
Log.d("test", "Fixing alarms");
Log.d("test", String.valueOf(runOnce));
When I run it on my phone, I get "Fixing alarms1" returned to me, but not "fixing alarms" or the value of the runOnce variable. Could someone explain this behavior? It shouldn't be that it broke since it couldn't find something, because everything has a default value for it. I have also checked the console with the test filter and without filters, and no error message is being displayed.
EDIT: After further testing, I realized that it didn't like taking an int variable from the SharedPreferences and assigning it to a long. My bad.
Related
I am working with numbers, I get an int from shared preferences, I do some maths and then
I want to do something IF the result is situated between 2 numbers.
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", Context.MODE_PRIVATE);
int A = settings.getInt("A", 1);
int B = settings.getInt("B", 1);
operation = (TextView) findViewById(R.id.imc );
operation.setText(A*B);
String operation;
if (SOMETHING HERE!) { // is situated between 1 and 20
something
}
What should I do?
Any suggestin will be apreciated.
You just need a simple logic dude.Do the following,
if(A>1 && A<20)
{
//Do what ever you want.
}
I am new to using shared preferences and on my first try im getting errors that don't make sense to me. I assign a value like this:
int saveScore = sp.getInt("SAVE_SPOT",0); //This is intentional to get the
//default value of 0 to go to case 0
switch(saveScore){
case 0:
SharedPreferences.Editor edit1 = sp.edit();
edit1.putInt("SCORE_1", score);
edit1.putInt("SAVE_SPOT", 1);
edit1.commit();
break;
case 1:
int previous_score = sp.getInt("SCORE_1",0); // error happens here
if(sp.getInt("SCORE_1",0)>score){
SharedPreferences.Editor edit2 = sp.edit();
edit2.putInt("SCORE_2", score);
edit2.putInt("SAVE_SPOT", 2);
edit2.commit();
}
else{
SharedPreferences.Editor edit3 = sp.edit();
edit3.putInt("SCORE_2", previous_score);
edit3.putInt("SCORE_1", score);
edit3.putInt("SAVE_SPOT", 1);
edit3.commit();
}
break;
Every time i run the program i get the error "string cannot be cast to integer". I am almost 99% sure the variable score is an int and not a string but I am not sure why i am getting this error.
You can check to make 100% it is an int by using this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
If putInt won't work, you could use Integer.parseInt( instead.
I solved my issue, un installing the app is necessary every time in testing because thats the only way to clear the stored data
It seems that with putInt() it won't let you put anything but an int, so that is odd. Are you really telling the full story here?
My guess is that you have ANOTHER key that has the name SCORE_1 that was actually stored as a string, and when you're grabbing out the int, it's picking up the String instead. That's the only way. According to the API:
Throws ClassCastException if there is a preference with this name that is not an int.
So I think SCORE_1 is already in there, and was stored as a string. For the hell of it, try to get out SCORE_1 using getString() instead.
See here: http://developer.android.com/reference/android/content/SharedPreferences.html#getInt%28java.lang.String,%20int%29
Basically the app opens up to a menu and at the top it says Welcome to bla bla. I want to change that every time they open the app to something different each time so next time it would say. Bla bla is awesome and so are you. Next time it may display a different text. Basically I want to be able to create a string array possibly and each time the user opens the app/activity, a random string is selected and displayed. If there is a better way of going it by a string array, I am open to suggestions. Thanks!!
you should use shared preferences and every time the user start the application show another sentence.
you should save the sentences in your shared preferences and to save a counter for
retrieving the index your in the str array.
should be like:
String Sentences = "sen one, sen two, sen three, sen four";
int counter = 0;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("sentences", Sentences);
editor.putInt("counter", counter);
editor.commit();
here you save in your device the sentences and the counter.
now how you get the current sentence and display?
should be like:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit()
String sen = prefs.getString("sentences", "");
int counter = prefs.getInt("counter", 0);
String[] fetchArray= sen.split(",");
//now you should display fetchArray[counter].
tv_1.settext(fetchArray[counter] + "");
counter = counter+1;
if (counter == fetchArray[counter].length)
counter = 0;
editor.putInt("counter", counter);
editor.commit();
this should perfectly work.
good night.
Build an array of your strings, and pick a random one each time.
For example this will generate a random number between 0 and 99:
Random ran = new Random();
randomNum = ran.nextInt(100);
So, you can then call a string from your array: myArray.get(randomNum).
I am creating a fairly simple android application which is basically a timer, I am trying to make it so that you can set the timer length in the settings and then using preferences retrieve the value and set it as the timer length. I can retrieve the value from the preferences and simply display it.
But when I try to convert the string value (i.e. 1) to a long value using either Long.parseLong(string) or Long.valueOf(String) and Long.valueOf(Int), I don't receive any errors in the code but when I try and start the application, it force closes and the error log says it is caused by NumberFormatException, Here is the the section of code I am using, also if I remove the line that says Long.ParseLong... everything else works fine.
private long interval = 1000 ;
private long startTime = 30000;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown_timer);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n"+ prefs.getString("timerLength","NULL"));
startTime = Long.parseLong(builder.toString());
TextView view = (TextView)findViewById(R.id.showTimer);
view.setText(builder.toString());
Pls remove "\n"
StringBuilder builder = new StringBuilder();
builder.append(prefs.getString("timerLength","NULL"));
startTime = Long.parseLong(builder.toString());
The problem is the '\n' character. The string should only contain a long as a String for it to be successfully parsed.
I having developing simple application, which has just like game. When I have finished game the gave over page display, which as time and score. Now if i want to play that game again and again. How to store that previous all time and score and current finished.
I want to display, all time and score in to the list according to high to low score, after score button was clicked.
I have done shared preferences in gaveover page and that value get from score page. but why not display when i play third time. second time it is ok. third time and so on.. just replacing upward . I don't have enough idea, how to store that all information in to array and display on list. But I have try to use map, but getting not more idea.
I want to display this type of format in to the score page:
Time .............. Score
1:10 .............. 175
2:05 .............. 145
1:15 .............. 110
2:50 ............... 90
Here I have just started little code but not complete and better,
GaveOver.Java
Where just diplay socre , time and mistakes after finish game.
Score.Java
public class Scores extends Activity {
private static String strTime;
private static int intScore;
public static SharedPreferences settings;
public static final String MY_PREFS_NAME = "PrefName";
#Override
protected void onCreate(Bundle savedInstanceState) {
ImageView back, reset, score_home;
super.onCreate(savedInstanceState);
setContentView(R.layout.score);
// lv = (ListView) findViewById(R.id.listView);
getValuesFromGaveOver();
SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0);
String data=pref.getString("DATA", "Nothing");
Log.i("horror", "DATA "+data);
}
private void getValuesFromGaveOver() {
SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0);
strTime = pref.getString(TIME, "n/a");
intScore = pref.getInt(SCORE, -1);
Log.i("horror", "From Gave Over "+"Time="+strTime+" "+"Score="+intScore);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences pref = this.getSharedPreferences(MY_PREFS_NAME, 0);
strTime = pref.getString(TIME, "");
intScore = pref.getInt(SCORE, -1);
savePreferences(intScore, strTime);
}
private void savePreferences(int s, String t) {
SharedPreferences sPref = this.getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = sPref.edit();
edit.putString("DATA", strTime+" "+intScore);
edit.commit();
}
}
please give me the good suggestion, how to do it?
The cleanest way would be to use sqlite databases.
Using SharedPreferences is much easier, especially for beginners.
You could do it like that: You save a 3rd item, the actual entry count as SharedPreference.
Everytime you save a new entry you increment this counter.
Then you append the current counter number to the TIME and SCORE keys.
// Saves a new entry | Attention: code not tested!
save(int score, int time){
SharedPreference pref = ...
SharedPreference.Editor editor = ...
int newEntryID = pref.getInt("numEntries", 0) + 1;
editor.setInt("numEntries", newEntryID);
editor.setInt("score" + newEntryID, score);
editor.setString("time" + newEntryID, time);
editor.commit();
}
Assuming "score" is the SharedPreference-Key for SCORE and same for the time.
Reading would be of the same scheme.
for(int i=0; i<numEntries; ++i){
pref.getInt("score" + i, 0);
...
}
using the shared preference you can store both,
1) first you have to store time, once this is done you have to store score mapped on the given time,
you are doing this way,
edit.putString("DATA", strTime+" "+intScore);
But you can take different approach if you have only one player playing at one time,
edit.putString("TIME", strTime);
edit.putString(strTime, strScore);
1:10 .............. 175
So here first you mapped your time with TIME and then you mapped score 175 with 1:10
Hope this will help you
Good idea would be to define Java bean holding score ( say with 2 Fields, time in seconds / points / maybe date / name / whatrever else fields you like to store). You can easily do following with them:
sort in a list and limit their amount ( you do not like to have 10000 of score entries, 100 will be anough )
marshall this list to / from JSON ( Shameless self advertising: https://github.com/ko5tik/jsonserializer )
store JSON in a shared preference or in a private application file (I store up to 100 local highscore entries, and 1000 all time scores and use files)