안녕하세요. 누누입니다.
연습 삼아 만들어본 sqlite를 이용한 리스트뷰와 소소한 기능들입니다.
우선 스핀킷의 오픈 라이브러리 주소입니다.
https://github.com/ybq/Android-SpinKit
ybq/Android-SpinKit
Android loading animations. Contribute to ybq/Android-SpinKit development by creating an account on GitHub.
github.com
토글 버튼을 사용하여 타이머가 작동하는 상황을 시각적으로 표현하기 위해 만들었습니다.
MainActivity.class 입니다.
public class MainActivity extends AppCompatActivity {
Context mContext = null;
ArrayList spinnerArray = new ArrayList<>();
ArrayList listArray = new ArrayList<>();
ArrayList<Element> element = new ArrayList<Element>();
Spinner spinner;
EditText name,age;
TextView result;
Handler mHandler;
SpinKitView spin_kit;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DBHelper dbHelper = new DBHelper(getApplicationContext(),"Board.db",null,1);
final ArrayAdapter listAdapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,listArray);
final ListView listview = (ListView)findViewById(R.id.listview);
final ToggleButton toggleButton = (ToggleButton)findViewById(R.id.toggleButton);
mContext = this;
spinner = (Spinner)findViewById(R.id.gender);
name = (EditText) findViewById(R.id.name) ;
age = (EditText) findViewById(R.id.age) ;
result=(TextView)findViewById(R.id.result);
spin_kit = (SpinKitView)findViewById(R.id.spin_kit);
spin_kit.setVisibility(View.INVISIBLE);
//스피너 리스트 목록
spinnerArray.add("남자");
spinnerArray.add("여자");
//초기 EditText 데이터 넣기
if(element.size()==0){
dbHelper.insert("누누",27,"남자");
}
show(listAdapter,dbHelper,listview);
name.setText(element.get(0).getName());
age.setText(String.valueOf(element.get(0).getAge()));
if(element.get(0).getGender().equals("남자") ){
spinner.setSelection(0);
}else{
spinner.setSelection(1);
}
//토글버튼 리스너
toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(toggleButton.isChecked()){
mHandler = new Handler(){
public void handleMessage(Message msg){
spin_kit.setVisibility(View.VISIBLE);
if(count<element.size()){
name.setText(element.get(count).getName());
age.setText(String.valueOf(element.get(count).getAge()));
if(element.get(count).getGender().equals("남자") ){
spinner.setSelection(0);
}else{
spinner.setSelection(1);
}
count++;
mHandler.sendEmptyMessageDelayed(0,5000);
Log.d("count : ", String.valueOf(count) + "|" + element.size());
}
else{
count=0;
handleMessage(msg);
}
}
};
mHandler.sendEmptyMessage(0);
}else{
spin_kit.setVisibility(View.INVISIBLE);
mHandler.removeMessages(0);
name.setText(element.get(0).getName());
age.setText(String.valueOf(element.get(0).getAge()));
if(element.get(0).getGender().equals("남자") ){
spinner.setSelection(0);
}else{
spinner.setSelection(1);
}
}
}
});
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,spinnerArray);
spinner.setAdapter(arrayAdapter);
//전송버튼 클릭 리스너
findViewById(R.id.submit).setOnClickListener(new Button.OnClickListener(){
public void onClick(View view){
String names = name.getText().toString();
int ages = Integer.parseInt(age.getText().toString());
String genders = spinner.getSelectedItem().toString();
dbHelper.insert(names,ages,genders);
show(listAdapter,dbHelper,listview);
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setTitle(element.get(position).getName() + " | "+element.get(position).getAge() + " | "+element.get(position).getGender() + "\n");
dialogBuilder.setPositiveButton("지우기", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dbHelper.delete(element.get(position).getNum());
show(listAdapter,dbHelper,listview);
}
});
dialogBuilder.setNegativeButton("선택하기", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
name.setText(element.get(position).getName());
age.setText(String.valueOf(element.get(position).getAge()));
if(element.get(position).getGender().equals("남자") ){
spinner.setSelection(0);
}else{
spinner.setSelection(1);
}
}
});
dialogBuilder.show();
}
});
}
//셀렉트 보드 함수
//뷰 변경사항 확인
private void show(ArrayAdapter listAdapter,DBHelper dbHelper,ListView listview){
listAdapter.clear();
element.clear();
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Board ORDER BY num DESC",null);
if(cursor !=null){
cursor.move(0);
while(cursor.moveToNext()){
int num = Integer.parseInt(cursor.getString(cursor.getColumnIndex("num")));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = Integer.parseInt(cursor.getString(cursor.getColumnIndex("age")));
String gender = cursor.getString(cursor.getColumnIndex("gender"));
//객체에 DB내용 담기
element.add(new Element(num,name,age,gender));
}
listview.setAdapter(listAdapter);
for(Element element : element){
listAdapter.add(element.getNum() +" | " +element.getName()+ " | " +element.getAge()+ " | " +element.getGender()+"\n");
}
listAdapter.notifyDataSetChanged();
}
}
}
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">
<LinearLayout
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textOn="5초마다 바뀜"
android:textOff="맨위에것만 바뀜"
/>
</LinearLayout>
<!--Spin Kit-->
<com.github.ybq.android.spinkit.SpinKitView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/spin_kit"
style="@style/SpinKitView.Large.Circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:SpinKit_Color="@color/colorAccent" />
<LinearLayout
android:orientation="vertical"
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="이름 : "
/>
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="이름"
/>
</LinearLayout>
<LinearLayout
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="나이 : "
/>
<EditText
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="나이"
/>
</LinearLayout>
<LinearLayout
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="성별 : "
/>
<Spinner
android:id="@+id/gender"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</Spinner>
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/submit"
android:text="전송하기"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.dodola.listview.extlib.ListViewExt
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.dodola.listview.extlib.ListViewExt>
</LinearLayout>
</LinearLayout>
</LinearLayout>
DB 객체 Element 입니다.
public class Element implements Serializable {
private int num;
private String name;
private int age;
private String gender;
public Element(int num,String name,int age,String gender){
super();
this.num =num;
this.name = name;
this.age = age;
this. gender = gender;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Element{" +
"num=" + num +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
마지막으로 DBHelper입니다.
public class DBHelper extends SQLiteOpenHelper {
// DBHelper 생성자로 관리할 DB 이름과 버전 정보를 받음
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
// DB를 새로 생성할 때 호출되는 함수
@Override
public void onCreate(SQLiteDatabase db) {
// 새로운 테이블 생성
/* 이름은 BOARD이고, 자동으로 값이 증가하는 num 정수형 기본키 컬럼과
name 문자열 컬럼, age 정수형 컬럼, gender 문자열 컬럼으로 구성된 테이블을 생성. */
db.execSQL("CREATE TABLE BOARD (num INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, gender TEXT);");
}
// DB 업그레이드를 위해 버전이 변경될 때 호출되는 함수
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String name ,int age, String gender) {
// 읽고 쓰기가 가능하게 DB 열기
SQLiteDatabase db = getWritableDatabase();
// DB에 입력한 값으로 행 추가
db.execSQL("INSERT INTO BOARD VALUES(null, '" + name + "', " + age + ", '" + gender + "');");
db.close();
}
public void update(String name, int age) {
SQLiteDatabase db = getWritableDatabase();
// 입력한 항목과 일치하는 행의 가격 정보 수정
db.execSQL("UPDATE BOARD SET age=" + age + " WHERE name='" + name + "';");
db.close();
}
public void delete(int num){
SQLiteDatabase db = getWritableDatabase();
// 입력한 항목과 일치하는 행의 가격 정보 수정
db.execSQL("DELETE FROM BOARD WHERE num=" + num );
db.close();
}
public String getResult() {
// 읽기가 가능하게 DB 열기
SQLiteDatabase db = getReadableDatabase();
String result = "";
// DB에 있는 데이터를 쉽게 처리하기 위해 Cursor를 사용하여 테이블에 있는 모든 데이터 출력
Cursor cursor = db.rawQuery("SELECT * FROM BOARD", null);
while (cursor.moveToNext()) {
result += cursor.getString(cursor.getColumnIndex("num"))
+ " | "
+ cursor.getString(cursor.getColumnIndex("name"))
+ " | "
+ cursor.getString(cursor.getColumnIndex("age"))
+ " | "
+ cursor.getString(cursor.getColumnIndex("gender"))
+ "\n";
/* result += cursor.getString(0)
+ " | "
+ cursor.getString(1)
+ " | "
+ cursor.getInt(2)
+ " | "
+ cursor.getString(3)
+ "\n";*/
}
cursor.close();
return result;
}
}
build gradle에
dependencies {
implementation 'com.dodola:listviewext:1.0'
implementation 'com.github.ybq:Android-SpinKit:1.2.0'
}
추가도 잊지 마세요!
실행화면과 설명입니다.
코드를 올리면서 생각해 봤는데... 토글이 동작하는중에는 전송버튼을 막아두는게 현명해 보입니다.
코드를 이것저것 수정하면서 만든 거라 중복된 내용의 코드가 있을 수 있습니다. 발견 시 댓글 달아주시면 감사하겠습니다 ㅠ.