I am making an android application where i got a set of strings that i load from SharedPreferences so that i can save the strings. The strings contain only numbers, but it is not an int value, its a string value. And i wounder how i can minus the numbers that's in there, becuase usually, i would have been using something like an int value = value - value; But that doesn't seem to work since it's a string and not an int value. How can i do this even though it's a string? I know i could use int values instead, but as i didn't think of this before now, when i'm almost done, it would be alot of work changing all of the code that's related to this. Please help me and thanks so much in advance!
You will have to convert your strings to ints first, then operate on them, then save the string back:
String value = preferences.getString("key:");
int intValue = Integer.valueOf(value);
intValue = intValue - 1;
preferences.edit().putString("key", Integer.toString(intValue)).commit();
Try using Integer.valueOf(string) or Integer.parseInt(string).
Learning basic programming the the concept of casting will help you tremendously. One datatype can be converted to another using the base classes, which often times deal with String. For instance look at the Documentation of Integer.
Well as you have said that it is a lot of work to change the code and save it as int, I would suggest converting the string into an integer, refer to this link for more information, someone has asked about converting strings to integers, and as Android is Java-based, this can apply to your project:
Converting a string to an integer on Android
Hope this helps.
Related
Ultimately I am trying to store an Int Array in Shared Preferences but I know Kotlin doesn't support that. So I am converting my Int Array to a String Array using the method here:
How can I store an integer array in SharedPreferences?
My issue is that I am struggling to put in a default value for the getStringSet method:
private fun loadIntScoreArray() {
val prefs = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE)
//TODO: Load the String array
var default = emptyList<String>()
avgScoreArrayString = prefs.getStringSet(AVG_SCORE_ARRAY, default)
}
However default is not an acceptable object in the prefs.getStringSet(AVG_SCORE_ARRAY, default) line. The error is confusing because it seems contradictory:
Required: MutableList
Found: (Mutable)Set!
Required: (Mutable)Set!
Found: MutableList
There is few things you need to know. Since API 11 you can only store plain objects or sets to shared preferences. You can convert your list to set, but it can be lossy conversion in your list contain duplicates.
If you want to use sets you should call it like this:
//to get
prefs.getStringSet(AVG_SCORE_ARRAY, emptySet<String>()))
//to set
prefs.edit().putStringSet(key, AVG_SCORE_ARRAY)
The other way is to join array to a single string using join operation. Here is a doc for you https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to.html
To be honest both of these ways are not the perfect solutions. If it is production application and I recommend using persistance library like Room, Realm etc.
Hope it helps.
Edit.
If you are hundred percent sure you are going to have 5 ints stored (and it is not gonna change in a near or distant future), using database could be overkill. I recommend using joining to single string and storing it as single string or just store 5 independent int values. There is no point in complicating simple things.
I am creating a calculator app in android. It should calculate anonymously whatever is on textBox. For e.g. I enter 1+2.5-5*8 in textBox. But when I call addition method the app gets crashed. Because the input is in string format and answer I want is in numeric format. I used string buffer. I tried in java that when I enter (1+1+3-1) in stringBuffer and I display using println() method it give correct answer but same does not happen with string buffer when I take that value from editText.
You have to convert string into integer or float.
Use Integer.parseInt("") method to covert to integer and Float.parseFloat("") to convert to float.
First of all welcome to StackOverFlow
It might help if you add code and the error log in the question
So I am gonna cover all the possible things that might be happening wrong in your program:
NumberFormatException- you might not be converting the string "12" into int 12 to do so use Interger.parseInt(your string buffer with number only here);
Try using a stack and a queue for your solution (google it you will get details)
You might be making a mistake in getting string from edittext it sometimes give NullPointerException
if above is not enough comment and add your code asap
I need calculate a thing. but my formula sentence has occur some problem.
TextView ticketP = (TextView)findViewById (R.id.ticketQ);
ticketP.setText(oneSession.getTicketOder());
String Ctotal = "";
Ctotal = jsonObject.optString("price");
String OneTotal = oneSession.getTicketOder() * Ctotal; // this part has occur the problem which is the operator * .
You'll need to convert the Strings to numeric type before performing any multiplication. Depending on the type of numeric value you are using take a look Double.parseDouble(String string) or Integer.parseInt(String string).
int oneTotal = Integer.valueOf(oneSession.getTicketOder()) * Integer.valueOf(Ctotal);
to convert it again to String use
String.valueOf(oneTotal)
Yes. Your going to have to use the parsing methods in order to convert the string to a native numerical type. You also need to be care about a few things with your code.
json.optString() can return null. opt = optional.
I would suggest using json.getInt() or json.getDouble() this will not only give you the correct type, but also throw an exception if the values aren't correct.
Secondly your going to have to convert your numerical answer back to a string if you want to display it. But this is easy enough with a .toString() or + "" if you are lazy.
Why does this code trigger a force close in Android?
`score.setText(Integer.parseInt((String) score.getText())+1);`
score is a TextView, and I am simply increasing the number by 1. I have predefined a String resource to be the initial number in the score TextView.
I am quite frustrated.
First off you should try breaking down your code so you can actually see what is going on with it.
Instead of
score.setText(Integer.parseInt((String) score.getText())+1);
try
String tmp = score.getText().toString();
int score;
score = Integer.parseInt(tmp) + 1;
score.setText(String.valueOf(score));
EDIT: Upon further reading of the documentation, setText has several overloads, one of which DOES take an int, but it takes the int of a resource ID. My guess is that your score is not a valid resource ID, thus crashing your application.
public final void setText (int resid)
Oh and as far as the frequent FC's when beginning Android Dev, it happens to the best of us. The key is to learn WHY the FC's happen, and have a LOT of patience.
mostly u need to do this
score.setText(Integer.parseInt(score.getText().toString())+1);
coz.. getText() returns a Editable Object which cannot be parsed to Integer. So it give NumberFormat Exception.
AndMake sure to set TextView,s Text to an integer initially..
try this way
score.setText(String.valueOf(Integer.parseInt(score.getText().toString())+1));
as you can pass the integer value that's why getting force the application
TextEdit.setText takes a CharSequence as input.
You are supplying an integer through Integer.parseInt((String) score.getText())+1
See, if converting it back to string and using it in setText helps.
You can convert an integer to string using Integer.toString.
PS: I am new to java myself.
The compiler should have ideally caught this error.
It's possible java uses some implicit type conversions from string to int.
I'm having an arrayList with loads of numbers, I want
to have a different image on every number in the array represented by each number... but I dont know how to put a Variable in (R.drawable."HERE"), if its even possible?!
This is what i've tried to do, Im pretty new to android and Java,
so this may seem pretty funny to you haha... (the array is not shown)
String s = names[position];
String img = s.toString();
holder.imageView.setImageResource(R.drawable.img);
Hope you understand my question.
Thanks in advance
//Halle
You can use reflection do do that. See here for an example.