GetSerializableExtra returns null

I need some help resolving the following question.

I have two actions: A and B. Activity A starts B for the result, and B sends A back to the serializable object.

Action: initial 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 at which action A receives 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 that goes 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(); } } 

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

+4
source share
1 answer

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 call the Activity, not the Intent returned by the activity called startActivityForResult ().

Result Intent is a data parameter passed to onActivityResult (). You must restore your Serializable object.

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

One more thing: I think you have one more error in ExpensePacket.getMonthYear (), because you are creating a String returnString but returning something else. Just check this part to make sure you do what you want.

+8
source

Source: https://habr.com/ru/post/1438321/


All Articles