0

请告诉我我是否正确使用 String [] FROM 来映射光标。

当我在 MainActivity 的 oncreate 方法中使用 SimpleCursorAdapter 时,出现错误

方法 SimpleCursorAdapter(MainActivity, int, Cursor, String[], int[]) 对于 MainActivity 类型未定义

我已经检查了 api docs 中的构造函数,我根据它正确使用它

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>
4

1 回答 1

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);
于 2013-03-22T07:07:04.147 回答