God_Father
God_Father

Reputation: 601

How to call a method in an Activity from another class

I am working on an SMS application and I have a method in my MainActivity to perform a button click:

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

This method works fine and performs the button click when I call this method from inside the MainActivity class.
But, when I call this method from any other class as shown below, where I call the Main Activity's updateMessage method from the IntentServiceHandler class, I am getting a NullPointerException:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.Button.performClick()' on a null object reference

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();
    }
}

How can I handle this?

Edit: I even tried to make the updateMessage method static, and now i get the following exception

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Upvotes: 0

Views: 643

Answers (1)

Elvis Lin
Elvis Lin

Reputation: 11

Don't call the method of Activity in an IntentService, try to use Intent to communicate between Activity and IntentService.

  1. Replace the last two statements onHandleIntent() with

    Intent intent = new Intent();
    broadcastIntent.setAction(MainActivity.UPDATE_MESSAGE);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    sendBroadcast(intent);
    
  2. And you should register a BroadcastReceiver in onCreate() of MainAcitivty like

    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. onHandleIntent of IntentService run in another thread (instead of main thread / ui thread), so Updating UI components in onHandleIntent isn't permitted.

Upvotes: 1

Related Questions