본문 바로가기

Android

주소록 만들기

recyclerview 라이브러리 임포트

Gradel Scripts>dependencies>implementation 'androidx.recyclerview:recyclerview:1.0.0'
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btnadd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:srcCompat="@drawable/ic_library_add"
        android:backgroundTint="#9C536D"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20sp"
        android:layout_marginRight="20sp"/>

</RelativeLayout>


item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10sp"
    android:background="#1D571E"
    android:layout_margin="10sp"
    android:id="@+id/item">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFEB3B"
        android:text="이름출력"
        android:textSize="20sp"
        android:id="@+id/txtname"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#71F71E"
        android:text="이곳에는 주소가 출력됩니다...."
        android:textSize="15sp"
        android:layout_below="@id/txtname"
        android:id="@+id/txtadd"/>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_delete"
        android:layout_alignParentRight="true"
        android:id="@+id/btndel"/>
</RelativeLayout>


AddDB.java

package com.example.ex13;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class AddDB  extends SQLiteOpenHelper {
    public AddDB(@Nullable Context context) {
        super(context, "juso.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table juso(id integer primary key autoincrement,name text,address text)");
        db.execSQL("insert into juso(name,address) values('김경민','시카고')");
        db.execSQL("insert into juso(name,address) values('홍경민','북한')");
        db.execSQL("insert into juso(name,address) values('나경민','LA')");
        db.execSQL("insert into juso(name,address) values('오경민','독일')");
        db.execSQL("insert into juso(name,address) values('남궁경민','러시아')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


AddAdapter.java

package com.example.ex13;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class AddAdapter extends RecyclerView.Adapter<AddAdapter.ViewHolder> {
    //생성자를 만들기 위해서
    //데이터를 저장할 공간
    ArrayList<AddVO> array;

    //어디 actuvuty에서 호출했는지
    Context context;



    public AddAdapter(ArrayList<AddVO> array, Context context) {
        this.array = array;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //view 생성
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final int id=array.get(position).getId();
        //final=값이 변하지 못하게함
        holder.txtname.setText(array.get(position).getName());
        holder.txtadd.setText(array.get(position).getAdd());
        holder.item.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                LinearLayout view=(LinearLayout)LayoutInflater.from(context).inflate(R.layout.input,null);
                final EditText edtname=view.findViewById(R.id.edtname);
                final EditText edtadd=view.findViewById(R.id.edtadd);
                edtname.setText(array.get(position).getName());
                edtadd.setText(array.get(position).getAdd());

                AlertDialog.Builder box=new AlertDialog.Builder(context);
                box.setTitle("주소수정" + id);
                box.setView(view);
                box.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AddDB helper=new AddDB(context);
                        SQLiteDatabase db=helper.getWritableDatabase();
                        String sql="update juso set name='" + edtname.getText().toString() + "'";
                        sql += ", address='" + edtadd.getText().toString() + "'";
                        sql += " where id=" +id;
                        db.execSQL(sql);

                        array.remove(position);
                        AddVO vo=new AddVO();
                        vo.setId(id);
                        vo.setName(edtname.getText().toString());
                        vo.setAdd(edtadd.getText().toString());
                        array.add(position,vo);
                        notifyDataSetChanged();

                    }
                });
                box.setNegativeButton("닫기",null);
                box.show();
                return false;
            }
        });
        holder.btndel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder  box=new AlertDialog.Builder(context);
                box.setMessage(id + "를(을)삭제하시겠습니까?");
                box.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AddDB helper=new AddDB(context);
                        SQLiteDatabase db=helper.getWritableDatabase();
                        String sql="delete from juso where id=" +id;
                        db.execSQL(sql);

                        array.remove(position);
                        notifyDataSetChanged();
                    }
                });
                box.setNegativeButton("닫기",null);
                box.show();

            }
        });
    }

    @Override
    public int getItemCount() {
        return array.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtname,txtadd;
        ImageView btndel;
        RelativeLayout item;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtname=itemView.findViewById(R.id.txtname);
            txtadd=itemView.findViewById(R.id.txtadd);
            btndel=itemView.findViewById(R.id.btndel);
            item=itemView.findViewById(R.id.item);
        }
    }
}


AddVO.java

package com.example.ex13;

public class AddVO {
    private int id;
    private String name;
    private String add;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAdd() {
        return add;
    }

    public void setAdd(String add) {
        this.add = add;
    }
}


MainActivity.java

package com.example.ex13;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SearchView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    AddDB helper;
    SQLiteDatabase db;

    //데이터 결과를 넣기 위해
    Cursor cursor;

    AddAdapter adapter;
    ArrayList<AddVO> array;

    RecyclerView list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle("주소록");

        //context는 activity
        helper=new AddDB(this);
        db=helper.getReadableDatabase();
        cursor=db.rawQuery("select * from juso" ,null);

        array=new ArrayList<AddVO>();

        while(cursor.moveToNext()){
            AddVO vo=new AddVO();
            vo.setId(cursor.getInt(0));
            vo.setName(cursor.getString(1));
            vo.setAdd(cursor.getString(2));
            array.add(vo);

        }
        list=findViewById(R.id.list);
        LinearLayoutManager manager=new LinearLayoutManager(this);
        list.setLayoutManager(manager);


        adapter=new AddAdapter(array,this);
        list.setAdapter(adapter);

        FloatingActionButton btnadd=findViewById(R.id.btnadd);
        btnadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final LinearLayout view=(LinearLayout)getLayoutInflater().inflate(R.layout.input,null);
                AlertDialog.Builder box=new AlertDialog.Builder(MainActivity.this);
                box.setTitle("주소등록");
                box.setView(view);
                box.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EditText edtname=view.findViewById(R.id.edtname);
                        EditText edtadd=view.findViewById(R.id.edtadd);
                        String strname=edtname.getText().toString();
                        String stradd=edtadd.getText().toString();

                        //데이터베이스에  추가
                        String sql="insert into juso(name,address) values(";
                        sql += "'" + strname + "',";
                        sql += "'" + stradd + "')";
                        db.execSQL(sql);

                        //화면에 추가
                        AddVO vo=new AddVO();
                        vo.setName(strname);
                        vo.setAdd(stradd);
                        array.add(vo);
                        //어덥터 Refresh
                        adapter.notifyDataSetChanged();

                    }
                });
                box.setNegativeButton("닫기",null);
                box.show();
            }
        });

    }
    //옵션메뉴등록
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem search=menu.findItem(R.id.search);

        SearchView searchView=(SearchView)search.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String str) {
                cursor=db.rawQuery("select * from juso where name like '%" + str + "%' or address like '%" + str + "%'",null);
                array.clear();
                while (cursor.moveToNext()){
                    AddVO vo=new AddVO();
                    vo.setId(cursor.getInt(0));
                    vo.setName(cursor.getString(1));
                    vo.setAdd(cursor.getString(2));
                    array.add(vo);
                }
                adapter.notifyDataSetChanged();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.itemname:
                cursor=db.rawQuery("select * from juso order by name",null);
                break;
            case R.id.itemadd:
                cursor=db.rawQuery("select * from juso order by address",null);
                break;
        }
        array.clear();
        while (cursor.moveToNext()){
            AddVO vo=new AddVO();
            vo.setId(cursor.getInt(0));
            vo.setName(cursor.getString(1));
            vo.setAdd(cursor.getString(2));
            array.add(vo);
        }
        adapter.notifyDataSetChanged();
        return super.onOptionsItemSelected(item);
    }
}


input.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10sp">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="이름입력"
        android:textSize="20sp"
        android:id="@+id/edtname"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="주소입력"
        android:textSize="20sp"
        android:id="@+id/edtadd"/>
</LinearLayout>


menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/itemname"
        android:title="이름 정렬"/>
    <item
        android:id="@+id/itemadd"
        android:title="주소 정렬"/>
    <item
        android:id="@+id/search"
        android:title="검색"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.widget.SearchView"/>
</menu>