我嘗試從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一起,並解析該數據並顯示它。我還沒有整理出來的數據格式化和解析的是,簡單地使用日誌作爲一個佔位符:
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)
如果有人能告訴我,我要去哪裏錯了,會非常感激。這樣
Intent i = new Intent(getApplicationContext(), VCardActivity.class);
i.putExtra("URI",uri.toString());
startActivity(i);
通過意向
得到的數據可能是URI有一個空值。 –
我已經在StaffListListener上直接測試了uri,它工作正常。問題在於調用VCardActivity,或者uri如何通過intent。 – misaochan
通過意圖傳遞uri.toString() –