Can not getIntExtra() at onActivityResult

女生的网名这么多〃 提交于 2019-12-23 03:23:09

问题


I got a problem with sending and receiving int types from one activity to another via Intent;

I'm sending it with onActivityResult() function which is placed at the receiving activity.

The code:

The Sending Activity:

Intent ba=new Intent();

MyPoints = fgv.getPoints();

int MP=(int)MyPoints;
Log.i("Problem","MyPoints MP = "+MP);

ba.putExtra("FocusScore",MP);
Log.i("Problem","MyPoints = "+MP);

setResult(RESULT_OK,ba);
finish();

The Receiving Activity:

//At the onClick in order to move the the other class

Intent goFocus =new Intent(Games.this,FocusGame.class);

startActivityForResult(goFocus,1);

//At the onActivityResult function

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==RESULT_OK)
        {   

          switch (requestCode) {

             case 1: {
             //Coming back from Focus-Game
             //Problem:!!

              int sss= getIntent().getIntExtra("FocusScore", -1); 
              Log.i("Problem","sss = "+sss);

                 }
             break;

             default :
             break;

            }

}

The result of the code is given a log where sss=-1. Which means that

getIntent().getIntExtra();

is always null.

And the Log of the MP is working fine.

-

Hope you could help me over here.

- Thanks in advance, Yaniv.


回答1:


Use the value of data not getIntent()

if (data != null) {
    //int sss= getIntent().getIntExtra("FocusScore", -1); 
    Bundle extras = data.getExtras();
    int sss =  extras.getInt("FocusScore");
}

or just

if (data != null) {
    //int sss= getIntent().getIntExtra("FocusScore", -1);     
    int sss= data.getIntExtra("FocusScore", -1); 
}

More info: Cannot get Data from the intent - Android




回答2:


The problem is that you're using getIntent() istead of data

int sss= getIntent().getIntExtra("FocusScore", -1); 

should be

int sss= data.getIntExtra("FocusScore", -1); 

Remember that getIntent() returns the intent that was used to create the calling Activity, not the intent that YOU used to launch the second activity.



来源:https://stackoverflow.com/questions/22204869/can-not-getintextra-at-onactivityresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!