ContentProvider without SQL

元气小坏坏 提交于 2019-12-09 16:22:20

问题


I have two pieces of data that need to be accessed from outside applications and stored. According to documentation ContentProviders are the only possible way, but it also mentions external storage. ContentProviders implement a database-like "interface" and using a database would be extremely unnecessary for two pieces of data. I would rather save them to a file, but using a ContentProvider by implementing the abstract methods is problematic because the methods are structured as database queries.

I know that there is nothing specifying that ContentProviders must use a database underneath to store data, but is there any other way to store minimal amount of data that has to be shared to the file system?


回答1:


I just used MatrixCursor to solve that exact problem. Take a look at it.

Edit: Sorry, I had just scanned the question when I answered it. ContentProvider is the only way for Applications to share data. Activities within an Application can use SharedPreferences for smaller data, with the addition of persistence.

Edit v2: Here's the function I used to populate a MatrixCursor for the query function of my ContentProvider. I am using a predefined VIEW I created that returns a set of distinct values, and this sets up a cursor with _ids that I can pass to my ExpandableListView.

private Cursor getFactions() {
        MatrixCursor mc = new MatrixCursor(Model.Faction.PROJECTION);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.query(MODELFACTION_TABLE_NAME, new String[] { Model.Faction.FACTION }, null, null, null, null, Model.Faction.FACTION + " ASC");
        c.moveToFirst();
        do {
            mc.addRow(new Object[] { c.getPosition(), c.getString(c.getColumnIndex(Model.Faction.FACTION))});               
        } while (c.moveToNext() && ! c.isAfterLast());
        c.close();
        db.close();
        return mc;
    }



回答2:


The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed)

Useful links:

http://developer.android.com/reference/android/content/SharedPreferences.html

http://developer.android.com/guide/topics/data/data-storage.html



来源:https://stackoverflow.com/questions/5600838/contentprovider-without-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!