5.2实验中列表中姓名来自通过 ContentResolver 读取实验 5.1 应用程序中所实现的 ContentProvider。用代码怎么实现
时间: 2024-03-20 18:38:58 浏览: 63
好的,那我来回答你的问题:
首先,我们需要在5.1实验中实现一个ContentProvider用于提供数据。这个ContentProvider应该至少包含一个表,可以使用SQLiteOpenHelper来创建和管理这个表。在这个表中,我们需要存储姓名和其他有关信息。下面是一个简单的例子:
```java
public class MyContentProvider extends ContentProvider {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_NAME_ID = "_id";
private static final String COLUMN_NAME_NAME = "name";
private static final String COLUMN_NAME_INFO = "info";
private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_NAME + " TEXT," +
COLUMN_NAME_INFO + " TEXT)";
private SQLiteDatabase db;
@Override
public boolean onCreate() {
MyDatabaseHelper helper = new MyDatabaseHelper(getContext(), DATABASE_NAME, null, DATABASE_VERSION);
db = helper.getWritableDatabase();
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long id = db.insert(TABLE_NAME, null, values);
return ContentUris.withAppendedId(uri, id);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return db.delete(TABLE_NAME, selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return db.update(TABLE_NAME, values, selection, selectionArgs);
}
private static class MyDatabaseHelper extends SQLiteOpenHelper {
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
```
接下来,在5.2实验中,我们需要使用ContentResolver来读取这个ContentProvider提供的数据。假设我们要显示一个列表,其中包含所有的姓名,我们可以这样做:
```java
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.mycontentprovider/mytable"), new String[]{"_id", "name"}, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"}, new int[]{android.R.id.text1});
listView.setAdapter(adapter);
}
}
```
这样就可以从ContentProvider中读取所有的姓名,并显示在一个列表中了。
阅读全文