开发者

Define interfaces for Android Intents

When using Android startActivityForResult, I don't have any guarantee about what I'll get in the Intent returned by onActivityResult.

I would like to define some kind of interface to limit the possibility of errors when transmitting data from an Activity to another (eg mistyped variable name).

Is t开发者_运维问答here a way to do that? For example could I use something similar to the Android Interface Definition Language but between Activitys?


There are 2 scenarios when passing data between two activities A,B.

  1. Activity A wants to pass data on Activity B ( through the startActivity Intent )
  2. Activity B wants to return data on Activity A when it ends using setResult

on both cases i suggest to create some public static final variables for the extra keys to use.

For example if you need to pass an integer using the key "rating" from A to B i would probably do

class A extends Activity {
    public static final String RESULT_STATUS = "RESULT_STATUS";
    // Whatever ....
    public void startB(int rating) { 
        Intent toStart = new Intent(this, B.class);
        toStart.putExtra(B.EXTRA_RATING, rating);
        startActivityForResult(toStart, 0);
    }

    public void onActivityResult(int requestCode /* 0 in our case */, int resultCode, Intent data) {
            if (resultCode == RESULT_OK ) {
                    String returnedStatus = data.getStringExtra(RESULT_STATUS);
                    // Whatever ....
            }

}

class B extends Activity {
    public static final String EXTRA_RATING = "EXTRA_RATING";
    public void onCreate(Bundle b) {
        // Whatever ....
        int rating = getIntent().getIntExtra(EXTRA_RATING,0);
    }

    // Whatever ....

    public void returnDataAndFinish(String status) {
        Intent result = new Intent();
        result.putExtra(A.RESULT_STATUS, status);
        setResult(RESULT_OK, result);
        finish();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜