Convert string to integer(s) - android

In my app i have just imported a string to this activity from another activity.
I need this string to be converted into 5 integers, the following:
int counter1, counter2, counter3, counter4, counter5;
This is my code for receiving the string:
Bundle gotBasket = getIntent().getExtras();
number = gotBasket.getString("lol");
The string is currently passed successfully, all i need is for it to be converted to integers.

Ad.1. Q
Integer.parseInt(gotBasket.getString("lol"));
Watch out for the NumberFormatException - if the string does not contain a parsable integer.
Ad.2. Q
ScrollView per each column? You really want it that way?

Use Integer.parseInt()
EDIT: Or in the first activity attach the extra as an int, then in your new activity use Bundle.getInt()

Related

Android TextView display a string to three decimal places through double convertion from another class

I cannot restrict the TextView to show only 3 decimals when I'm using a variable from another class. Here's the problem:
I have this TextView
public static TextView pt_resultado;
However when I tried to use it to show the number inputted from another screen while converting from Double restricting the decimals:
pt_resultado.setText(String.format("%.3f",(Double.toString(ActivityPopulacao.pt_resultado2))));
I get the following error:
java.util.IllegalFormatConversionException: %f can't format java.lang.String arguments
Is there a way to show only three decimals, put without changing the conversion?
You are trying inserting string as float.
You should do:
pt_resultado.setText(String.format("%.3f",Double.valueOf(ActivityPopulacao.pt_resultado2.getText().toString())))
You need to:
Retrieve String from TextView.
Convert String to Double/Float.
Format Double/Float value as String at 3 decimal places.
I assumed that ActivityPopulacao.pt_resultado2 is also TextView!
To help you also understand why this is happening ill break it flow a bit.
double recievedNum = ActivityPopulacao.pt_resultado2;
String convertedNumAsString = String.format ("%.3f", recievedNum);
pt_resultado.setText(convertedNumAsString);
Can you see the mistake? Your using Double.toString(number) where its expecting a number. String.format takes in the double does formatting and converts to string for you.
Defining TextView as a static view will cause memory leaks. Going forward, you can pass value from one activity to another using Intent - I presume you're using activity. Also, getText().toString() has already converted the input value to string. So you don't need that Double.toString() any more. Copy below code and paste it in the code that is responsible for starting the new activity.
Intent in = new Intent(ActivityPopulacao.this, NewActivity.class);
in.putExtra("key", pt_resultado2.getText().toString());
startActivity(in);
To receive the value, get the intent and request for the string in your NewActivity onCreate() method.
String newDouble = getIntent().getStringExtra("key");
pt_resultado.setText(newString);
Note that NewActivity in the above snippet refers to the activity that needs the value.
Why do you convert to string and try to format it like it is a Double?
The format() method expects a number to format.
Since ActivityPopulacao.pt_resultado2 is Double you should format the double value:
pt_resultado.setText(String.format("%.3f", ActivityPopulacao.pt_resultado2));

Firebase android hashmap integer value turned into Long

changeweek = (Map<String,ArrayList<Integer>>)dataSnapshot.child("week").getValue();
ArrayList<Integer> test = changeweek.get("Monday");
Log.d("changeweek",changeweek.toString());
int j = test.get(2);
I get an error in the last line which is the following:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
at com.example.fake9.tendee.ScheduleActivity$1$1.onDataChange(ScheduleActivity.java:107)
I don't know how this happens since I am storing Arraylist of integers into the hashmap. The following is a picture of the database.
The Firebase SDK internally stores all integer-like number values as Long values, whether or not you want. This helps defend against possibly very large numbers as values.
Your cast to a Map with values of type Integer is overriding that, then causing problems at runtime when the types don't match. You can correct this by simply changing your value type from Integer to Long.
Rather than directly converting long to int, convert long to string using String.valueOf() then we can easily convert string value to int using Integer.parseInt()
So you can go with this,
**
int j = Integer.parseInt(String.valueOf(test.get(2)));
**

Minusing string number values in android

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.

Android math operator

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 trigger a force close on Android?

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.

Categories

Resources