This is a correction to the code in Hour 2.
In Listing 2.12, we handle the result from a call to startActivityForResult().
The idea is that one Activity will handle data entered in a second Activity.
To show this, the code updates a TextView in the initial Activity. Unfortunately, when I transcribed the code for the book I left out the initialization of that TextView. The error is also in the code for download. There were great tech reviewer and editors on this book. This is my mistake and it will be corrected.
The required line that was dropped is:
t = (TextView) findViewById (R.id.textView1);
package com.bffmedia.hour2app; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class ActivityA extends Activity { TextView t; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_a_layout); Button b = (Button)findViewById(R.id.button1); t = (TextView) findViewById (R.id.textView1); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ActivityA.this, ActivityB.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); Bundle b = new Bundle(); b.putString("GREETING", "Hello"); intent.putExtra("BUNDLE", b); intent.putExtra("STRING", "World!"); intent.putExtra("BOOLEAN", true); intent.putExtra("INT", 5); startActivity(intent); } }); Button getData = (Button)findViewById(R.id.button2); getData.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ActivityA.this, ActivityC.class); startActivityForResult(intent, 0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data ) { if (requestCode == 0 && resultCode == Activity.RESULT_OK){ String enteredData = data.getStringExtra("Data"); t.setText(enteredData); } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_layout, menu); return true; } }
Advertisements
Listing 2.7, Line 10: “intnumItems” should be “int numItems”
There is another inconsistency in your posted correction:
activity_layout != activity_a_layout
setContentView(R.layout.activity_a_layout);
….
getMenuInflater().inflate(R.menu.activity_layout, menu);
The book doesn’t say to change the initial ‘activity_layout’ when ‘activity_c_layout’ is created.
I would suggest sticking with activity_layout.
Suggested Fix:
Line 17: (on pasted corrected code above) setContentView(R.layout.activity_layout);