如何用cursorloader读取一个SQLite数据库中的android?数据库中、如何用、SQLite、cursorloader

2023-09-04 23:48:03 作者:没有关系,我们只是朋友

我建立我的应用程序,使人们可以创建自己的朋友群。当创建一个组,将其写入2表的SQL数据库。第一个表有一个组名和组ID。第二个表有两列,一组ID和用户ID。这是工作的罚款。

不过,现在我希望能够从数据库中读取。我用一个ListView片段与 cursorloader ,但我遇到了麻烦来显示信息。我想列出从第一个表中的所有组名在我的列表视图中。

我的问题是,当我第一次使用了 cursorloader 来列举我的接触,我使用的是乌里 onCreateLoader 方法内容提供商。具体来说,我有 CONTENT_URI ContactsContracts.Contacts 类。

cursorloader 实例的ContentProvider

  @覆盖
公共装载机<光标> onCreateLoader(INT I,束束){
    乌里contentUri = ContactsContract.Contacts.CONTENT_URI;
    返回新CursorLoader(getActivity(),contentUri,投影,选择,ARGS,ORDER);
}
 

然而,如果不使用内容提供商,我不知道放在 onCreateLoader 的方法,因为返回什么新CursorLoader(... )要求乌里第二个参数。

我怎么可能能够显示在列表视图我的数据库中的数据?任何建议

片段类code:

 公共类GroupListFragment扩展ListFragment实现LoaderManager.LoaderCallbacks<光标> {

CursorAdapter的mAdapter;
私人OnItemSelectedListener监听;
私有静态最后的String []投影= {GroupContract.GroupDetails.COLUMN_NAME_GROUP_NAME};
私有静态最后的串选择= NULL;
最终的String [] FROM = {GroupContract.GroupDetails.COLUMN_NAME_GROUP_NAME};
最终诠释[] TO = {android.R.id.text1};
私有静态最后字串[] args = NULL;
私有静态最后弦乐ORDER = NULL;
私人光标C;


@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    mAdapter =新SimpleCursorAdapter(getActivity(),android.R.layout.simple_list_item_1,空,发件人,收件人,0);
    ReadDBAsync readDB =新ReadDBAsync();
    readDB.execute();
}

@覆盖
公共无效onActivityCreated(包savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    setListAdapter(mAdapter);
    getLoaderManager()initLoader(0,空,这一点)。
}

@覆盖
公共装载机<光标> onCreateLoader(INT I,束束){
    乌里contenturi = Uri.parse(内容://$p$pamble.oneapp);
    乌里tableuri = Uri.withAppendedPath(contenturi,GroupContract.GroupDetails.TABLE_NAME);
    返回新CursorLoader(getActivity(),tableuri,投影,选择,ARGS,ORDER);
}

@覆盖
公共无效onLoadFinished(装载机<光标> cursorLoader,光标光标){
    mAdapter.swapCursor(光标);
}

@覆盖
公共无效onLoaderReset(装载机<光标> cursorLoader){
    mAdapter.swapCursor(空);
}


私有类ReadDBAsync扩展的AsyncTask<虚空,虚空,字符串> {

    @覆盖
    保护字符串doInBackground(虚空......空隙){

        ContractDBHelpers mDBHelper =新ContractDBHelpers(getActivity());
        SQLiteDatabase DB = mDBHelper.getReadableDatabase();
        字符串返回值=数据库中读取;
        C = db.query(GroupContract.GroupDetails.TABLE_NAME,投影,NULL,NULL,NULL,NULL,NULL);
        返回返回值;
    }

    @覆盖
    保护无效onPostExecute(字符串结果){
        Toast.makeText(getActivity(),结果,Toast.LENGTH_LONG).show();
    }
}

}
 

解决方案 在Android程序中使用已有的SQLite数据库

这些是步骤来创建一个列表片段cursorloader

1)创建一个类扩展 SQLiteOpenHelper 并覆盖的onCreate onUpgrade 来创建表。

2)创建一个类扩展的ContentProvider 并创建URI来访问你的数据库。请参阅http://developer.android.com/guide/topics/providers/content-providers.html.添加您的URI的 URIMatcher 您在使用的onCreate 的onupdate ,查询等(覆盖方法)相匹配的URI。请参阅http://developer.android.com/reference/android/content/UriMatcher.html

3)在插入方法调用的getContext()。getContentResolver()。有NotifyChange(URI,空)。在查询方法调用 setNotificationUri(ContentResolver的CR,开放的URI)返回之前的内容提供商插入变化自动反映到你的装载机。 ( http://stackoverflow.com/a/7915117/936414 )。

4)给出的URI的 onCreateLoader

请注意: 如果没有一个内容提供者,改变列表的自动刷新并不像的当前机器人版本可行的。如果您不希望您的的ContentProvider可见,设置属性出口清单中为false。或者你也可以实现自定义的CursorLoader如 http://stackoverflow.com/a/7422343/936414 检索数据数据库。但在这种情况下,自动数据的清爽不可能

I'm setting up my app so that people can create groups of their friends. When a group is created, it writes 2 tables to the SQL database. The first table has a group name and a group id. The second table has 2 columns, a group id and a user id. This is working fine.

However, now I want to be able to read from the database. I'm using a listview fragment with a cursorloader but I'm having trouble getting the information to display. I want to list all the group names from the first table in my list view.

My problem is that, when I first used the cursorloader to list my contacts, I was using a Uri from the content provider in the onCreateLoader method. Specifically I had CONTENT_URI from the ContactsContracts.Contacts class.

Example of cursorloader with contentprovider:

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
    return new CursorLoader(getActivity(),contentUri,PROJECTION,SELECTION,ARGS,ORDER);
}

However, without using a content provider, I don't know what to put in the onCreateLoader method because return new CursorLoader(...) requires a Uri in the second argument.

Any suggestion on how I might be able to display my database data in a listview?

fragment class code:

public class GroupListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

CursorAdapter mAdapter;
private OnItemSelectedListener listener;
private static final String[] PROJECTION ={GroupContract.GroupDetails.COLUMN_NAME_GROUP_NAME};
private static final String SELECTION = null;
final String[] FROM = {GroupContract.GroupDetails.COLUMN_NAME_GROUP_NAME};
final int[] TO = {android.R.id.text1};
private static final String[] ARGS = null;
private static final String ORDER = null;
private Cursor c;


@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1,null,FROM,TO,0 );
    ReadDBAsync readDB = new ReadDBAsync();
    readDB.execute();
}

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    setListAdapter(mAdapter);
    getLoaderManager().initLoader(0,null,this);
}

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    Uri contenturi = Uri.parse("content://preamble.oneapp");
    Uri tableuri = Uri.withAppendedPath(contenturi,GroupContract.GroupDetails.TABLE_NAME);
    return new CursorLoader(getActivity(),tableuri,PROJECTION,SELECTION,ARGS,ORDER);
}

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

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


private class ReadDBAsync extends AsyncTask<Void,Void,String> {

    @Override
    protected String doInBackground(Void... voids) {

        ContractDBHelpers mDBHelper = new ContractDBHelpers(getActivity());
        SQLiteDatabase db = mDBHelper.getReadableDatabase();
        String returnvalue = "database read";
        c = db.query(GroupContract.GroupDetails.TABLE_NAME,PROJECTION,null,null,null,null,null);
        return returnvalue;
    }

    @Override
    protected void onPostExecute(String result){
        Toast.makeText(getActivity(), result, Toast.LENGTH_LONG).show();
    }
}

}

解决方案

These are the steps to create a cursorloader in a list fragment

1) Create a class extending SQLiteOpenHelper and override onCreate and onUpgrade to create your tables.

2) Create a class extending ContentProvider and create the URIs to access your database. Refer http://developer.android.com/guide/topics/providers/content-providers.html. Add your URIs to the URIMatcher which you use in onCreate, onUpdate, query, etc (overridden methods) to match the URI. Refer http://developer.android.com/reference/android/content/UriMatcher.html

3) In the insert method call getContext().getContentResolver().notifyChange(uri, null). In the query method call setNotificationUri(ContentResolver cr, Uri uri) before returning the content provider for the insertion change to reflect automatically to your loader. (http://stackoverflow.com/a/7915117/936414).

4) Give that URI in onCreateLoader.

Note: Without a content provider, automatic refreshing of changes to the list is not feasible as of the current android version. If you don't want to have your contentprovider visible, set exported attribute in manifest to false. Or you can implement your custom CursorLoader as in http://stackoverflow.com/a/7422343/936414 to retrieve data from the database. But in this case automatic refreshing of data is not possible