将数据从非活动类传递到活动时的NullPointerException(通过intent)

时间:2013-06-01 10:20:19

标签: android

我试图从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)

如果有人能告诉我哪里出错了,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

通过这样的意图传递数据

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");
        }