본문 바로가기

Android

주소록만들기(버튼,옵션메뉴)

메인 화면

옵션메뉴에서 정렬 기능

데이터 입력할 수있음 취소누르면 메인화면으로 돌아감

앱설계:

주소록 만들기(입력,취소 버튼)
옵션메뉴(이름,번호,주소 정렬)

java>AddressDB

package com.example.ex05;

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

import androidx.annotation.Nullable;

public class AddressDB extends SQLiteOpenHelper {
    //Address
    public AddressDB(@Nullable Context context) {
        super(context, "address.db",null,1);
    }
    //DB가 만들어질때 TABLE 생성
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table tbladd(_id integer primary key autoincrement,name text,address text,tel text);");
        db.execSQL("insert into tbladd(name,address,tel) values('가','다구','010-1111-1111');");
        db.execSQL("insert into tbladd(name,address,tel) values('나','나구','010-0000-0000');");
        db.execSQL("insert into tbladd(name,address,tel) values('다','가구','010-1111-1111');");
    }

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

    }
}

 

java>AddressVO

package com.example.ex05;

import java.lang.reflect.Constructor;

public class AddressVO {
    private String name;
    private String address;
    private String tel;

    //마우스 우클릭 Generate>Getters and Setters
    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }
    //Constructor=생성자:마우스 우클릭 Generate>Constructor
}

java>InsertActivity.java

package com.example.ex05;
import androidx.appcompat.app.AppCompatActivity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class InsertActivity extends AppCompatActivity {
    AddressDB helper;
    SQLiteDatabase db;
    EditText edtname,edtaddress,edttel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert);
        edtname=findViewById(R.id.edtname);
        edtaddress=findViewById(R.id.edtaddress);
        edttel=findViewById(R.id.edttel);
        helper=new AddressDB(this);
        db=helper.getWritableDatabase();
    }

    public void mClick(View v){
        switch (v.getId()){
            case R.id.btnsave:
                String strname=edtname.getText().toString();
                String straddress=edtaddress.getText().toString();
                String strtel=edttel.getText().toString();
                String sql="insert into tbladd(name,tel,address) values(";
                sql += "'"+strname+"',";
                sql += "'"+strtel+"',";
                sql += "'"+straddress+"')";
                db.execSQL(sql);
                Toast.makeText(InsertActivity.this,"저장됐어",
                Toast.LENGTH_SHORT).show();
                finish();
                break;
            case R.id.btncancel:
                //닫고 메인으로 돌아가기
                finish();
                break;
        }
    }


}

 

java>MainActivity.java

package com.example.ex05;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    AddressDB helper;
    SQLiteDatabase db;
    CursorAdapter adapter;
    //SimpleCursorAdapter adapter;
    ListView list;
    Cursor cursor;

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

        helper = new AddressDB(this);
        db = helper.getReadableDatabase();
        //data를 select 해서 cursor에 넣기
        cursor = db.rawQuery("select * from tbladd order by name", null);
        /*adapter=new SimpleCursorAdapter(this,
                R.layout.item,cursor,
                new String[]{"name","address","tel"},
                new int[]{R.id.txtname,R.id.txtaddress,
                R.id.txttel});

         */
        adapter = new MyAdapter(this, cursor);
        list = findViewById(R.id.list);
        list.setAdapter(adapter);

        Button btninsert = findViewById(R.id.btninsert);
        btninsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, InsertActivity.class);
                startActivity(intent);
            }
        });
    }

    //커서 어덥터
    public class MyAdapter extends CursorAdapter {
        public MyAdapter(Context context, Cursor c) {
            super(context, c);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return getLayoutInflater().inflate(R.layout.item, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView txtname = view.findViewById(R.id.txtname);
            txtname.setText(cursor.getString(1));
            TextView txtaddress = view.findViewById(R.id.txtaddress);
            txtaddress.setText(cursor.getString(2));
            TextView txttel = view.findViewById(R.id.txttel);
            txttel.setText(cursor.getString(3));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.itemname:
                cursor = db.rawQuery("select * from tbladd order by name", null);
                break;
            case R.id.itemaddress:
                cursor = db.rawQuery("select * from tbladd order by address", null);
                break;
            case R.id.itemtel:
                cursor = db.rawQuery("select * from tbladd order by tel", null);
                break;
        }
        adapter.changeCursor(cursor);
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onRestart() {
        cursor = db.rawQuery("select * from tbladd order by name", null);
        adapter.changeCursor(cursor);
        super.onRestart();
    }


    }



 

res>layout>activity_insert.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"
    tools:context=".InsertActivity"
    android:orientation="vertical"
    android:padding="10sp">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="주소록"
    android:textSize="30sp"
    android:layout_gravity="center"/>
    <EditText
        android:id="@+id/edtname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="이름 입력"
        android:textSize="30sp"/>
    <EditText
        android:id="@+id/edtaddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="주소 입력"
        android:textSize="30sp"/>
    <EditText
        android:id="@+id/edttel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="전화번호 입력"
        android:textSize="30sp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btnsave"
            android:layout_width="0px"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="저장"
            android:textSize="20sp"
            android:onClick="mClick"/>
        <Button
            android:id="@+id/btncancel"
            android:layout_width="0px"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="취소"
            android:textSize="20sp"
            android:onClick="mClick"/>
    </LinearLayout>
</LinearLayout>

 

res>layout>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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="10sp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="주소록"
        android:textSize="30sp"
        android:layout_gravity="center"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btninsert"
        android:text="주소등록"/>
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

res>layout>item.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:background="#658057"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtname"
        android:text="장희빈"
        android:textSize="30sp"
        android:textColor="#033B68"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtaddress"
        android:text="서울 종각 경희궁"
        android:textSize="30sp"
        android:textColor="#033B68"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txttel"
        android:text="010-1500-0812"
        android:textSize="30sp"
        android:textColor="#033B68"/>
</LinearLayout>

 

res>menu>menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/itemname"
        android:title="이름으로 정렬하기"/>
    <item
        android:id="@+id/itemtel"
        android:title="전화번호로 정렬하기"/>
    <item
        android:id="@+id/itemaddress"
        android:title="주소로 정렬하기"/>
</menu>