1. 程式人生 > >四大元件之一contentprovider的使用

四大元件之一contentprovider的使用

//例項化XML
setContentView(R.layout.contenprovder_layout);

//例項化空間
mInsertBtn = (Button) findViewById(R.id.insertbtn);
mSelectBtn = (Button) findViewById(R.id.selectbtn);
mDeleteBtn = (Button) findViewById(R.id.deletebtn);
mUpdateBtn = (Button) findViewById(R.id.updatebtn);


mInsertBtn.setOnClickListener(this);
mSelectBtn.setOnClickListener(this);
mDeleteBtn.setOnClickListener(this);
mUpdateBtn.setOnClickListener(this);


}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.insertbtn:
ContentValues values = new ContentValues(); // 裝載插入資料
values.put(DataColumn.User.USER_NAME, "contentProvider學習");
values.put(DataColumn.User.PASSWORD, "abcde");

getContentResolver().insert(Mycontenprovder.URI_CONTENT, values);

break;
case R.id.updatebtn:
ContentValues contentValues = new ContentValues(); // 裝載資料
contentValues.put(DataColumn.User.PASSWORD, "12345");
contentValues.put(DataColumn.User.USER_NAME, "資料儲存Provider");

String whereClause = DataColumn.User.PASSWORD + "=?";
String[] whereArgs = new String[] { "abcd" };

getContentResolver().update(Mycontenprovder.URI_CONTENT, contentValues, whereClause, whereArgs);

break;
case R.id.deletebtn:
String where = DataColumn.User.PASSWORD + "=?";
String[] selectionArgs = new String[] { "abcd" };

getContentResolver().delete(Mycontenprovder.URI_CONTENT, where, selectionArgs);

break;
case R.id.selectbtn:
Cursor cursor = getContentResolver().query(Mycontenprovder.URI_CONTENT, null, null, null, null);

if(cursor.moveToFirst()){
int count = cursor.getCount();
for(int i = 0 ; i < count; i++){
String userName = cursor.getString(cursor.getColumnIndex(DataColumn.User.USER_NAME));
String passWord = cursor.getString(cursor.getColumnIndex(DataColumn.User.PASSWORD));

//Logs.v("userName :"+userName+ " passWord :"+passWord);

cursor.moveToNext();
}
cursor.close();
}

break;
}
}
}