Sunday, November 13, 2011

Change a textView field after creating an Activity

I could not remember how to change the textView field after the start of the program. I got an error that was caused by the int to string conversion. I finally got my code to work and I decided to share it.
I added a button to make the application more interactive


public class Main extends Activity

Button add;
TextView tv;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)
        add = (Button) findViewById(;
        tv = (TextView) this.findViewById(;
        tv.setText("0"); //the starting value
        add.setOnClickListener(new View.OnClickListener()
        int counter = 0;
        String s = "";
public void onClick(View v)
s =  Integer.toString(counter); //change to string
tv.setText(s); //the text will be changed here.

I am sure that I ran into a better method of adding text to the TextView. I just wanted to publish this here as it might help others getting something running. If you can see any areas where I can refine my code then please post it in the comments.