1. 개요
AutoCompleteTextView와 sqlite 를 이용한 자동완성 표시
2. 설명
- "확인"을 클릭 할 때마다 sqlite에 키워드를 저장하여 자동완성기능을 사용함
3. 소스
3.1 MainActivity.java
package com.example.myautomaketextview;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
sqliteCTR sqlCTR;
EditText edtlst;
Button btnok, btndel;
private List<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sqlCTR = new sqliteCTR(this,1);
setContentView(R.layout.activity_main);
// 리스트 생선함.
list = new ArrayList<String>();
// DB에서 데이터 가져오기
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
settingList(autoCompleteTextView);
edtlst = findViewById(R.id.autoCompleteTextView2);
btnok = findViewById(R.id.btnok);
btnok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 검색 문자 입력
if ("" == edtlst.getText().toString()) return;
sqlCTR.insertData(edtlst.getText().toString());
// 목록 초기화 (변수에 가냥 값을 넣어도 좋지만 혹시나 하는 예외 가 있어 DB에 넣고 다시 읽어 옴.
settingList(autoCompleteTextView);
edtlst.setText("");
}
});
btndel = findViewById(R.id.btndel);
btndel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
delList(autoCompleteTextView);
}
});
}
private void settingList(AutoCompleteTextView autoCompleteTextView){
Cursor res = sqlCTR.getAllData();
if(res.getCount() ==0){
Toast.makeText(MainActivity.this, "데이터를 찾을수 없습니다.", Toast.LENGTH_LONG).show();
return;
}
list.clear();
while(res.moveToNext()){
list.add(res.getString(1));
}
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, list));
}
private void delList(AutoCompleteTextView autoCompleteTextView){
sqlCTR.deleteDateAll();
list.clear();
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, list));
}
}
3.2 Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btndel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="목록 초기화" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="78dp"
android:orientation="horizontal">
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView2"
android:layout_width="332dp"
android:layout_height="match_parent"
android:completionHint="검색어를 입력하세요."
android:completionThreshold="1"
android:contentDescription="검색어를 입력하세요." />
<Button
android:id="@+id/btnok"
android:layout_width="306dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="확인" />
</LinearLayout>
</LinearLayout>
3.3 SqliteCTR.java
package com.example.myautomaketextview;
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.NonNull;
import static java.sql.DriverManager.println;
public class sqliteCTR extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "lsitTest.db";
public static final String TABLE_NAME = "lsit_table";
// table column
public static final String guid = "id";
public static final String input1 = "input1";
// 생정자
public sqliteCTR(Context context, int version){
super(context, DATABASE_NAME,null,version);
}
// table 생성
@Override
public void onCreate(@NonNull SQLiteDatabase db) {
println("onCreate!!!");
String sql = "CREATE TABLE ";
sql += TABLE_NAME + "(guid INTEGER PRIMARY KEY AUTOINCREMENT, input1 TEXT)";
println(sql);
db.execSQL(sql);
}
// table 삭제 후 재생성,
@Override
public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion){
println("onUpgrade!!!");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
// insert
public boolean insertData(String input1prm){
println("insertData!!!");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(input1, input1prm);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result==-1)
return false;
else
return true;
}
// select
public Cursor getAllData(){
println("getAllData!!!");
SQLiteDatabase db = this.getWritableDatabase();
String sql = "Select * From " + TABLE_NAME;
Cursor res = db.rawQuery(sql, null);
return res;
}
// update
public boolean updateData(String input0prm, String input1prm){
println("udpateData!!!");
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(input1,input1prm);
int rs = db.update(TABLE_NAME, contentValues, "guid=?", new String[]{input0prm});
if (rs >0)
return true;
else
return false;
}
// delete
public int deleteDate(String id){
println("deleteDate!!!");
SQLiteDatabase db=this.getWritableDatabase();
return db.delete(TABLE_NAME,"guid=?", new String[]{id});
}
// all delete
public int deleteDateAll(){
println("deleteDate all!!!");
SQLiteDatabase db=this.getWritableDatabase();
return db.delete(TABLE_NAME,"",new String[]{});
}
}
반응형
'IT > 안드로이드' 카테고리의 다른 글
(Android)안드로이드 RecyclerView.scrollToPosition() 설명 (0) | 2023.02.24 |
---|---|
(Android) 버튼 아래 고정하고 RecyclerView 화면 체우기 (0) | 2023.02.22 |
sqlite 가상머신 DB 파일 확인 (0) | 2023.02.15 |
sqlite 사용(CRUD) (0) | 2023.02.15 |
자동 import 사용기 (0) | 2023.02.13 |