我正在尝试从 OnClickListener 调用另一个活动,但遇到了 NullPointerException。我使用https://stackoverflow.com/a/7325248/1291619提供的建议将数据传递给其他活动。
此类旨在侦听列表并在单击项目时使用选定的 uri 启动 VCardActivity.java。它与意图一起发送 uri:
public class StaffListListener implements OnItemClickListener {
ArrayList<String> items;
Activity activity;
public StaffListListener(ArrayList<String> items, Activity activity) {
this.items = items;
this.activity = activity;
}
/**
* Send user to view with contact details
*/
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//items.get(pos) returns the UPI needed. Append to http://www.cs.auckland.ac.nz/our_staff/vcard.php?upi=
Uri.Builder b = Uri.parse("http://www.cs.auckland.ac.nz/our_staff/vcard.php").buildUpon();
b.appendQueryParameter("upi", items.get(pos));
Uri uri = b.build();
Log.d("URL of staff", uri.toString());
Intent i = new Intent(activity.getApplicationContext(), VCardActivity.class);
i.putExtra("URI",uri);
activity.startActivity(i);
}
}
此类旨在接收意图以及 uri,并解析数据并显示它。我还没有整理好数据的格式化和解析,只是用Log作为占位符:
public class VCardActivity extends ListActivity {
private VCardActivity local;
private String uri;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vcard);
local = this;
Bundle extras = getIntent().getExtras();
if (extras != null) {
uri = extras.getString("URI");
}
try {
URL url = new URL(uri.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = urlConnection.getInputStream();
StringBuffer fileContent = new StringBuffer("");
int ch;
while( (ch = stream.read()) != -1){
fileContent.append((char)ch);
}
String data = new String(fileContent);
Log.i("TAG", "data: " + data);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
我的例外:
06-01 10:06:13.293: E/AndroidRuntime(903): FATAL EXCEPTION: main
06-01 10:06:13.293: E/AndroidRuntime(903): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lim.assignment/com.lim.json.VCardActivity}: java.lang.NullPointerException
06-01 10:06:13.293: E/AndroidRuntime(903): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
如果有人能告诉我哪里出错了,将不胜感激。