Updating textView in Android Studio - java

I have a textView set up on my main activity, and a button. When I click the button, I'd like the textView to start updating it's value based on the code below. However, this doesn't work and the problem is the loop. Can someone explain why? I am new to Java and Android Development
button2 = (Button) findViewById(R.id.button);
button2.setOnClickListener(new OnClickListener() {
TextView textView = (TextView)findViewById(R.id.refView);
public void onClick(View arg0) {
for(i=1;i<1;i++){
i = i + 1;
textView.setText(String.valueOf(i)+"hello");
}
}
});
Thank You

Try this:
TextView textView = (TextView)findViewById(R.id.refView);
button2.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View arg0) {
i = i + 1;
textView.setText(String.valueOf(i)+"hello");
}
});
Your for loop conditions were wrong.
for(i=1;i<1;i++) won't even start, because 1<1 is already met.
Initiate count variable i before onClick and then update it before click and set new text with updated i.

Not sure what exactly you want to happen. But, you can get rid of this line
i = i + 1;
because the i++ already increments i by 1 with each iteration of the for loop.
Second, since i starts off at 1 and you want the loop to run while i<1, it will never enter the loop. It is never less than 1.
Third, if the conditions were different, say
for (int i=0; i<10; i++)
it will run through the loop so fast that you won't even recognize a change.

Related

Print several inputs into different plain texts - Android Studio

I'm working on a project in Android Studio where I have one EditText where the user will insert one word at a time, 10 times. Everytime the user writes a new input and clicks on the button it goes to a different TextView than the previous ones and different from the next ones.
How can I put the different inputs into the specific (different) TextViews?
Every TextView has a different sequencial ID like, word1, word2, etc.
I haven't done java in a long time, so I'm having problems with logic. I tried to do the following but the app crashes.
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
printwords(gameword.getText().toString());
}
});
public void printwords(String word) {
String[] array = new String[10];
TextView[] positions = new TextView[10];
for (int i=0; i < 10; i++){
array[i] = word;
positions[i].setText(array[i]);
}
}
}
You're creating a new array of TextView's and String every time the button is clicked. Change your code to the code below and it should work.
Make your int[] textViews , String[] array & int i = 0 class variables and then initialize them in onCreate() after setContentView()
In above code, int[] textViews is the array of ID's of TextView's from your activity.
After doing that, change your code to following:
gameword = (EditText) findViewById(R.id.wordj);
public void onClick(View v) {
array[i] = gameword.getText().toString();
YourActivity.this.findViewById(textViews[i]).setText(array[i]);
i++;
}
});

onClick is not working until I comment the while Loop inside my function

I have a function goClicked which is a onClick method of "Go" button, but when clicking the button, the function is not executed (I am able to say this because the toast is not showing).
But if I comment the while loop then click on the "Go" button, the function is executed (the toast is appearing).
public void goClicked(View view) {
afterGoPressed();
Toast.makeText(MainActivity.this,"pressed",Toast.LENGTH_SHORT).show();
countDown();
correctCount = 0;
totalCount = 0;
TextView time = (TextView) findViewById(R.id.time);
String timetext = time.getText().toString();
while (!timetext.equals("0")) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
}
By putting a tight loop like that into your code the Event Dispatch Thread (EDT) is "starved" and so the GUI never gets a chance to do anything.
A simple workaround would be add a bit of a sleep in the loop to let the EDT have a turn. But you really need to do a bit more research into how to do GUI programming.
As it stands the code looks like an infinite loop because the timetext variable used in the loop condition does not change inside the loop. timetext is presumably supposed to change in reaction to GUI events. If the GUI is starved and so doesn't get to run then timetext never changes.
I think you're dealing with an infinite loop.
If when you create the variable timetext the text contained in time is not 0, the variable timetext will never be 0, hence the condition to exit the loop is never met.
public void goClicked(View view) {
afterGoPressed();
Toast.makeText(MainActivity.this,"pressed",Toast.LENGTH_SHORT).show();
countDown();
correctCount = 0;
totalCount = 0;
TextView time = (TextView) findViewById(R.id.time);
String timetext = time.getText().toString(); // <--- this will never change
while (!timetext.equals("0")) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
}
Sorry, I know this doesn't offer much of a practical solution to your issue. Maybe if you let us know what you're trying to achieve with that loop we can help a little better.
But for all I know, if you block a thread inside of the public void onClick(View view) method of a View.OnClickListener instance (either by making it sleep with Thread.sleep() or by running an infinite loop), it will also freeze the rest of your app until the onClick(View view) method finishes. That's why you can't even see the Toast appear, although it's before the while loop. Because the main Thread was notified that there has been a click event, but the response from that event is never arriving.

Variable in a name [duplicate]

This question already has an answer here:
App crashing at the end of array
(1 answer)
Closed 7 years ago.
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
element.setImageResource(image_elements[1]);
name.setImageResource(image_names[1]);
}
});
My code works when hard coded but I want to use operators like ++ and --. Why can't I? Example below.
element.setImageResource(image_elements[++]);
name.setImageResource(image_names[++]);
Why doesn't this work and how can I get it to.
If your goal is to move to the next element on each click, why not simply use an int index field and increment it?
nextButton.setOnClickListener(new View.OnClickListener() {
private int i = 0;
public void onClick(View v) {
// parallel array anti-pattern below is a no-no
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i++;
// if you want to cycle elements of the array and
// to prevent array index out of bounds:
i %= image_elements.length;
}
});

Java(Android) stuck in while loop

when I run my app it will continuously be stuck in a while loop. It should leave the while loop when a button is pressed, however even after pressing a button it continues to loop.
View.OnClickListener listener11 = new View.OnClickListener() {
#Override
public void onClick(View view) {
temp1 = button[0];
temp3 = button[0].getBackground();
state++;
}
};
while(state == 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
button[0].setOnClickListener(listener11);
}
variable:
state is an int temp1 is a button temp3 is a Drawable
the delay is there because I actually have 20 buttons and I have the setOnClickListeners for all the buttons inside that while loop so I think it causes it to crash without the delay. Another question would be is it possible to have the setOnClickListeners outside the while loop but still be able to check for button clicks inside the loop?
The problem is you are pressing the button while the thread is in a sleeping state causing the event to not be triggered and therefor the state to never change.
You should remove the while loop and just set all the listeners in a for loop:
for(int i = 0; i< button.length; i++) {
button[0].setTag(i);
button[0].setOnClickListener(listener11);
}
And then change your listener to be something like:
private boolean firstClick = true;
View.OnClickListener listener11 = new View.OnClickListener() {
#Override
public void onClick(View view) {
if(firstClick) {
firstClick = false;
temp1 = button[(int)view.getTag()];
} else {
temp2 = button[(int)view.getTag()];
}
}
};
I'm not sure exactly what the code is supposed to be doing because I have no idea of the context, but I think think you could remove the while loop altogether:
// initialize the listener
View.OnClickListener listener11 = new View.OnClickListener() {
#Override
public void onClick(View view) {
// add code that runs when button is clicked here
}
};
// now that we have the listener all set up we add it to the button, at which point it just keeps listening for you, no need to put the thread to sleep
button[0].setOnClickListener(listener11);
UPDATE:
So because you want to see if the second value matches the first value you could use a helper method:
private String firstValue = "";
public boolean isMatch(String mostRecentValue) {
boolean match = false;
if (firstValue.isEmpty()) {
firstValue = mostRecentValue;
} else {
match = firstValue.equals(mostRecentValue);
firstValue = "";
}
return match;
}
This method takes a value and if it is the first click the value is saved, if it is the second click it compares it with the first click and then resets the method. A boolean is returned false for no match, and true for a match. Call this method from within the onClick() method and pass in the buttons value. I've used String as an example value but you could use any object type.
I think you might be misunderstanding what setOnClickListener is doing. It's not handling the click, it is setting up the click handler. The line button[0].setOnClickListener(listener11); would be part of your activity initialisation and then not called again.
The reason you get stuck is because the main thread is busy in the while loop and isn't given an opportunity to process click events. Click events are handled on the main thread but only when it's not already busy doing something. In this case, it's forever busy in the while loop. For example, if the main thread was processing a method that would take 10 seconds to complete and you tap on a button 3 seconds into it, the button press wouldn't be handled for another 7 seconds. At which point, the previously set listener11 would be executed.
What you seem to be trying to achieve is already handled by the Looper. You need to be thinking in terms of event handling. So in other words, all your logic needs to go in listener11 or something similar.

Three Buttons OnClickListener Android App

I have been trying to built a Math Flash Card App, the user inputs two numbers and then chooses one button depending if it wants the numbers add, subtract or multiply.
Image:http://i.stack.imgur.com/83FdN.png
The problem seem to be the OnClickListener. I have created other projects with one button and they work perfectly but with two buttons i don't know how to do it.
I have tried:
Creating OnclickSListener for each button, the code doesn't show any error but when i try to run the app it force closes.
I have tried the methods on this post: Android - multiple OnClickListener? and this one http://blog.idleworx.com/2011/06/build-simple-android-app-2-button.html and stil the app shows no errors but can't run.
I have taken the button code out and run it and then it works. I don't know what else to do.
This is the last code that I have tried just trying with one button, app still force closed.
public class MainActivity extends ActionBarActivity implements OnClickListener{
int num1, num2, total;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtInt1 = (EditText)findViewById(R.id.txtInt1);
final EditText txtInt2 = (EditText)findViewById(R.id.txtInt2);
final TextView result = (TextView) findViewById(R.id.txtResult);
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());
final Button btnAddition = (Button) findViewById(R.id.btnAddition);
Button btnSubstraction = (Button) findViewById(R.id.btnSubstraction);
Button btnMultiplication = (Button) findViewById(R.id.btnMultiplication);
/*
btnSubstraction.setOnClickListener(this);
btnAddition.setOnClickListener(this);
btnMultiplication.setOnClickListener(this); */
btnAddition.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v == btnAddition){
if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20",
Toast.LENGTH_SHORT).show();
}
else {
total = num1+num2;
result.setText(num1+" + "+num2+" = "+total);
}
}
}
});
Thank you!
Since you are implementing OnClickListener, it is required that you have the Override method onClick(View arg). By using switches you can setup individual cases for each button you want clickable actions for. Here are the steps
1) After instantiation of button widgets: Set onClickListener to each button widget
btnSubstraction.setOnClickListener(this);
btnAddition.setOnClickListener(this);
btnMultiplication.setOnClickListener(this);
2) Create your cases in onClick() method: Make sure that this is outside of your onCreate()
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddition:
// do some action for addition
break;
case R.id.btnSubstraction:
// do some action for substraction
break;
case R.id.btnMultiplication:
// do some action for multiplication
break;
default:
break;
}
}
3) Be sure that you implement OnClickListener
For a great tutorial on buttons you should check out http://ljtatum.blog.com/buttons/. You can download free example code. But what I have posted above will work for you. Cheers!
Its better to move them to a single OnClick block of code .
Check whether the v.getId() is the button id .
Try by changing the code to
btnSubstraction.setOnClickListener(this);
btnAddition.setOnClickListener(this);
btnMultiplication.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnAddition){
if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20",
Toast.LENGTH_SHORT).show();
}
else {
total = num1+num2;
result.setText(num1+" + "+num2+" = "+total);
}
}
}
});
Have you tried setting Logs? u can do this by:
Log.e("TAG","MSG");
Then you can watch the LogCat and hunt the error down! ;)
I would implement the other Buttons exactly like you did your first one with the anonymous inner class.
btnSubstraction.setOnClickListener(new OnCLickListener() {
#Override
public void onClick(View v){
Your Code goes here or u trigger another Method for readability for example:
Substraction();
...
You should keep an Eye on the ID of the Buttons:
R.findViewById...
But you don't even need this if you trigger the onClick on the buttonobject. ;)
Yeah I guess that's it, try to leave the:
if(v==btnAddition)
The System already knows this by triggering the onClick over the buttonObject.
SO your code should go like this:
btnAddition.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (num1 <=0 || num1 >20 || num2 <=0 || num2 >20 ){
Toast.makeText(MainActivity.this, "The numbers shoudl be between 1 and 20",
Toast.LENGTH_SHORT).show();
}
else {
total = num1+num2;
result.setText(num1+" + "+num2+" = "+total);
}
}
}
});
btnSubstraction.setOnClickListener(new OnCLickListener() {
#Override
public void onClick(View v){
//Substractioncode here
}
});
What DaveS. is saying is that you are probably getting an exception in onCreate() on these two lines
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());
these should be moved to the onClick() because in onCreate() they have not yet been given values so you will get a NumberFormatException. You also should do some error-checking such as
try {
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());
} catch (NumberFormatException e) {
// log the error and possibly print a message to the user
}
You should always post your stacktrace when your app crashes so we can find the answer easily. The issue with the code you posted is not due to the way you are setting the OnClickListener which is what you indicated.
This SO answer shows how to set the OnClickListener for Buttons. All will work fine so you decide which works best for you.
You are trying to getText and convert that string in int in onCreate(). In onCreate() you will get "" which is a blank string while you trying to convert it you will get a NumberFormatException. Solution is move these two inside onClick method of button.
num1 = Integer.parseInt(txtInt1.getText().toString());
num2 = Integer.parseInt(txtInt2.getText().toString());

Categories

Resources