package activity.cyq.contentprovidertenderer;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class MyContentProvider extends ContentProvider {
public static final Uri URI=Uri.parse("content://cyq.activity.MyContentProvider");
private SQLiteDatabase database;
@Override
public boolean onCreate() {
database = getContext().openOrCreateDatabase("ContentProvider", Context.MODE_PRIVATE, null);
database.execSQL("Create Table contacts( _id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT DEFAULT NONE , cellPhotoNumber TEXT DEFAULT NONE) ");
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor = database.query("contacts", null, null, null, null, null, null);
return cursor;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
database.insert("contacts", "_id", values);
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
package activity.cyq.contentprovidertenderer;
import android.content.ContentValues;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText usernameEdit;
private EditText cellPhotoNumberEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameEdit = (EditText) findViewById(R.id.username);
cellPhotoNumberEdit = (EditText) findViewById(R.id.cellPhotoNumber);
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("username", usernameEdit.getText().toString());
values.put("cellPhotoNumber", cellPhotoNumberEdit.getText().toString());
getContentResolver().insert(MyContentProvider.URI, values);
Toast.makeText(MainActivity.this, "数据库创建成功", Toast.LENGTH_SHORT).show();
}
});
}
}