如何在android中的listView中添加数据“给我异常”

时间:2011-11-19 15:35:30

标签: android listview

我使用contactPickerIntent来选择用户联系人 我想当pick用户在listView中添加用户时 代码给我异常

<Button
        android:id="@+id/button1"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:onClick="doLaunchContactPicker"
        android:text="Contact" />



    <ListView
        android:id="@+id/contactsList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.99" >
    </ListView>

和活动

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView = (ListView) findViewById(R.id.contactsList);
        setContentView(R.layout.main);
    }


    public void doLaunchContactPicker(View view) {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);


    }

    ArrayAdapter<String> adapter;
    ArrayList<String> dataArray = new ArrayList<String>();
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case CONTACT_PICKER_RESULT:
                // handle contact results
                Bundle extras = data.getExtras();
                Set<String> keys = extras.keySet();
                Iterator<String> iterate = keys.iterator();
                while (iterate.hasNext()) {
                    String key = iterate.next();
                    Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
                    System.out.println("-------------LinkedList--------------");
                    dataArray.add((String) extras.get(key));
                }
                Uri result = data.getData();
                Log.v(DEBUG_TAG, "Got a result: "+ result.toString());
                System.out.println(result.toString());


                System.out.println("--------ArrayAdapter-------------------");
                 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataArray);
                System.out.println("------------Last----------");
                listView.setAdapter(adapter);
                break;
            }

        } else {
            // gracefully handle failure
            Log.w(DEBUG_TAG, "Warning: activity result not ok");
        }
    }

这段代码给我的例外 为什么给我Exception以及将数据添加到listview的正确方法

1 个答案:

答案 0 :(得分:0)

以这种方式更改onCreate(Bundle)

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) findViewById(R.id.contactsList);
}

您应该在View方法之后找到setContentView(int)