[英]NullPointerException when passing data from a non-activity class to an activity (via intent)
我正在嘗試從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)
如果有人可以告訴我我要去哪里錯了,將不勝感激。
這樣通過意圖傳遞數據
Intent i = new Intent(getApplicationContext(), VCardActivity.class);
i.putExtra("URI",uri.toString());
startActivity(i);
並像這樣獲取數據
Bundle extras = getIntent().getExtras();
if (extras != null) {
uri = extras.getString("URI");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.