在我为Android开发应用程序时遇到了LoaderManager的问题。每当我尝试使用以下代码时:
getLoaderManager().initLoader(0, null, this);
它告诉我,我不能使用它。这是我的代码的一部分:
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private CursorAdapter cursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insertNote("New Note");
String[] from = {DBComHelper.NOTE_TEXT};
int[] to = {android.R.id.text1};
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to, 0);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
getLoaderManager().initLoader(0, null, this);
}
以下是活动代码:
package com.berendhulshof.privatenotes;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private CursorAdapter cursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insertNote("New Note");
String[] from = {DBComHelper.NOTE_TEXT};
int[] to = {android.R.id.text1};
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to, 0);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
getLoaderManager().initLoader(0, null, this);
}
private void insertNote(String noteText) {
ContentValues values = new ContentValues();
values.put(DBComHelper.NOTE_TEXT, noteText);
Uri noteUri =
getContentResolver().insert(NotesProvider.CONTENT_URI, values);
Log.d("MainActivity", "Inserted note " + noteUri.getLastPathSegment());
}
@Override
public Loader onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, NotesProvider.CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader loader) {
cursorAdapter.swapCursor(null);
}
}
有人可以解释一下我在这里做错了吗?
答案 0 :(得分:0)
这可能是重复的,因为有些问题有这个答案,但大多数问题也没有使用正确的导入。但是我愿意。但答案有助于这个问题:Implementing LoaderCallbacks in Activity Android
我必须将getLoaderManager更改为getSupportloaderManager。
答案 1 :(得分:0)
getLoaderManager().initLoader(0, null, this);
这一行不适用,因为该行中的this
是一个活动,但此行中的initloader
方法接受LoaderCallbacks
接口,该接口必须单独实施。