티스토리 뷰
1. DatabaseHelper 클래스를 만듭니다.
2. DatabaseHelper 클래스 코딩하기
package com.example.sqlite_sample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db"; // 1. 데이터베이스 네임
public static final String TABLE_NAME = "students"; //2. 테이블 네임
// 3. 테이블 항목 네임
public static final String COL_1 = "ID";
public static final String COL_2 = "Name";
public static final String COL_3 = "Surname";
public static final String COL_4 = "Marks";
public DatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
// 데이터 추가하기
public boolean insertData(String name, String surname, String marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME, null,contentValues);
if(result == -1)
return false;
else
return true;
}
// 데이터 보여주기(읽어오기)
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME, null);
return res;
}
//데이터 수정하기(업데이트)
public boolean updateDatat(String id, String name, String surname, String marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
db.update(TABLE_NAME,contentValues,"ID = ?",new String[] { id });
return true;
}
// 데이터 삭제하기
public Integer deleteData(String id){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,"ID = ?",new String[] {id});
}
}
2. 레이아웃 XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="7dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<EditText
android:id="@+id/editText_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="14dp"
android:layout_marginTop="19dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Surname"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_name"
tools:ignore="MissingConstraints" />
<EditText
android:id="@+id/editText_marks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="19dp"
android:layout_marginTop="29dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Marks"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_surname"
tools:ignore="MissingConstraints" />
<Button
android:id="@+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="52dp"
android:layout_marginTop="36dp"
android:text="ADD"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_id" />
<Button
android:id="@+id/button_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="52dp"
android:layout_marginTop="24dp"
android:text="Update"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button_add" />
<Button
android:id="@+id/button_viewall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="52dp"
android:layout_marginTop="36dp"
android:text="View"
app:layout_constraintStart_toEndOf="@+id/button_add"
app:layout_constraintTop_toBottomOf="@+id/editText_id" />
<EditText
android:id="@+id/editText_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="ID"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_marks" />
<Button
android:id="@+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="44dp"
android:layout_marginTop="22dp"
android:text="Delete"
app:layout_constraintStart_toEndOf="@+id/button_update"
app:layout_constraintTop_toBottomOf="@+id/button_viewall" />
</androidx.constraintlayout.widget.ConstraintLayout>
3. MainActivity.java 코딩하기
package com.example.sqlite_sample;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName, editSurname, editMarks, editID;
Button btnAddData, btnviewall, btnUpdate, btnDelete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editName = findViewById(R.id.editText_name);
editSurname = findViewById(R.id.editText_surname);
editMarks = findViewById(R.id.editText_marks);
editID = findViewById(R.id.editText_id);
btnAddData = findViewById(R.id.button_add);
btnviewall = findViewById(R.id.button_viewall);
btnUpdate= findViewById(R.id.button_update);
btnDelete = findViewById(R.id.button_delete);
AddData(); // 데이터 추가하기
viewAll(); // 데이터 보여주기
UpdateData(); // 데이터 업데이트(수정)
DeleteData(); // 데이터 삭제하기
}
// 데이터베이스에 추가하기
public void AddData() {
btnAddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString(),
editSurname.getText().toString(),
editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
});
}
//데이터베이스 보여주기
public void viewAll()
{
btnviewall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//show message
showMessage("에러","데이터를 찾을수 없다.");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("id : "+ res.getString(0) + "\n");
buffer.append("name : "+ res.getString(1) + "\n");
buffer.append("surname : "+ res.getString(2) + "\n");
buffer.append("marks : "+ res.getString(3) + "\n\n");
}
// Show all data
showMessage("데이터",buffer.toString());
}
});
}
public void UpdateData(){
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdated = myDb.updateDatat(editID.getText().toString(),editName.getText().toString(),editSurname.getText().toString(),editMarks.getText().toString());
if(isUpdated == true)
Toast.makeText(MainActivity.this,"Data Updated",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
}
});
}
public void DeleteData(){
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer deleteRows = myDb.deleteData(editID.getText().toString());
if(deleteRows > 0 )
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Deleted",Toast.LENGTH_LONG).show();
}
});
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
2021.04.08 - [프로그래밍/안드로이드 앱프로그래밍] - 안드로이드 sqlite 추가하기 insert 소스코드
'프로그래밍 > 안드로이드 앱프로그래밍' 카테고리의 다른 글
안드로이드 전면광고 google admob version 20.1.0 (0) | 2021.06.19 |
---|---|
버튼 눌렀을때 메시지가 나타나게 하기 (0) | 2021.06.17 |
안드로이드 SQLite 업데이트(수정하기) (0) | 2021.04.08 |
안드로이드 sqlite 추가하고 보여주기 (0) | 2021.04.08 |
안드로이드 sqlite 추가하기 insert 소스코드 (0) | 2021.04.08 |
댓글