【问题标题】:How to call a method in an Activity from another class如何从另一个类调用 Activity 中的方法
【发布时间】:2016-11-13 06:18:07
【问题描述】:

我正在开发一个 SMS 应用程序,我的 MainActivity 中有一个方法可以执行按钮单击:

public void updateMessage() {
    ViewMessages.performClick();
}

当我从MainActivity 类内部调用此方法时,此方法工作正常并执行按钮单击。
但是,当我从如下所示的任何其他类调用此方法时,我从 IntentServiceHandler 类调用 Main Activity 的 updateMessage 方法,我得到一个 NullPointerException

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean android.widget.Button.performClick()”

public class IntentServiceHandler extends IntentService {

    public IntentServiceHandler() {
       super("IntentServiceHandler");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String message = intent.getStringExtra("message");
        TransactionDataBase transactionDB = new TransactionDataBase(this, 1);
        transactionDB.addMessage(message);
        MainActivity mainActivity = new MainActivity();
        mainActivity.updateMessage();
    }
}

我该如何处理?

编辑:我什至尝试将 updateMessage 方法设为静态,但现在出现以下异常

android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图。

【问题讨论】:

标签: java android nullpointerexception


【解决方案1】:

不要在IntentService中调用Activity的方法,尽量使用Intent在Activity和IntentService之间进行通信。

  1. 将最后两个语句 onHandleIntent() 替换为

    Intent intent = new Intent();
    broadcastIntent.setAction(MainActivity.UPDATE_MESSAGE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    sendBroadcast(intent);
    
  2. 你应该在 MainAcitivty 的 onCreate() 中注册一个 BroadcastReceiver,比如

    private BroadcastReceiver receiver;
    
    @Override 
    public void onCreate(Bundle savedInstanceState){
    
        // ....
    
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_MESSAGE);
    
        receiver = new BroadcastReceiver() {
            @Override 
            public void onReceive(Context context, Intent intent) {
            // do something based on the intent's action 
            // for example, call updateMessage()
            } 
        };
    
        registerReceiver(receiver, filter);
    } 
    
  3. IntentService 的 onHandleIntent 在另一个线程中运行(而不是主线程/ui 线程),因此不允许在 onHandleIntent 中更新 UI 组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多