请告诉我我正确使用String [] FROM来映射光标。
当我在MainActivity的oncreate方法中使用SimpleCursorAdapter时,它给出了错误
方法SimpleCursorAdapter(MainActivity,int,Cursor,String [],int [])未定义类型MainActivity
我已经检查了api文档中的构造函数,根据我正确使用它
public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)**
这是我的MainActivity.java:
package com.example.listview;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
private ListView list;
private Cursor cursor;
private SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
list = (ListView) findViewById(R.layout.listview);
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
String [] FROM = {cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)), cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))};
int [] TO = {android.R.id.text1, android.R.id.text2};
adapter = SimpleCursorAdapter(MainActivity.this, android.R.layout.two_line_list_item,cursor,FROM,TO);
list.setAdapter(adapter);
}
}
这是我的布局listview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
答案 0 :(得分:3)
将SimpleCursorAdapter
对象创建为:
adapter =new SimpleCursorAdapter(MainActivity.this,
^^^ android.R.layout.two_line_list_item,cursor,FROM,TO);
您忘记使用new
创建SimpleCursorAdapter
并使用ListView ID初始化list
而不是R.layout.listview
list= (ListView) findViewById(R.id.listview);