메모등록
MemoWriteActivity

package com.tis.mymemoapp;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MemoWriteActivity extends AppCompatActivity {

    ImageView imgBanner;
    Button btWrite,btList;
    EditText txtName,txtMsg;
    DBHandler dbHandler;
    String tag="MyLog";

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memo_write_acitity);

        btWrite = (Button)findViewById(R.id.btnAdd);
        btList = (Button)findViewById(R.id.btnList);
        txtName = (EditText)findViewById(R.id.editName);
        txtMsg = (EditText)findViewById(R.id.editMsg);

        MyHandler handler = new MyHandler();
        btWrite.setOnClickListener(handler);
        btList.setOnClickListener(handler);

        dbHandler = DBHandler.getDBHandler(this);
        Log.i(tag,"dbHandler===="+dbHandler);



        imgBanner = (ImageView)findViewById(R.id.imgBanner);
        imgBanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MemoWriteActivity.this, "쇼핑몰로 이동", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MemoWriteActivity.this,MyShopActivity.class);
                startActivity(intent);
            }
        });
    }//onCreate()-----------

    class MyHandler implements View.OnClickListener{
        Intent intent = new Intent(MemoWriteActivity.this,MemoListActivity.class);
        //누를때마다 생성하지 않기위해 위로 올렸다.
        @Override
        public void onClick(View v){
            if(v==btWrite){//작성자, 메모내용 받아오기
                String name = txtName.getText().toString();
                String msg = txtMsg.getText().toString();
                long id = dbHandler.insert(name,msg);
                Toast.makeText(MemoWriteActivity.this,id+"번글 생성",Toast.LENGTH_SHORT).show();
                txtName.setText("");
                txtMsg.setText("");
                txtName.requestFocus();
            }else if(v==btList){
                Toast.makeText(MemoWriteActivity.this,"목록보러 갑니다.",Toast.LENGTH_SHORT).show();
                startActivity(intent);
            }
        }
    }


}

List보여주기(Adapter)
//(Model) Adapter = > 데이터를 갖는다.
//View Adapter를 연결
//2.Adapter에 데이터 넘기기
//3.View Adapter연결하기


list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="@drawable/main_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_weight="0"
        android:textSize="20sp"
        android:layout_margin="3dp"
        android:textColor="@color/colorPrimaryDark"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="::한줄 메모장 목록::"></TextView>

    <ListView
        android:id="@+id/listView"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></ListView>

    <Button
        android:id="@+id/goWriteBtn"
        android:text="메모 글쓰기"
        android:background="#ccaabb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></Button>

</LinearLayout>

MemoListActivity.java

package com.tis.mymemoapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MemoListActivity extends AppCompatActivity {

    Button goWriteBtn;
    ListView listView;
    DBHandler dbHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        goWriteBtn = (Button)findViewById(R.id.goWriteBtn);
        listView = (ListView)findViewById(R.id.listView);//View

        //(Model) Adapter = > 데이터를 갖는다.
        //View와 Adapter를 연결
        //1.데이터를 자료구조에 담기

//        List<String> arr=new ArrayList<>();
//        arr.add("안녕");
//        arr.add("반갑습니다.");
        dbHandler = DBHandler.getDBHandler(this);
        List<String> arr = dbHandler.listAll();
        //2.Adapter에 데이터 넘기기
        ArrayAdapter<String> adapter = new ArrayAdapter<>(MemoListActivity.this,
                android.R.layout.simple_list_item_single_choice,arr);
        //3.View와 Adapter연결하기
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        //listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //다중선택이 가능함



        goWriteBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //뒤로 가기 Intent를 이용하면 스택에 하나가 더 쌓이는 것이다.
                //따라서 뒤로가기를 사용
                onBackPressed();
            }
        });

    }
}

SQLite이용
C:\Users\chanqun\AppData\Local\Android\Sdk\platform-tools 을 시스템 변수에 추가.

C:\Users\chanqun>adb shell
generic_x86:/ $ su
generic_x86:/ # ls
generic_x86:/ # cd data
generic_x86:/data # cd data
generic_x86:/data/data # cd com.tis.mymemoapp
generic_x86:/data/data/com.tis.mymemoapp # pwd
/data/data/com.tis.mymemoapp
generic_x86:/data/data/com.tis.mymemoapp # mkdir databases

generic_x86:/data/data/com.tis.mymemoapp/databases # sqlite3 sample.db
SQLite version 3.18.2 2017-07-21 07:56:09
Enter ".help" for usage hints.
sqlite> create table memo(idx integer primary key autoincrement,
   ...> name varchar(30) not null,
   ...> msg text not null,
   ...> wdate date);
sqlite> insert into memo(name,msg,wdate) values('Tom','Hello','2020-10-05');
sqlite> select * from memo;
1|Tom|Hello|2020-10-05   

MyDBHelper

package com.tis.mymemoapp;

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

public class MyDBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME="/data/data/com.tis.mymemoapp/database/sample2.db";
    private static final int DB_VERSION=1;
    public MyDBHelper(Context ctx){
        super(ctx,DB_NAME,null,DB_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //테이블을 새로 생성함
        String sql="create table if not exists memo(idx integer primary key autoincrement, name varchar2(20) not null," +
                "msg text not null, wdate date)";
        db.execSQL(sql);
        Log.i("MyLog","memo테이블 생성됨");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        Log.i("MyLog","onUpgrade()호출 old:"+i+", new:"+i1);
        //DB가 업그레이드되면 자동으로 호출되는 서비스
        //기존 테이블을 ㅇrop하고 새로 생성한 뒤 새로운 데이터를 insert 하는 것
        String sql="drop table if exists memo";
        db.execSQL(sql);

        this.onCreate(db);//테이블을 다시 생성
        //새로운 데이터 삽입
        sql = "insert into memo(name,msg,wdate) values('test','Hello Test','2020-10-05')";
        db.execSQL(sql);

    }
}

DBHandler
insert,select,delete,update기능 

package com.tis.mymemoapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DBHandler {
    private Context ctx;
    private MyDBHelper dbHelper;
    private SQLiteDatabase db;
    private final static String TABLE_NAME="memo";

    private DBHandler(Context ctx){
        this.ctx=ctx;
        dbHelper = new MyDBHelper(this.ctx);
        db=dbHelper.getWritableDatabase();//DATABASE얻어오기
    }

    public static DBHandler getDBHandler(Context ctx){
        return new DBHandler(ctx);
    }

    public void close(){
        dbHelper.close();
    }
    //한줄 메모글을 등록하는 메소드
    public long insert(String name, String msg){
        ContentValues values = new ContentValues();
        values.put("name",name);
        values.put("msg",msg);
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        values.put("wdate",sdf.format(d));
        long id = db.insert(TABLE_NAME,null,values);
        //insert문을 알아서 작성한다.
        return id;
    }
    public List<String> listAll(){
        Log.i("MyLog","listAll()");
        String [] cols = {"idx","msg","name","wdate"};
        Cursor cr = db.query(TABLE_NAME,cols,null,null,null,null,"idx desc");
        List<String> arr = new ArrayList<>();
        while(cr.moveToNext()){
            int idx = cr.getInt(0);
            String msg = cr.getString(1);
            String name = cr.getString(2);
            String wdate = cr.getString(3);
            String row = idx+": "+msg+"["+name+"]\n"+wdate;
            arr.add(row);
            Log.i("MyLog",row);
        }
        return arr;
    }

    public int delete(String idx){
        int n = db.delete(TABLE_NAME,"idx=?",new String[]{String.valueOf(idx)});
        return n;
    }

    public String selectMemoByIdx(String idx){
        String [] cols = {"idx","msg","name","wdate"};
        Cursor cr = db.query(TABLE_NAME,cols,"idx=?",new String[]{idx},null,null,null);
        List<String> arr = new ArrayList<>();
        while(cr.moveToNext()){
            int idx2 = cr.getInt(0);
            String msg = cr.getString(1);
            String name = cr.getString(2);
            String wdate = cr.getString(3);
            String row = idx2+": "+msg+"["+name+"]\n"+wdate;
            arr.add(row);
            Log.i("MyLog",row);
        }
        if(arr.size()==1){
            return arr.get(0);
        }else{
            return "데이터가 없습니다.";
        }
    }

    public int update(String idx, String name,String msg){
        //수정할 값들을 ContentValue에 저장한다.
        ContentValues values = new ContentValues();
        values.put("name",name);
        values.put("msg",msg);
        int n = db.update(TABLE_NAME,values,"idx=?",new String[]{idx});
        return n;
    }

}

정상적으로 들어가는 것을 확인할 수 있다.

+ Recent posts