Riskhan Riskhan - 3 years ago 244
Android Question

How to update a TextView of an activity from another class

Iam new to android/java programming. I have two class, one is an activity and other normal class. In my activity class contains TextView. Can i update TextView of activity class from normal class. I tried with random code, but it fails. Please provide a solution...

// activity class
public class MainMenu extends Activity {
public TextView txtView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txtView = (TextView)findViewById(R.id.text);
}

}

// other class
public class ClassB {
public ClassB(){
}

public void Update(){
TextView txtView = (TextView)findViewById(R.id.text);
txtView.setText("Hello");
}
}

Answer Source

You have to pass the Context reference via constructor.

public class ClassB {
   Context context;
   public ClassB(Context context){
     this.context=context;
   }

   public void Update(){
        TextView txtView = (TextView) ((Activity)context).findViewById(R.id.text);
        txtView.setText("Hello");
   }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download