setText crashes app when trying to display byte values - java

I'm working on a android app that send and recieves data. In the app i have a button an a few texviews. When i press the button then data (two chars) will be send. And an the data that has been send will be shown in two tekst views.
I did the same with two integers and that worked now i want to do the same with bytes and chars and that failes.
The logcat gives the following error:
10-28 09:27:19.338: E/AndroidRuntime(13138): android.content.res.Resources$NotFoundException: String resource ID #0x0
Beloww is the onClick lisener code:
#Override
public void onClick(View v) {
// Control value
ArrayOutput[0] = 'B';
ArrayOutput[1] = 'B';
//Creating TextView Variable
TextView text = (TextView) findViewById(R.id.tv);
//Creating TextView Variable
TextView statustext = (TextView) findViewById(R.id.status);
//Sets the new text to TextView (runtime click event)
text.setText("You Have click the button");
// Convert string to bytes
ArrayOutput[0] = ArrayRecieved[0];
ArrayOutput[1] = ArrayRecieved[1];
final char Byte1 = (char) ArrayOutput[0];
final char Byte2 = (char) ArrayOutput[1];
final TextView Xtext = (TextView) findViewById(R.id.xtext);
final TextView Ytext = (TextView) findViewById(R.id.ytext);
Ytext.setText(Byte1);
Xtext.setText(Byte2);
try
{
statustext.setText("Sending....");
server.send(ArrayOutput);
statustext.setText("Sending succes");
}
catch (IOException e)
{
statustext.setText("Sending failed");
Log.e("microbridge", "problem sending TCP message", e);
}
}
});
Does anybody have a sugestion what the problem might be? Any suggestions is welcome! if i need to supply more information please say so.
Update
Thanks you all for your suggestions! For the onclick function it works! I tried to do the same for the recieve function. This event handler funnction is called when there is data avalable.
When i use the setText function it crashes my ap after a few cycles, in this function i have three settext operations. only the first one is called (then the app crashes). When i change the ordere of these operations then still only the first one is called. Could it be that the app displays the first settext operation but crashes? I use dummy data, so when the eventhandler function is called the actual recieved data is not used, but still the app crashes after the first operation. Does anybody have a sugestion?
On the other side data is send every second.
Below is the onRecieve (event handler)function:
#Override
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data)
{
Log.e(TAG, "In handler!");
//Control value
ArrayRecieved[0] = 'C';
ArrayRecieved[1] = 'B';
if (data.length < 2){
return;
}
// Set data that has been recieved in array
//ArrayRecieved[0] = data[0];
//ArrayRecieved[1] = data[1];
char Byte1 = (char) ArrayRecieved[0] ;
char Byte2 = (char) ArrayRecieved[1] ;
TextView Xtext = (TextView) findViewById(R.id.xtext);
TextView Ytext = (TextView) findViewById(R.id.ytext);
Xtext.setText(""+Byte2);
Ytext.setText(""+Byte1);
TextView textRecvStatus = (TextView) findViewById(R.id.RecvStatusText);
textRecvStatus.setText("In handler!");
}
});

TextView has two methods like
TextView.setText(CharSequence) and TextView.setText(int).
1) first method directly assigns a text to TextView which is passed as CharSequence (can be String,StringBuffer,Spannable...)
2) second methods searches for the String resource that you define in Resources with ID passed as parameter.
and you are passing char as parameter. this char is type casted into int and invokes it as TextView.setText(int) and searches for the Resource String with that int ID whose value is not defined in Resources.
type cast char as String like String.valueOf(char) and try once...

The signature for the method you are using takes a CharSequence, hence sequence of characters. Using setText(someEmptyString + Byte1), you create a sequence of characters from the concatenation of someEmptyString (which you would define as "") and Byte1.

set with some change like
Ytext.setText(""+Byte1);

setText() expects string or resource id (int). If you want to display numeric value, you need to convert it to string, i.e.:
setText(String.valueOf(someInt));

Try out as below:
Ytext.setText(""+Byte1);
Xtext.setText(""+Byte2);

Related

What's wrong with my calculator android application?

I am making an app that work like calculator..
Here is my code snippet.
EditText etfirst,etsecond;
Button btnadd;
etfirst = (EditText)findViewById(R.id.etfirst);
etsecond = (EditText)findViewById(R.id.etsecond);
btnadd = (Button)findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int first,second,result;
first= Integer.valueOf(etfirst.getText().toString());
second = Integer.valueOf(etsecond.getText().toString());
result = first + second;
tvresult.setText("Result: " + result); }
});
My problem is that when i get integer value from EditText into TextView it is not working ..
I also tried Integer.parseInt(String a); but it is also not helpful..
Please guide me how to make my code properly
use property inputType:number or also can numberDecimal value of inputType.
because by default edittext will accept all character/number etc. but typecast to integer only will work on numeric value.
Change this line
tvresult.setText("Result: " + result);
as
tvresult.setText("Result: " + String.valueOf(result));
and in the exception it is saying NullPointerException bind the variable tvresult with your xml object.

Java - dynamically build textview reference

New Android/Java coder. Trying to replicate in Android app a project I built in MS-Access.
I have a layout with similar named TextViews, like text10, text12, etc. In MS-Access I can dynamically build those names with collection referencing:
For X = 10 To 15
Me.Controls("text" & X) = Null
Next
There is no array required. So looking for structure in java that can accomplish the same functionality.
I want to dynamically set background color of multiple TextView based on two inputs. One is to build TextView reference and the other is a state indicator that will determine color.
Here is one procedure calling setSubColor:
public void Clear(MenuItem mi) {
puz.setText("");
sol.setText("");
for (int i=0; i<26; i++) {
setSubColor(aryA[i].charAt(0), 0);
What I have so far for setSubColor:
public void setSubColor (char c, int i) {
TextView v = (TextView) >>>dynamically reference v using name built with ("tv" + c)
if (i == 0) {v.setBackgroundColor(Color.TRANSPARENT);}
else {v.setBackgroundColor(Color.YELLOW);}
You can get the res id from the res name at runtime. So if your textview had name "text1", you could get the integer id by using:
int id = getResources().getIdentifier("text1", "string", getPackageName());
TextView view = findViewById(id);
But do so only as a last resort, it's error prone, slow and somewhat of an anti pattern.
EDIT by OP: No matter what the name argument is always returns 0 but marked as answer because it led to the following code that works exactly as I want, anti-pattern or not.
TextView v = (TextView) findViewById(getResources().getIdentifier("tv" + c, "id", getPackageName()));
Instead of the TextView Id field use its Tag field.
String tag = (String)textView.getTag() and textView.setTag(Object tag) with tag instanceof String
then you can find the TextView by Tag

EditText field not appending text

I am fairly new to Android. I am making a very simply calculator.
For the Plus button I've written code to getText from the editText field store it in an array index for later addition and then show the + sign to be appended so the user can see the operation.
But for the code posted below, everything else executes except it doesn't show the + sign appended to the EditText view.
button_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lower_textfield.length() == 0)
{
Toast.makeText(getApplicationContext(), "Write a number to add first",
Toast.LENGTH_SHORT).show();
}
else
{
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.append("+");
}
}
});
Here tmp is String and arr is Int Array.
Help would be appreciated.
The method
append()
on the EditText object should must work.
Check the inputType of the EditText object.
May be mistakenly you've written any numeric inputType like.
android:inputType="numberDecimal"
It should be
android:inputType="none"
OR
android:inputType="text"
First of all, make sure you're running on the GUI thread. Never touch GUI from a non-GUI thread.
If that isn't the problem, try this instead:
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.setText(arr[0] + "+");

Convert number in textview to int

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int
CharSequence value1 = getText(R.id.textView);
int num1 = Integer.parseInt(value1.toString());
And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers
Any advice?
I can also provide more of my code if necessary
You can read on the usage of TextView.
How to declare it:
TextView tv;
Initialize it:
tv = (TextView) findViewById(R.id.textView);
or:
tv = new TextView(MyActivity.this);
or, if you are inflating a layout,
tv = (TextView) inflatedView.findViewById(R.id.textView);
To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.
To get a value from tv use tv.getText().
Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..
String tvValue = tv.getText().toString();
if (!tvValue.equals("") && !tvValue.equals(......)) {
int num1 = Integer.parseInt(tvValue);
}
TextView tv = (TextView)findviewbyID(R.id.textView);
int num = Integer.valueOf(tv.getText().toString());
Here is the kotlin version :
var value = textview.text.toString().toIntOrNull() ?: 0
TextView tv = (TextView)findviewbyID(R.id.textView);
String text = tv.getText().toString();
int n;
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
{
n = Integer.parseInt(text);
}
else
{
System.out.println("not a valid number");
}
this code actually works better:
//this code to increment the value in the text view by 1
TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
CharSequence v1=quantityTextView.getText();
int q=Integer.parseInt(v1.toString());
q+=1;
quantityTextView.setText(q +"");
//I hope u like this

Another Android Activity or an iterative JAVA method?

I am new to Android application development and am trying to find a way to proceed through a series of screens that take in user input. I'm making a small math game where the user would answer basic two integer addition problems. So far the main menu is created. It has a New Game button which launches my GameActivity and it runs just fine for one math problem. However, after the user inputs their answer to the simple math problem, I would like to be able to continue on to another math problem once the user had answered the current problem and the method would return a correct/incorrect value. Initially I thought of doing something like a basic FOR loop from within the GameActivity :
for(int i = 0; i < 10; i++){ gameMethod(); }
gameMethod() is a JAVA method that simply generates 2 random numbers, adds them to get the correct answer and then prompts the user using an EditText field to type in their guess. It displays the random numbers and answer using TextView boxes created in an XML layout file.
Each call to the gameMethod would, at least I think, just re-input the randomized numbers into the TextView fields displayed on the screen each iteration. I really don't care what the previous numbers were so I figured I would just overwrite them. I wan't able to get the code to do that though. I put in a Log.d() statement or two and found that the FOR loop was in fact running through correctly 10 times, but it was not waiting for user input before firing off its next gameMethod().
In doing some looking around, I found the startActivityForResult() and wondered if this was a more appropriate way of approaching this. So in this way, I foresee having three Activities, the Main menu which calls the GameActivity which would then iterate through, say 10 times, each iteration calling yet another activity GameScreenActivity which would actually put the numbers on the screen, read in user input and then return 1 for a correct answer and 0 for an incorrect answer. So far in reading up on StarActivityForResult() I'm getting somewhat confused by the process and wondered if this was even a plausible path to be exploring.
Again, I'm very new at this Android programming and appreciate any and all help that I can get.
Thank you.
Sorry for not including the gameMethod() initially, I've added it below.
// Create and initialize arrays of integers
int[] a = {0,1,2,3,4,5,6,7,8,9,10};
int[] b = {0,1,2,3,4,5,6,7,8,9,10};
// Creates random number generator
Random randy = new Random();
// Generates two random values to add
int r1 = randy.nextInt(10);
int r2 = randy.nextInt(10);
// Calculates correct answer
int an = a[r1] + a[r2];
// Displays 1st number
TextView number1 = (TextView) findViewById(R.id.firstNumber);
number1.setText(Integer.toString(a[r1]));
// Displays 2nd number
TextView number2 = (TextView) findViewById(R.id.secondNumber);
number2.setText(Integer.toString(b[r2]));
// Displays correct answer
TextView answer1 = (TextView) findViewById(R.id.answerNumber);
//hide answer until user puts in theirs
answer1.setVisibility(View.INVISIBLE);
answer1.setText(Integer.toString(an));
//hide the answer place holder value
TextView uAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber);
uAnswerDisplay.setVisibility(View.INVISIBLE);
//Get the EditText field that the user will input their answer to
EditText inputText = (EditText) findViewById(R.id.userInput);
//set up a listener to run once the ENTER key is hit after their answer has been entered
inputText.setOnKeyListener(new EditText.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
//only go on the ENTER key when pressed DOWN
if((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
EditText innerInputText = (EditText) findViewById(R.id.userInput); //get the EditText box reference
TextView innerUAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber); //get the TextView box that the answer will go in
String inputString = innerInputText.getText().toString(); //capture the user's input
int uAnswer = Integer.parseInt(inputString); //parse user answer to an integer
int cAnswer = Integer.parseInt((((TextView) findViewById(R.id.answerNumber)).getText()).toString());
innerUAnswerDisplay.setText(Integer.toString(uAnswer)); //display the string after converting from integer
//change colors of text based on correctness
if (uAnswer == cAnswer){ innerUAnswerDisplay.setTextColor(Color.GREEN); } //green for correct
else { innerUAnswerDisplay.setTextColor(Color.RED); } //red for incorrect
innerUAnswerDisplay.setVisibility(View.VISIBLE); //make the user input answer visible
TextView innerAnswer1 = (TextView) findViewById(R.id.answerNumber);
innerAnswer1.setVisibility(View.VISIBLE); //hide answer until user puts in theirs
} //end of if
return false; //return false
} //end of onKey
}); //end of setOnKeyListener
Sorry for all the edits, I couldn't get the edits to include the code and post correctly so I broke it up into chunks and added a little at a time.
From what you say, I'd consider two ways of letting the user answer questions:
have an onclick listener on the input EditText that triggers a new loop;
have a dialog activity that gets started in the beginning of the loop, which prompts the user for a new answer, your game activity would receive the answer via its onActivityResult.

Categories