小女照着书敲的代码~可是运行不了~求大牛解释~package com.example.chapter4_uiimport android.app.ListA
小女照着书敲的代码~可是运行不了~求大牛解释~
package com.example.chapter4_ui;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
public class SimpleCursorAdapters extends ListActivity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//获得通讯录联系人游标对象Cursor
Cursor c=getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(c);
//实例化列表适配器
ListAdapter adapter=new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
c,
new String[] {People.NAME},
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
}
[解决办法]
在manifest文件添加权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
[解决办法]
代码问题很多...需要继续努力啊
1、onCreate中不宜做阻塞的数据查询
2、数据查询应该是异步的
3、联系人数据查询没必要查询所有数据,根据需求,看你下文只需要一个name,那么查询语句应该是
Cursor c=getContentResolver().query(People.CONTENT_URI, new String[]{People.NAME}, null, null, null);
[解决办法]
四个问题
1. 没有加载layout
ListActivity需要一个id为@android:list 的 ListView
所以需要新建一个布局文件如下:(以文件名为activity_main.xml为例)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
然后在super.onCreate(savedInstanceState);下加上
setContentView(R.layout.activity_main); //参数改为自己布局文件的ID
2. 2.x版本安卓通讯录数据库的结构比例子中的复杂
例子中的android.provider.Contacts.People 类已经不存在了
所以获得通讯录联系人Cursor的语句改为
Cursor c=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
实例化列表适配器的语句改为
ListAdapter adapter=new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
c,
new String[] {ContactsContract.Contacts.DISPLAY_NAME_PRIMARY},
new int[] {android.R.id.text1});
解决如上两个问题已经可以看见联系人了 但是还有问题
3. Cursor对象没有释放 要在重载的onDestory()中调用
c.close();方法
4.
startManagingCursor(Cursor c)方法 和
SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)构造函数 都是被弃用的
如4楼所说 因为这两个方法都是是阻塞的 需要用 CursorLoader进行异步的查询 否则将会导致UI的无响应 甚至ANR错误
