我是android的初学者。我想在ListView中显示联系人列表。我已经在activity_main.xml中有一个ListView,我在MainActivity.java中提到过这一点。但是当我运行程序时出现错误
java.lang.RuntimeException:无法启动活动 ComponentInfo {com.example.yuvi.contactsex / com.example.yuvi.contactsex.MainActivity}: java.lang.RuntimeException:您的内容必须具有其id为的ListView 属性是'android.R.id.list'
我从网站上获得了这段代码。我不知道在哪里更改代码。任何人帮助我。
的AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
activity_main.xml中
MainActivity.java
public class MainActivity extends ListActivity {
ListView lv;
Cursor cursor1;
@Override
public int getSelectedItemPosition() {
return super.getSelectedItemPosition();
}
@Override
public long getSelectedItemId() {
return super.getSelectedItemId();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.list);
// create a cursor to query the Contacts on the device to start populating a listview
cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor1);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID}; // get the list items for the listadapter could be TITLE or URI
int[] to = {android.R.id.text1, android.R.id.text2}; // sets the items from above string to listview
// new listadapter, created to use android checked template
SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor1, from, to);
setListAdapter(listadapter);
// adds listview so I can get data from it
lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
答案 0 :(得分:0)
java.lang.RuntimeException:您的内容必须具有其ID为其的ListView 属性是'android.R.id.list'
当您使用ListActivity
时,您必须在xml中的@android
属性中添加id
:
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
希望这有帮助。