如何从另一个数据库(简单光标加载器)更新列表?

时间:2016-03-20 13:04:24

标签: android database simplecursoradapter android-cursorloader

我是Android新手,遇到了问题:如何使用Simple Cursor Loader从其他数据库更新列表?

我有这段代码:

public class ListViewFragmentActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {

private static final int CM_DELETE_ID = 1;

private ListView listViewData;
private Button mAddButton, mViewButtonProject, mViewButtonStaff;

private DatabaseHelper db;

private SimpleCursorAdapter scAdapter;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_view);

    final Context context = this;

    db = new ProjectDatabase(this);
    db.open();

    String[] from = new String[] { db.COLUMN_NAME, db.COLUMN_DESCRIPTION };
    int[] to = new int[] { R.id.textViewName, R.id.textViewDescription };

    scAdapter = new SimpleCursorAdapter(this, R.layout.list_view_item, null, from, to, 0);
    listViewData = (ListView) findViewById(R.id.listViewData);
    listViewData.setAdapter(scAdapter);        

    mViewButtonProject = (Button)findViewById(R.id.newView1);
    mViewButtonProject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            db = new ProjectDatabase(context);
            db.open();
        }
    });

    mViewButtonStaff= (Button)findViewById(R.id.newView2);
    mViewButtonStaff.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            db = new StaffDatabase(context);
            db.open();
        }
    });

    getSupportLoaderManager().initLoader(0, null, this);
}

protected void onDestroy() {
    super.onDestroy();
    db.close();
}

protected void onResume() {
    super.onResume();
    getSupportLoaderManager().getLoader(0).forceLoad();
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
    return new CustomCursorLoader(this, db);
}

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

@Override
public void onLoaderReset(Loader<Cursor> loader) {
}

static class CustomCursorLoader extends CursorLoader {

    DatabaseHelper db;

    public CustomCursorLoader(Context context, DatabaseHelper db) {
        super(context);
        this.db = db;
    }

    @Override
    public Cursor loadInBackground() {
        Cursor cursor = db.getAllData();
        return cursor;
    }

}

切换发生在按钮的基础之间,但是我做了,列表显示默认数据库。

0 个答案:

没有答案