parseInt crashing android app - android

So I'm trying to make a calculator app (just to get a hang of android development), and I noticed with some testing that the parseInt conversion from "String tack1" is causing the app to crash. Can someone tell me why? I can't seem to figure it out and I've been searching the internet for quite a while now. (hehe I'm a noob so please go easy) In the code below, I've modified a couple lines to make it seem obvious what it's supposed to print however it still crashes. Here's the code:
equals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oC = 1; //operator checker is on 1 (for plus)
switch(oC){ //check for operator clicked
case 0: break;
case 1:
tack1 = "1"; //INSERTED THIS TO MAKE OUTPUT OBVIOUS
tack1 = tack1.trim(); tack2 = tack2.trim(); //INSERTED BEFORE TO DEAL WITH WHITESPACE
numOne = Integer.parseInt(tack1); //CRASHES HERE
answer.setText(numOne);
modeChecker = 0; oC = 0;break;
NOTES ON PROGRAM(some of comments repeated and other stuff as well):
The tack1 = "1"; is to make output obvious
The tack1.trim() is to deal with whitespace
Yes whatever is in tack is a number and an integer (not even a negative integer)
Yes numOne is an integer and is defined wayy above (not in code listed here)
Sorry the indents are all messed up(after case 1) because of the comments I added
This is a section of my onClick method, so closing brackets aren't included in here.
Can someone please help me?
THANKYOU :D

I'd be willing to bet it's actually crashing on the following line AFTER the call to parseInt.
You're calling setText(int) on your TextView. When you pass an int to this method, that int is a pointer to a string resource...you're probably expecting an auto-conversion to a string. Since you are passing it an int that is generated in your application, it's extremely unlikely that this int also points to a string resource in your res/values/strings.xml file. What you really want to do is change numOne to a string first, which you can do inline:
Change
answer.setText(numOne);
to
answer.setText(String.valueOf(numOne));
and you're good to go.

Related

Android Exception: UnknownFormatConversionException

Hi I am setting some text inside a RobotoText that is positioned inside of a ViewHolder I am calling it like this:
viewHolder.txtSimilarAds.setText((((Property) ads.get(position)).getSimilar_items_count() == 1 ? context.getString(R.string.ad_data_similar) : context.getString(R.string.ad_data_similar_plural, ads.get(position).getImagesCount())));
However (sometimes NOT always)for some reason I keep getting this error exception UnknownFormatConversionException and it points to this line inside of the class. What could be the problem? Am I doing anything wrong?
Check that the string in R.string.ad_data_similar_plural contains a valid placeholder for an integer. It should be something like "Here is my number: %d".
String format specification
As an aside, one-liner like these are harder to understand, and make debugging more difficult. A more readable approach would have given the erroneous line more easily:
String similarAdsText;
Property adsProperty = ads.get(position);
if (adsProperty.getSimilar_items_count() == 1) {
similarAdsText = context.getString(R.string.ad_data_similar);
}
else {
similarAdsText = context.getString(R.string.ad_data_similar_plural, adsProperty.getImagesCount());
}
viewHolder.txtSimilarAds.setText(similarAdsText);
You are trying too many methods in single line try splitting it. The problem looks like you are comparing Property object with 1 which is wrong.
(Property)ads.get(position)).getSimilar_items_count() == 1
change this to
Property property = (Property) ads.get(position));
property.getSimilar_items_count() == 1

calculator on actionscript 3

This is the simplified version of my question.
There are
movieclip1
movieClip2
movieClipadd
TextA
TextB
Text C
Text answer
Touching movieclip1 should change TextA to 1 (the content should be 1)
Touching movieclip2 should change TextC to 2 (the content should be 2)
Touching movieclipadd should change TextB to + (the content should be +)
Then automatical Textanswer should give the answer. that is 3(1+2=3)
This is for mobile and I know to use ontouchbegin and ontouchend.
There's a couple of ways to accomplish what you want to do, one way would be to have a method for each operation type that you plan to have your calculator support, then you can just have a switch statement that calls the appropriate method, something like this (I got lazy and just did the operation inline, if it were more complicated would probably want methods):
switch(textB.text)
{
case '+': textAnswer.text = parseInt(textA.text)+parseInt(textC.text);
break;
case '-': textAnswer.text = parseInt(textA.text)-parseInt(textC.text);
break;
//etc.
default: throw new Error('unhandled operator');
}
assuming that you are going to use your knowledge of the touch handlers to populate the text boxes.
While I sort of agree with arunkumar due to the lack of code provided it's a simple enough problem with enough easy solutions to provide one. But note that on SO it is standard that you provide your current work and as much background information as is relevant.

For loop not terminating - Android

I don't know why but my for loop won't 'stop' when its reached the truth of the termination statement.
for(int i = 1; i < 11; i++){
edittext.setText("");
EasyGame();
//if(i==10){
//Game.this.finish();
//}
}
EasyGame() is an arithmetic method, just adds two numbers together. I tried using the if statement shown above, but it still wouldn't do anything, and if it did it would call finish() after the first question!
If someone would be kind to help me I would be grateful.
EDIT:
public void EasyGame(){
Random rand = new Random();
final int a = (int) rand.nextInt(20)+1;
final int b = (int) rand.nextInt(20)+1;
String aString = Integer.toString(a);
String bString = Integer.toString(b);
String display = aString + " + " + bString + " =";
questionLabel.setText(display);
c = a + b;
}
that for loop is inside a switch/case, which deals with onClick() for buttons
Very difficult to say without seeing more code, but what you have posted alone is inherently flawed because you're trying to continuously update a UI element within a loop. If that loop is running on the UI thread, then the system isn't going to be able to redraw any UI elements such as your edittext until the loop (and whatever containing callback method) exits.
Therefore, when you say "I tried using the if statement shown above, but it still wouldn't do anything, and if it did it would call finish() after the first question!" I make the assumption that you're believing that the loop is only iterating once because you only ever see edittext display whatever is passed in the last ever .setText() call.
I dont see anything wrong with that code. The only possible problem is that your counter is being decremented somewhere (for example inside EasyGame();), or the problem is somewhere else
In the lack of provided code, I assume that your indefinite loop is happening inside EasyGame() method
The loop probably only runs once, and then it gets halted by a never ending loop in EasyGame().
Note: Don't use initial capitalized letters for methods, it's confusing.
I agree with Trevor Page, and i'll try and clarify :
your code, if it runs on a callback on the UI thread, could be calling itself by generating a callback when you are clearing the first textView or modifying the second.
Also, what do you mean by 'it won't stop' ? I don't quite see what you are trying to do here, since you erase 10 times the content of a textView and replace 10 times the content of another one.

Compare button text

Ok my pattience is gone now...I tried for 30 minutes to make this simple thing work but I failed so bad.Maybe it is because I started directly with android,no java...I studied c++ before,and in c++ this was so easy to do...
I have a button in a xml file:
<Button android:text="Button"
android:layout_width="wrap_content"
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="108dp">
</Button>
And in my java file I have a string like this:
String test = new String();
test = "google";
I 've already set up the onclick listener for the button so there is no problem.
My question is if:
Button buttonx = (Button)findViewById(R.id.button1);
How can I compare if onClick(onclick code is already made) buttonx's text = the string test that is "google".
I tried with getText,setText...but nothing...
OK. First things first: Strings are completely different in Java to C++. In fact, Objects are pretty different all-round.
String test = new String();
test = "google";
does not do what you think it does.
What this does is create a new empty String object and store a reference to it in test. The next line stores a reference to a constant String "google" in test and makes the empty String you constructed in the previous line eligible for garbage collection. This is completely different to C++, where the second line would actually call the = operator on the String class. You can kinda think of everything in Java being a pointer (but not really), so assignment in Java behaves like pointer assignment in C++ (but not really).
Back to your question.
Something like this might work:
String test = "google";
Button b = ...;
if (test.equals(b.getText()) {
// whatever
}
Remember that although Java and C++ share some syntax similarities they are really completely different languages. Java references kinda behave like pointers, but not really.
Really.
String test = new String();
test = "google";
Button buttonx = (Button)findViewById(R.id.button1);
if (test.equals(buttonx.getText())) {
// it's equal
}
if (button.getText().toString().equalsIgnoreCase(test))
Toast.makeText(this, "Button text equals!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Button text is not the same.", Toast.LENGTH_SHORT).show();

Android: How can I print a variable on eclipse console?

I wanted to print the value of a variable on the console for my debugging purpose, but System.out.println doesn't work.
System.out.println and Log.d both go to LogCat, not the Console.
Window->Show View->Other…->Android->LogCat
I'm new to Android development and I do this:
1) Create a class:
import android.util.Log;
public final class Debug{
private Debug (){}
public static void out (Object msg){
Log.i ("info", msg.toString ());
}
}
When you finish the project delete the class.
2) To print a message to the LogCat write:
Debug.out ("something");
3) Create a filter in the LogCat and write "info" in the input "by Log Tag". All your messages will be written here. :)
Tip: Create another filter to filter all errors to debug easily.
Writing the followin code to print anything on LogCat works perfectly fine!!
int score=0;
score++;
System.out.println(score);
prints score on LogCat.Try this
I think the toast maybe a good method to show the value of a variable!
Ok, Toast is no complex but it need a context object to work, it could be MyActivity.this, then you can write:
Toast.maketext(MyActivity.this, "Toast text to show", Toast.LENGTH_SHORT).show();
Although Toast is a UI resource, then using it in another thread different to ui thread, will send an error or simply not work
If you want to print a variable, put the variable name.toString() and concat that with text you want in the maketext String parameter ;)
toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...
If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.
The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.
By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)
JSONArray list = new JSONArray();
if (jsonArray != null){
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
boolean flag;
try {
flag = jsonArray.get(i).toString().equals(obj.toString());
//Excluding the item at position
if (!flag)
{
list.put(jsonArray.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonArray = list;

Categories

Resources