开发者

Update main activity values from a different activity

I want to update textview in my main activity view.

I have main.xml file that contains the main application ascreen, in tha开发者_StackOverflow中文版t screen, I have textview that I need to update from time to time from another activity (class).

If I try to update those values from the main activity it work perfect, but when I'm trying to do it from deferent activity the application crashes.

Here is the method of the main activity, I need to know how to call it from the other activity.

Main Activity method:

    public void update_counters(){    
        TextView sms_textview = (TextView) findViewById(R.id.sms_textview);
        sms_textview.setText(String.valueOf(sms_missed));
    }

Please Help


Indeed it's a bad practice to have any static references to activities (or other contexts). Activity are designed to be rather independed from each other.

You can receive a result from an activity that was started with startActivityForResult() method and than react appropriately.


Like @Roman said, it's a bad practice to touch the UI stuff from other activities, and activities should be independent. What you can do, is a little bit redesign your message passing method. One might be good is to use the broadcast receiver, it also guarantees a better extensibility of your program.

So, whenever your 'other' activity need to call the update_counters, it turns to broadcast such an intent. Your previous MainActivity should register to listen to that broadcast, and update the UI as necessary. What would be the best is you can have several more instance of that activity, or other activity that can register to that broadcast as well.


Is there only one instance of your main activity? If so, store a static reference to it in the main activity class, initialize it in onCreate. Then have a static method that uses that reference to get to the instance:

static MainActivity TheMainActivity;

static public void update_counters()
{
    TextView sms_textview = (TextView) TheMainActivity.findViewById(R.id.sms_textview); sms_textview.setText(String.valueOf(sms_missed));
}

The in the other activity:

MainActivity.update_counters();

This is called a singleton. Or, sometimes, a global.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜