Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a button change value of a textview

So, my friend got me to mess with android programming in android studio today. I started making a beginner application and have had some good results. But right now I am trying to get a button to change the value of a textview.

Here is the code for the button and the textview

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add one"
        android:id="@+id/button3"
        android:layout_alignBottom="@+id/button2"
        android:layout_alignRight="@+id/textView"
        android:layout_toRightOf="@+id/button"
        android:onClick="addone"/>

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/counter"
        android:textSize="40dp"
        android:layout_alignTop="@+id/button3"
        android:layout_centerHorizontal="true"/>

and here is the code that is attempting to change the value of the text view.

public void addone(){

    numtest+=1;
    TextView t = (TextView) findViewById(R.id.counter);
    t.setText(numtest);

}

THe program compiles and opens, but it crashes whenever i press the button. I believe I have narrowed down the culprit to this line, but im not sure why it isnt working

TextView t = (TextView) findViewById(R.id.counter);

Any ideas?

like image 670
Bigandrewgold Avatar asked Dec 04 '22 09:12

Bigandrewgold


2 Answers

An overloaded method is your problem. It is subtle, a mistake even a seasoned programmer could make. I've made it myself before.

You are calling TextView.setText(Integer). This attempts to load a string having a resource id of numtest, which does not exist.

Try this instead:

public void addone(View v){
    numtest+=1;
    TextView t = (TextView) findViewById(R.id.counter);
    t.setText(numtest+"");
}

This will call TextView.setText(CharSequence) instead, which is what you're really trying to do.

Also, as Osmium USA demonstrated, your method signature is incorrect. The button pressed callback method must accept a view, and must be public.

like image 176
William Morrison Avatar answered Dec 07 '22 00:12

William Morrison


When you give a layout element a function to execute, it looks for that name accepting a View (so you know what was clicked if you assign multiple elements the same click behavior in the XML).

So addone() must be addone(View v)

From the Button Docs

In order for this to work, the method must be public and accept a View as its only parameter

William Morrison also has a good point. You should make that number a String either by what he did or use the Integer Class:

t.setText(Integer(numtest).toString());

or

t.setText(numtest+"");
like image 35
Osmium USA Avatar answered Dec 07 '22 01:12

Osmium USA