Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetSerializableExtra returning null

I need a little help to solve the following question.

I have two activities, A and B. The activity A start B for result, and B sends back to A a serializable object.

Activity a starting activity B:

    ...
    Intent intent = new Intent(MainActivity.this, ExpenseActivity.class);       
    startActivityForResult(intent, EXPENSE_RESULT);  
    ...

Activity B sending data to A:

    ...
    ExpensePacket packet = new ExpensePacket();
    ...
    Intent returnIntent = new Intent();
    returnIntent.putExtra(MainActivity.PACKET_INTENT,packet);
    setResult(RESULT_OK,returnIntent);     
    finish();

Point where the activity A gets the data sent from B:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == EXPENSE_RESULT) {
        if(resultCode == RESULT_OK){                
            ExpensePacket result = (ExpensePacket)getIntent().getSerializableExtra(PACKET_INTENT);

            wallet.Add(result);
            PopulateList();
        }
        else{
             //Write your code otherwise
        }
    }
}    

My Serializable object, the one who is sent from B to A:

class ExpensePacket implements Serializable {

    private static final long serialVersionUID = 1L;    
    private Calendar calendar;  

    public void SetCalendar(Calendar aCalendar){
        calendar = aCalendar;
    }

    public Calendar GetCalendar(){
        return calendar;
    }

    public String GetMonthYear() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        sdf.format(calendar.getTime());                 

        String returnString = "";
        returnString += sdf.toString();
        returnString += "/";
        returnString += Functions.GetMonthName(calendar);

        return sdf.toString();
    }   
}

Somebody can help me to figure out why the data sent from B to A is a null pointer.

like image 683
rodolfo gomes dias Avatar asked Oct 08 '12 02:10

rodolfo gomes dias


1 Answers

I think I found your error:

In your onActivityResult() method, you should use the Intent "data" parameter, instead of the getIntent() method. getIntent() returns the Intent used to invoke the Activity, not the Intent returned by the Activity invoked by startActivityForResult().

The result Intent is the "data" parameter passed in onActivityResult(). You should recover your Serializable object from there.

I made a small project with your code and can reproduce your problem. Changing getIntent() with data parameter solved the issue.

Just one more thing: I think you have another error in ExpensePacket.getMonthYear(), because you construct the String returnString, but return something else. Just check that part too to be sure you're doing what you want.

like image 103
eternay Avatar answered Oct 01 '22 09:10

eternay