[챕터 2-10-2] 프로바이더
2020. 2. 19. 20:44ㆍAndroid/Android 챕터 2-10
반응형
결과화면
INSERT 후 QUERY
UPDATE 후 QUERY
DELETE 후 QUERY
결과
프로젝트명 : MyProvider
하위 리니어레이아웃
- 레이아웃 높이 : wrap_content
MainActivity.java
더보기
package org.minokuma.myprovider;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
public void println(String data){
textView.append(data + "\n");
}
}
파일명 : DatabaseHelper
슈퍼클래스 : android.database.sqlite.SQLiteOpenHelper
DatabaseHelper.java
더보기
package org.minokuma.myprovider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
DatabaseHelper.java
더보기
package org.minokuma.myprovider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "person.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "person";
public static final String PERSON_ID = "_id";
public static final String PERSON_NAME = "name";
public static final String PERSON_AGE = "age";
public static final String PERSON_MOBILE = "mobile";
public static final String[] ALL_COLUMNS = {PERSON_ID, PERSON_NAME, PERSON_AGE, PERSON_MOBILE};
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "("+
PERSON_ID + " integer primary key autoIncrement, " +
PERSON_NAME + " text, " +
PERSON_AGE + " integer, " +
PERSON_MOBILE + " text " +
")";
public DatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_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);
}
}
파일명 : PersonProvier
슈퍼클래스 : android.content.ContentProvider
더보기
package org.minokuma.myprovider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class PersonProvier extends ContentProvider {
public static final String AUTHORITY = "org.minokuma.myprovider";
public static final String BASE_PATH = "person";
public static final Uri CONTENT_URL = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
private static final int PERSONS = 1;
private static final int PERSON_ID = 2;
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, BASE_PATH, PERSONS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", PERSON_ID);
}
private SQLiteDatabase sqLiteDatabase;
@Override
public boolean onCreate() {
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
sqLiteDatabase = databaseHelper.getWritableDatabase();
return true;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
switch (uriMatcher.match(uri)){
case PERSONS:
return "vnd.android.cursor.dir/persons";
default:
throw new IllegalArgumentException("알 수 없는 URI : " + uri);
}
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
long id = sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME, null, values);
if(id > 0){
Uri _url = ContentUris.withAppendedId(CONTENT_URL, id);
getContext().getContentResolver().notifyChange(_url, null);
return _url;
}
throw new SQLException("추가 실패 => URL : " + uri);
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
Cursor cursor;
int count = 0;
switch (uriMatcher.match(uri)) {
case PERSONS:
cursor = sqLiteDatabase.query(DatabaseHelper.TABLE_NAME, DatabaseHelper.ALL_COLUMNS, selection, selectionArgs, null, null, DatabaseHelper.PERSON_NAME + " ASC");
break;
default:
throw new IllegalArgumentException("알 수 없는 URI : " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case PERSONS:
count = sqLiteDatabase.update(DatabaseHelper.TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("알 수 없는 URI : " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case PERSONS:
count = sqLiteDatabase.delete(DatabaseHelper.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("알 수 없는 URI : " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
DatabaseHelper.java
더보기
package org.minokuma.myprovider;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insertPerson();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
queryPerson();
}
});
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updatePerson();
}
});
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deletePerson();
}
});
}
public void insertPerson(){
println("insertPerson()");
String uriStr = "content://org.minokuma.myprovider/person";
Uri uri = new Uri.Builder().build().parse(uriStr);
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
String[] columns = cursor.getColumnNames();
for(int i = 0; i < columns.length; i++){
println("#" + i + " : " + columns[i]);
}
ContentValues contentValues = new ContentValues();
contentValues.put("name","MINOKUMA");
contentValues.put("age", 30);
contentValues.put("mobile", "010-1000-1000");
uri = getContentResolver().insert(uri, contentValues);
println("insert 결과 : " + uri.toString());
}
public void queryPerson(){
try{
String urlStr = "content://org.minokuma.myprovider/person";
Uri uri = new Uri.Builder().build().parse(urlStr);
String[] columns = new String[] {"name", "age", "mobile"};
Cursor cursor = getContentResolver().query(uri, columns, null, null, "name ASC");
println("query 결과 : " + cursor.getCount());
int index = 0;
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(columns[0]));
int age = cursor.getInt(cursor.getColumnIndex(columns[1]));
String mobile = cursor.getString(cursor.getColumnIndex(columns[2]));
println("#" + index + " => " + name + ", " + age + ", " + mobile);
index += 1;
}
}catch (Exception e){
e.printStackTrace();
}
}
public void updatePerson(){
String urlStr = "content://org.minokuma.myprovider/person";
Uri uri = new Uri.Builder().build().parse(urlStr);
String selection = "mobile = ?";
String[] selectionArgs = new String[] {"010-1000-1000"};
ContentValues updateValues = new ContentValues();
updateValues.put("mobile", "010-2000-2000");
int count = getContentResolver().update(uri, updateValues, selection, selectionArgs);
println("update 결과 : " + count);
}
public void deletePerson(){
String urlStr = "content://org.minokuma.myprovider/person";
Uri uri = new Uri.Builder().build().parse(urlStr);
String selection = "name = ?";
String[] selectionArgs = new String[] {"MINOKUMA"};
int count = getContentResolver().delete(uri, selection, selectionArgs);
println("delete 결과 : " + count);
}
public void println(String data){
textView.append(data + "\n");
}
}
AndroidManifest.xml
더보기
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.minokuma.myprovider">
<permission android:name="org.minokuma.myprovider.READ_DATABASE" android:protectionLevel="normal" />
<permission android:name="org.minokuma.myprovider.WRITE_DATABASE" android:protectionLevel="normal" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:authorities="org.minokuma.myprovider"
android:name=".PersonProvier"
android:exported="true"
android:readPermission="org.minokuma.provider.READ_DATABASE"
android:writePermission="org.minokuma.provider.WRITE_DATABASE" />
</application>
</manifest>
반응형
'Android > Android 챕터 2-10' 카테고리의 다른 글
[챕터 2-10-4] 연락처 프로필 정보 조회 (0) | 2020.02.19 |
---|---|
[챕터 2-10-3] 앨범 (0) | 2020.02.19 |
[챕터 2-10-1] SQLite 데이터베이스 (0) | 2020.02.19 |