user2411574
user2411574

Reputation: 13

Edit TextView outside of OnCreate or Buttons Java Based

I am a beginner and have floundered on what should be an easy task. Through OnCreate or through buttons, I can edit any of the textviews through t.append(bla bla bla) but when I try to externalize the editing to another class, it all goes south and the program doesn't launch. This is on Android.

Main Java File

Public class MainActivity extends Activity

{
public int x = 1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

   setContentView(R.layout.main);

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

**THIS EDITS THE TEXTVIEW CORRECTLY---->** t.append(x);

MyTask update1 = new MyTask();

**THIS MAKES THE CODE FAIL--->**update1.run();
}

OTHER CLASS FILE

(usual imported packages)

Public class MyTask extends Activity {
@Override
public void run() {

setContentView(R.layout.main);

TextView u = (TextView)this.findViewById(R.id.android_happy);

u.setText(6+"");
}}

Thank you for any advice or places to read that I can go.

Upvotes: 1

Views: 1082

Answers (1)

Try to declare your TextView as instance variable and instantiate it in your onCreate method. In that way, you can access your TextView in other class.

Upvotes: 1

Related Questions