什么是弃用的“managedQuery”的适当替换者?

时间:2014-09-30 12:22:42

标签: android android-contentprovider

Android文档说:此方法在API级别11中已弃用。

这是代码:

class GridViewActivity_ extends     Activity
  {
    @Override
    protected void onCreate(Bundle  savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.gridview);

    GridView gv = (GridView)findViewById(R.id.gridview);

    Cursor c = managedQuery(Contacts.CONTENT_URI, 
            null, null, null, Contacts.DISPLAY_NAME);

    String[] cols = new String[]{Contacts.DISPLAY_NAME};
    int[]   views = new int[]   {android.R.id.text1};

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_1,
            c, cols, views);
    gv.setAdapter(adapter);
}
 }

如何替换此代码,而不是弃用代码?

对于活动,不是片段......

2 个答案:

答案 0 :(得分:19)

您可以看到此链接:Deprecated ManagedQuery() issue

Cursor cursor = getContentResolver().query(contentUri, null, null, null, Contacts.DISPLAY_NAME);

答案 1 :(得分:3)

根据这个伟大的tutorial

public class GridViewActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>
{
    private SimpleCursorAdapter mAdapter;

    @Override
public Loader<Cursor> onCreateLoader(int p1, Bundle p2)
{
    return new CursorLoader(this, Contacts.CONTENT_URI, null, null, null, Contacts.DISPLAY_NAME);
}

@Override
public void onLoadFinished(Loader<Cursor> p1, Cursor cursor)
{
    mAdapter.swapCursor(cursor);
}

@Override
public void onLoaderReset(Loader<Cursor> cursor)
{
    mAdapter.swapCursor(null);
}


@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO: Implement this method
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gridview);      
    GridView gv = (GridView)findViewById(R.id.gridview);
    String[] cols = new String[]{Contacts.DISPLAY_NAME};
    int[] views = new int[]{android.R.id.text1};
    mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, cols,views, 0);
    gv.setAdapter(mAdapter);
    getSupportLoaderManager().initLoader(0, null, this);
}

}