SimpleCursorAdapter无法在MainActivity中使用

时间:2013-03-22 07:04:17

标签: android listview

请告诉我我正确使用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>

1 个答案:

答案 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);