티스토리 뷰
SQLite 란?
1. 개발시 간략한 DB 필요할 경우가 있음. SQLite을 사용하여 간략한 DB 생성하여 사용 가능
2. 서버를 타지 않고 단말기 내에서만 처리되어야 하는 데이터의 경우 SQLite사용
SQLite 사용
1. DBHelper 클래스 생성 -> SQLiteOpenHelper 상속
2.DBHelper 클래스는 새로운 테이블 생성하고 데이터 삽입,삭제 하는 등 전반적으로 SQLite를 관리
3. onCreate, onUpgrade함수 필수적 추가
예) 데이터 추가하여 보여주기, 채팅같은것들
SQLite Example )
1 2 | Step 1: Create a New Project and Name it SQLiteOperations. Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code: | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.sqliteoperations.MainActivity" android:background="@android:color/holo_blue_dark"> <TextView android:text="@string/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="12dp" android:id="@+id/textView" android:textSize="18sp" android:textStyle="bold|italic" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:gravity="center" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/editName" android:textStyle="bold|italic" android:layout_below="@+id/textView" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:hint="Enter Name" android:gravity="center_vertical|center" /> <TextView android:text="@string/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="13dp" android:id="@+id/textView2" android:textStyle="bold|italic" android:textSize="18sp" android:layout_below="@+id/editName" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:gravity="center" android:hint="Enter Password" /> <Button android:text="@string/view_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2" android:textSize="18sp" android:onClick="viewdata" android:textStyle="bold|italic" android:layout_alignBaseline="@+id/button" android:layout_alignBottom="@+id/button" android:layout_alignRight="@+id/button4" android:layout_alignEnd="@+id/button4" /> <Button android:text="@string/add_user" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button" android:textStyle="bold|italic" android:textSize="18sp" android:onClick="addUser" android:layout_marginLeft="28dp" android:layout_marginStart="28dp" android:layout_below="@+id/editPass" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="23dp" /> <Button android:text="@string/update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3" android:onClick="update" android:textStyle="normal|bold" android:layout_below="@+id/editText3" android:layout_alignLeft="@+id/button4" android:layout_alignStart="@+id/button4" android:layout_marginTop="13dp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/editText6" android:layout_alignTop="@+id/button4" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:freezesText="false" android:hint="Enter Name to Delete Data" android:layout_toLeftOf="@+id/button2" android:layout_toStartOf="@+id/button2" /> <Button android:text="@string/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="21dp" android:layout_marginEnd="21dp" android:id="@+id/button4" android:onClick="delete" android:textStyle="normal|bold" tools:ignore="RelativeOverlap" android:layout_marginBottom="41dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:layout_marginTop="47dp" android:id="@+id/editText3" android:textStyle="bold|italic" android:textSize="14sp" android:layout_below="@+id/button" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="7dp" android:layout_marginStart="7dp" android:hint="Current Name" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:layout_marginTop="11dp" android:id="@+id/editPass" android:hint="Enter Password" android:gravity="center_vertical|center" android:textSize="18sp" android:layout_below="@+id/textView2" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textAllCaps="false" android:textStyle="normal|bold" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/editText5" android:textStyle="bold|italic" android:textSize="14sp" android:hint="New Name" android:layout_alignTop="@+id/button3" android:layout_alignLeft="@+id/editText3" android:layout_alignStart="@+id/editText3" android:layout_marginTop="32dp" /> </RelativeLayout> | cs |
1 | Step 3 : Now open app -> java -> package -> MainActivity.java and add the below code. | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | package com.example.sqliteoperations; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText Name, Pass , updateold, updatenew, delete; myDbAdapter helper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Name= (EditText) findViewById(R.id.editName); Pass= (EditText) findViewById(R.id.editPass); updateold= (EditText) findViewById(R.id.editText3); updatenew= (EditText) findViewById(R.id.editText5); delete = (EditText) findViewById(R.id.editText6); helper = new myDbAdapter(this); } public void addUser(View view) { String t1 = Name.getText().toString(); String t2 = Pass.getText().toString(); if(t1.isEmpty() || t2.isEmpty()) { Message.message(getApplicationContext(),"Enter Both Name and Password"); } else { long id = helper.insertData(t1,t2); if(id<=0) { Message.message(getApplicationContext(),"Insertion Unsuccessful"); Name.setText(""); Pass.setText(""); } else { Message.message(getApplicationContext(),"Insertion Successful"); Name.setText(""); Pass.setText(""); } } } public void viewdata(View view) { String data = helper.getData(); Message.message(this,data); } public void update( View view) { String u1 = updateold.getText().toString(); String u2 = updatenew.getText().toString(); if(u1.isEmpty() || u2.isEmpty()) { Message.message(getApplicationContext(),"Enter Data"); } else { int a= helper.updateName( u1, u2); if(a<=0) { Message.message(getApplicationContext(),"Unsuccessful"); updateold.setText(""); updatenew.setText(""); } else { Message.message(getApplicationContext(),"Updated"); updateold.setText(""); updatenew.setText(""); } } } public void delete( View view) { String uname = delete.getText().toString(); if(uname.isEmpty()) { Message.message(getApplicationContext(),"Enter Data"); } else{ int a= helper.delete(uname); if(a<=0) { Message.message(getApplicationContext(),"Unsuccessful"); delete.setText(""); } else { Message.message(this, "DELETED"); delete.setText(""); } } } } | cs |
1 | Step 4: In this step create a java class myDbAdapter. java. | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | package com.example.sqliteoperations; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class myDbAdapter { myDbHelper myhelper; public myDbAdapter(Context context) { myhelper = new myDbHelper(context); } public long insertData(String name, String pass) { SQLiteDatabase dbb = myhelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(myDbHelper.NAME, name); contentValues.put(myDbHelper.MyPASSWORD, pass); long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues); return id; } public String getData() { SQLiteDatabase db = myhelper.getWritableDatabase(); String[] columns = {myDbHelper.UID,myDbHelper.NAME,myDbHelper.MyPASSWORD}; Cursor cursor =db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null); StringBuffer buffer= new StringBuffer(); while (cursor.moveToNext()) { int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID)); String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME)); String password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD)); buffer.append(cid+ " " + name + " " + password +" \n"); } return buffer.toString(); } public int delete(String uname) { SQLiteDatabase db = myhelper.getWritableDatabase(); String[] whereArgs ={uname}; int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+" = ?",whereArgs); return count; } public int updateName(String oldName , String newName) { SQLiteDatabase db = myhelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(myDbHelper.NAME,newName); String[] whereArgs= {oldName}; int count =db.update(myDbHelper.TABLE_NAME,contentValues, myDbHelper.NAME+" = ?",whereArgs ); return count; } static class myDbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "myDatabase"; // Database Name private static final String TABLE_NAME = "myTable"; // Table Name private static final int DATABASE_Version = 1;. // Database Version private static final String UID="_id"; // Column I (Primary Key) private static final String NAME = "Name"; //Column II private static final String MyPASSWORD= "Password"; // Column III private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+ " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));"; private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME; private Context context; public myDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_Version); this.context=context; } public void onCreate(SQLiteDatabase db) { try { db.execSQL(CREATE_TABLE); } catch (Exception e) { Message.message(context,""+e); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { try { Message.message(context,"OnUpgrade"); db.execSQL(DROP_TABLE); onCreate(db); }catch (Exception e) { Message.message(context,""+e); } } } } | cs |
1 | Step 5: In this step create another java class Message.class | cs |
1 2 3 4 5 6 7 8 9 10 | package com.example.sqliteoperations; import android.content.Context; import android.widget.Toast; public class Message { public static void message(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } } | cs |
최종 결과
reference : https://abhiandroid.com/database/sqlite
'Android' 카테고리의 다른 글
[안드로이드] 카카오톡(Kakaotalk) 로그인 연동하기 (3) | 2018.08.01 |
---|---|
[안드로이드] AAR 라이브러리 파일 열기(내용확인하기) (0) | 2018.08.01 |
[Android] 액션바를 탭과 함께 보여 주기 예제 (0) | 2017.09.25 |
[Android]액션바와 탭 사용하기 (0) | 2017.09.25 |
[Android] Viewer 만들기(뷰어만들기) (0) | 2017.09.24 |
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 노드
- BFS
- 머신러닝
- node.js
- db
- 코드엔진
- 스프링
- 리버싱
- 학교
- 프로그래밍
- 초보자를 위한 C언어 300제
- 감자코딩
- C langauge
- 개발하는 관광이
- 백준
- programming
- 감자개발자
- Android
- C언어
- TensorFlow
- Algorigm
- Spring
- 백준알고리즘
- node
- 알고리즘
- 복습
- MVC
- 안드로이드
- Controller
- 텐서플로우
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
글 보관함