I am having trouble storing a double in the phone's memory. What are my other options if this isn't possible. Basically what the code is aiming to do using sharedpreferences is take the stored value of "Alcohol" spending and then add whatever the input is in the editText to it and then store that new value for the next time. Running total of spending on alcohol
**Can someone please help with this issue and be detailed where x y & z should go in the project.
The user selects from a spinner, which works.
public void addInput(){
double dblCostInput = Double.valueOf(inputBox.getText().toString());
String strCategories= spinnerCategories.getSelectedItem().toString();
if(strCategories.equals("Alcohol"))
{
alcoholSpend = alcoholSpend + dblCostInput;
inputBox.setText("");
nextInput();
inputBox.setText("Your Spending on"+strCategories+" is: " +d.format(alcoholSpend));
}
getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE).edit().putString("double", "0.28").commit();
and then to retrieve the double, simply use Double.parseDouble:
Double.parseDouble(getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE).getString("double", "0.28"));
Try below code for setting/putting & getting double with sharedpreferences :
////////////////////////////////////Setter/////////////////////////
Editor putDouble(final Editor edit, final String key, final double value) {
return edit.putLong(key, Double.doubleToRawLongBits(value));
}
//////////////////////////////Getter//////////////////////////////
double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));
}
Related
This question already has answers here:
How can I convert String to Double without losing precision in Java?
(4 answers)
Closed 9 years ago.
i want to develop one calculation base application but getting one problem.
Tried as below
double add_num = 10.06
String data = edittext.getText().toString();
value assign to data is
// data = 1000.06
now i am converting string to double
double amount = Double.parseDouble(data);
// amount = 1000.0
double final_amount = amount + add_num;
// final_amount = 1010.0
getting final_amount is 1000.0 which is not correct because amount value is losing precision i want the correct answer which is 1000.06
please let me know correct way without using format() method
Well, first of all correct value is 1010.12, not 1000.06. And this code:
double add_num = 10.06;
String value = "1000.06";
double amount = Double.parseDouble(value);
double final_amount = amount + add_num;
System.out.println(final_amount);
prints 1010.1199999999999, which is correct.
If you just want to print the number with the desired precision, use one of:
// Prints with two decimal places: "1010.12"
System.out.format("%.2f", final_amount);
System.out.println(String.format("%.2f", final_amount));
// Example, set TextView text with two decimal places:
edittext.setText(String.format("%.2f", final_amount));
By the way, in your code you have:
String data = edittext.getText().toString();
double amount = Double.parseDouble(value); // value?
Shouldn't it be?
double amount = Double.parseDouble(data);
String s="1000.06";
double d=Double.parseDouble(s);
System.out.println(d);
The above code give output: 1000.06
You should use String.ValueOf(double d);
For Example:-
Double to String
String value=String.valueOf(1000.06);
OR
String value=String.valueOf(add_num);
String to Double
Double value=Double.valueOf("1000.06");
OR
Double value=Double.valueOf(add_num);
First of all I'm a complete noob to android. Going step by step on my first app and facing some problems.
I can get my location in terms of Lat and Lon and now i have to save it to file and able to read the file to compare location in future. Could anybody please help me out on this can be done.
Following is my INCORRECT CODE
public void saveCurrentLocation(Location location){
SharedPreferences prefs = this.getSharedPreferences("com.example.mylocation", Context.MODE_PRIVATE);
String currentLat = "com.example.mylocation.location";
String now = prefs.getString(currentLat, location.getLatitude());
}
Error shown is that location.getLatitude is a double and cannot be saved to string (quite obvious but not sure how to change it)
Thanks
location.getLatitude() + "";
In Java, the + operator is overloaded to concatenate Strings. If you add "" to anything, it will be automatically cast to String.
If you want to store the result of location.getLatitude() in your sharedpreferences try converting the double to a String:
String.valueOf(location.getLatitude())
How to convert double to a string value that I get from the spinner, for example: "10 (ton)."
In summary:
How to convert string to double and delete the part (ton)?
I need only the value 10
Another option is using Java's substring method in the String class.
The signature is:
substring(int beginIndex, int endIndex)
Where endIndex equals to the index of the last character you want to include + 1.
In the case of your example, it will look like this:
String myString = "10 (ton)";
Double dbl = Double.parseDouble(myString.substring(0, 2));
Here is the link to the method:
Java substring
You must parse this String. Here is some example. Also use search.
Check these methods Double.parseDouble() and Double.toString() use these functions for converting double to string or vice-versa.
first you have to get rid of "(ton)" which can be achieved by using a String method for example
String inputString = "10 (ton)";
String str = inputString.split(" ")[0];
After that just parse the double Value
Double dbl = Double.parseDouble(str);
BTW: Not sure whether you want to go from double to string or vice-versa
i have a similar problem.
for correct formatting EditText text content to double value i use this code:
try {
String eAm = etAmount.getText().toString();
DecimalFormat dF = new DecimalFormat("0.00");
Number num = dF.parse(eAm);
mPayContext.amount = num.doubleValue();
} catch (Exception e) {
mPayContext.amount = 0.0d;
}
this is independet from current phone locale and return correct double value.
hope it's help;
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)
My app has a number of numeric user input fields which need sanity checks before proceeding to the next intent.
I read viewText fields, convert them to double and then do the (numeric) tests but odd things happen and I find that while the code runs on my HTC in debug, it falls over if I publish then download the published version. My code is sumarised as;
String sFy;
double mFy=0;D
sFy=(txtFy.getText().toString());
mFy=Double.parseDouble(sFy);
if sFy is null the .parsedouble crashes. If I use;
sFy=(txtFy.getText().toString());
mFy=getDouble(sFy);
private double getDouble(String string){
double temp=0.0;
try {
temp = Double.parseDouble(string.trim());
} catch(NumberFormatException nfe) {
System.out.println("getDouble, Could not parse " + nfe);
}
return temp;
}
it works, even if sFy is empty.
Can anyone tell my why, or suggest a 'correct' method?
Maybe like that :
String sFy;
double mFy=0;
sFy = txtFy.getText();
if ((sFy != ""){
mFy=Double.parseDouble(sFy);
}
Or maybe I haven't really understood your problem...
Your getDouble is returning 0.0 in case there is NumberFormatException.
Do you see debugger coming to System.out.println("getDouble, Could not parse " + nfe);