简体   繁体   中英

How to get the context lo launch a intent method from other class

I'm trying to call a mehod from another activity. This method have a Intent inside and I'm sure that the problem is with the context in the intent. I read some similars answer but I can't do it... I get a nullpointerException

ActivityA

This is the method with the intent...

public void startGreetingRecorder() {
        Intent recordIntent = new Intent(this, NewActivity.class);
        .
        .
        startActivityForResult(recordIntent,);

    }

ActivityB

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_save) {

            ActivityA.startGreetingRecorder();

        }
        return true;
    }

This is that I'm trying to do but don't work.

ActivityA

This is the method with the intent...

public void startGreetingRecorder(Context context) {
        Intent recordIntent = new Intent(context, NewActivity.class);
        .
        .
        startActivityForResult(recordIntent,);

    }

ActivityB

protected Context context;

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_save) {

            ActivityA.startGreetingRecorder(context);

        }
        return true;
    }

You are statically calling the method, so you need to mark the method as static as well as sending a context.

Activity A: (the receiver)

public static void startGreetingRecorder(final Activity a) {
  Intent recordIntent = new Intent(a, NewActivity.class);
        .
        .
  a.startActivityForResult(recordIntent,<SomeInteger>);

}

Activity B: (the caller)

[Edit] - Added the integer argument. This is used for handling the result.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == R.id.menu_save) {

        ActivityA.startGreetingRecorder(this);

    }
    return true;
}

If you don't actually need to handle the result, you can use context.startActivity(intent)

You can't call and activity method from other Activity in that way, you can use EventBus to achieve communication between activities.

Try with EventBus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM