Maurício Giordano
Maurício Giordano

Reputation: 3276

Can't access extras after coming back from an intent

I have a MainActivity that has a child activity PatientActivity.

The PatientActivity has a child activity RecordActivity.

In MainActivity, I intent to PatientActivity putting an extra content:

MainActivity.java

...
listPatients.setOnItemClickListener(new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id)
    {
        try {
            Intent intent = new Intent(view.getContext(), PatientActivity.class);
            intent.putExtra("patient", patients.getJSONObject(position).toString());
            startActivity(intent);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
});
...

In PatientActivity.java

    ...
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    intent = getIntent();

    String patientFromJson = intent.getStringExtra("patient");

    patient = Patient.fromJson(patientFromJson);

    ...

Now, in PatientActivity, at some point I intent to RecordActivity.

While in RecordActivity, when I press the Up button (not the back button), it crashes because the PatientActivity.onCreate() couldn't find the reference of patient, causing a NullPointerException.

How can I work this out?

Upvotes: 1

Views: 76

Answers (2)

Maur&#237;cio Giordano
Maur&#237;cio Giordano

Reputation: 3276

Done using SharedPreferences as @heLLo suggested.

PatientActivity.java

...
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    try
    {
        intent = getIntent();

        String patientFromJson = intent.getStringExtra("patient");

        patient = Patient.fromJson(patientFromJson);

        SharedPreferences.Editor editor = getSharedPreferences("br.com.metadoc", MODE_PRIVATE).edit();
        editor.putString("currPatient", patient.toString());
        editor.commit();

        setTitle(patient.getName());
    }
    catch(NullPointerException e)
    {
        String toBeAPatient = getSharedPreferences("br.com.metadoc", MODE_PRIVATE).getString("currPatient", null);

        patient = Patient.fromJson(toBeAPatient);

        setTitle(patient.getName());
    }
    ...

Upvotes: 1

heLL0
heLL0

Reputation: 1425

try this:

Bundle extras = getIntent().getExtras();
ArrayList<String>hi= new ArrayList<String>();
hi = extras.getStringArrayList("patient");

Upvotes: 1

Related Questions