0

I want to change a TextView from another, non-activity class. I see the answer here How to update a TextView of an activity from another class in the adapost's post, but I don't know how to properly pass a context to "ClassB".

In Main class, I tried ClassB obj = new ClassB(this); and ClassB obj = new ClassB(getApplicationContext());. But every time, TextView txtView = (TextView)findViewById(R.id.text); returns NullPointerException.

I am sure that I do it aftersetContentView, I can acheive this textView from Main class.

How to pass the context to make it work?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bart K
  • 21
  • 5

2 Answers2

0

Create an object of that activity inside the other class. Pass the activity in the constructor and attach it to the object. This way, all public variables and methods from the activity will be retrieved in the other class.

class B {
final MyActivity activity;
public B(MyActivity activity) {
this.activity = activity;
}
// here you can access all public field variables and methods of MyActivity.
}

But for activity to activity, you can make all those variables that will be used outside "static".

Francis Nduba Numbi
  • 2,499
  • 1
  • 11
  • 22
0

The problem was the Id resource. When the TextView's Id was set to @+id/text, the object returned NullPointerException. When I created Id xml resource, added an item <item type="id" name="tv_zero" /> and in the activity xml android:id="@id/tv_zero" Application worked fine. I called it in the main by ClassB ObjOne = new ClassB(this); and ObjOne.Update();

Bart K
  • 21
  • 5