SMALL


안도르이드 스튜디오는 OS안에서 DB와 TABLE 을 핸들링 할 수 있습니다 그래서 간단한 쿼리문으로 응용해서 예제를 작성해보도록 할텐데요 자바클래스와 xml이 너무 많은 관계로 주석으로 대체 설명이 되어있으니 참고하시고 읽어주세요 첫 순서는 DB생성과 TABLE 생성과 검색기능이 있고 그 다음 로그인화면으로 이동을 하는 버튼이 있습니다 그 이후에 로그인을 하게되면 게시판형식의 listView가 뜨고 거기에 글을 쓰거나 읽을 수 있는 기능을 구현해봤습니다

activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.ntsysmac01.sampledatabase.MainActivity">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout">
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="customer.db"
            android:id="@+id/editText"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DB 생성"
            android:id="@+id/button" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout"
        android:id="@+id/linearLayout2">
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="employee"
            android:id="@+id/editText2"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Table 생성"
            android:id="@+id/button2" />
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="상태 : "
        android:id="@+id/textView"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="95dp"
        android:layout_alignParentBottom="true" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginBottom="52dp"
        android:weightSum="1">
        <EditText
            android:layout_width="204dp"
            android:layout_height="wrap_content"
            android:id="@+id/editText3"
            android:layout_weight="1.25" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="검색하기"
            android:id="@+id/button3" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로그인하기"
        android:id="@+id/button4"
        android:layout_marginTop="46dp"
        android:layout_below="@+id/linearLayout2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>
cs

MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package com.example.ntsysmac01.sampledatabase;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
    SQLiteDatabase db;
    //db를 커넥션 해주기 위해 필요한 메소드
    MySQLiteOpenHelper helper;
    String databaseName;
    String tableName;
    String searchName;
    Button button;
    EditText editText;
    Button button2;
    EditText editText2;
    Button button3;
    EditText editText3;
    Button button4;
    TextView textView;
    boolean databaseCreated = false;
    boolean tableCreated = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //첫번째는 현재화면의 context를 지정
        //두번째는 db 파일명
        //세번째는 버전 번호
        helper = new MySQLiteOpenHelper(MainActivity.this,
                "customer.db",
                null,
                1);
        button = (Button)findViewById(R.id.button);
        editText = (EditText)findViewById(R.id.editText);
        button2 = (Button)findViewById(R.id.button2);
        editText2 = (EditText)findViewById(R.id.editText2);
        button3 = (Button)findViewById(R.id.button3);
        editText3 = (EditText)findViewById(R.id.editText3);
        button4 = (Button)findViewById(R.id.button4);
        textView = (TextView)findViewById(R.id.textView);
        //첫번째 버튼은 db를 생성하거나 열어주는 역할
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editText를 받아서 변수에 넣어줌
                databaseName = editText.getText().toString();
                //그 변수를 실행
                createDatabase(databaseName);
            }
        });
        //두번째 버튼은 db에 테이블을 생성하는 역할
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editText를 받아서 변수에 넣어줌
                tableName = editText2.getText().toString();
                //그 변수를 실행
                createTable(tableName);
                //레코드 입력 메소드를 호출함
                int count = insertRecord();
                println(count + "records inserted.");
            }
        });
        //세번째 버튼은 테이블을 검색 하는 역할
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //editText를 받아서 변수에 넣어줌
                searchName = editText3.getText().toString();
                //그 변수를 실행
                searchTable(searchName);
            }
        });
        //네번째 버튼은 로그인 화면으로 이동해주는 역할
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), login.class);
                startActivity(intent);
            }
        });
    }
    //현재 상태가 어떻게 되는지 textview에 표현해주는 기능
    private void println(String s) {
        textView.append("\n" + s);
    }
    //데이터베이스를 만들어주는 기능
    private void createDatabase(String name) {
        //현재 상태가 어떻게 되는지 textview에 뿌려줌
        println("creating database [" + name + "].");
            //db를 name값으로 생성해줌 (name값은 위에 databaseName 값을 가져옴)
            db = openOrCreateDatabase(name, MODE_WORLD_WRITEABLE, null);
            databaseCreated = true;
    }
    //테이블을 만들어주는 기능
    private void createTable(String name) {
        //현재 상태가 어떻게 되는지 textview에 뿌려줌
        println("creating table [" + name + "].");
        //위에 tableName값을 name으로 받아와서 테이블을 생성
        db.execSQL("create table "
                + name
                + "("
                + " _id integer PRIMARY KEY autoincrement, "
                + " name text, "
                + " age integer, "
                + " phone text);");
        tableCreated = true;
    }
    //테이블을 검색해주는 기능
    private void searchTable(String searchName) {
        //db객체를 얻어옴(읽기)
        db = helper.getReadableDatabase();
        //db에 들어있는 값들은 Cursor로 받아줘야됨
        //Cursor c = db.query(searchName, null, null, null, null, null, null); <<이렇게 해줘도됨 하지만 밑에게 더 간단함
        Cursor c = db.rawQuery("select * from " + searchName, null);
        //받아와서 뿌려주는 작업은 while문을 이용해야됨
        //while문 안의 조건에 들어가있는 c.moveToNext()는 위에 담아온 Cursor에 다음 값이 있으면 계속 실행
        //만약에 다음값이 없다면 멈춘다는 뜻
        while (c.moveToNext()){
            //각자의 값을 맡는 타입의 변수를 만들어 넣어줌
            String name = c.getString(c.getColumnIndex("name"));
            int age = c.getInt(c.getColumnIndex("age"));
            String phone = c.getString(c.getColumnIndex("phone"));
            //그리고 값을 뿌려줌
            println(searchName+" 테이블의 값 =\n이름 : " + name + " 나이 : " + age + " 번호 : " + phone);
        }
    }
    //테이블에 값을 넘어줌 insert (테이블 검색기능을 테스트해보기 위해서)
    private int insertRecord(){
        println("inserting records.");
        int count = 3;
        db.execSQL("insert into employee(name, age, phone) values ('john', 20, '010-1234-5678');");
        return count;
    }
}
cs

MySQLiteOpenHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.example.ntsysmac01.sampledatabase;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
 * Created by ntsysMac01 on 2015-12-21.
 */
//이 클래스는 helper로 db를 커넥션 연동 시키기 위해서 꼭 필요한 클래스 이다
public class MySQLiteOpenHelper extends SQLiteOpenHelper{
    public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}
cs

login.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="I D"
            android:id="@+id/textView2"
            android:textAlignment="center" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText4" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="P W"
            android:id="@+id/textView3"
            android:textAlignment="center" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText5" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="ID는 이름 PW는 나이로 입력해주세요."
            android:id="@+id/textView4" />
    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="확인"
            android:id="@+id/button5" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="상태 : "
            android:id="@+id/textView5" />
    </LinearLayout>
</LinearLayout>
cs

login.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.example.ntsysmac01.sampledatabase;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class login extends AppCompatActivity {
    SQLiteDatabase db;
    MySQLiteOpenHelper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        //db를 사용해야되기 때문에 helper에 연결시켜준다
        helper = new MySQLiteOpenHelper(login.this,
                "customer.db",
                null,
                1);
        final EditText id = (EditText)findViewById(R.id.editText4);
        final EditText pw = (EditText)findViewById(R.id.editText5);
        Button button = (Button)findViewById(R.id.button5);
        final TextView textView = (TextView)findViewById(R.id.textView5);
        //버튼을 클릭하게 됨과 동시에 db에서 확인을하게 된다
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db = helper.getReadableDatabase();
                String name = id.getText().toString();
                String age = pw.getText().toString();
                String db_name = null;
                String db_age = null;
                //쿼리문 설정
                Cursor c = db.rawQuery("select * from employee" , null);
                //while문으로 역시 원하는값을 변수에 넣어줌
                while (c.moveToNext()){
                    db_name = c.getString(c.getColumnIndex("name"));
                    db_age = c.getString(c.getColumnIndex("age"));
                }
                //그다음 조건문을 걸어줘서 조건에 부합하다면 성공 메세지와 함께 다음 화면으로 이동
                if(name.equals(db_name) && age.equals(db_age)){
                    textView.append("\n로그인 성공!!!");
                    Intent intent = new Intent(getApplicationContext(), listview.class);
                    startActivity(intent);
                }else if(TextUtils.isEmpty(name) || TextUtils.isEmpty(age)){//유효성검사 해당 변수에 안에 값의 null이거나 비어 있는지를 체크
                    Toast.makeText(login.this,"ID와 PW를 입력하세요",Toast.LENGTH_LONG).show();
                }else{
                    //아니라면 실패라는 메세지와 함께 화면 이동은 발생하지 않음
                    textView.append("\n실패");
                }
            }
        });
    }
}
cs

list.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#009cc3">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="번호"
            android:id="@+id/textView23"
            android:layout_weight="1"
            android:textAlignment="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="제목"
            android:id="@+id/textView24"
            android:layout_weight="1"
            android:textAlignment="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="작성자"
            android:id="@+id/textView25"
            android:layout_weight="1"
            android:textAlignment="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="날짜"
            android:id="@+id/textView26"
            android:layout_weight="1"
            android:textAlignment="center" />
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="430dp"
        android:id="@+id/listView" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="글쓰러가기"
        android:id="@+id/button7"
        android:layout_gravity="center_horizontal" />
</LinearLayout>
cs

Item.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.ntsysmac01.sampledatabase;
/**
 * Created by ntsysMac01 on 2015-12-22.
 */
public class Item {//listView에 데이터가 들어갈 공간을 정의함
    private String[] borditem;//String 배열 타입에 데이터를 넣기위해 선언
    public Item(String[] obj02){
        borditem = obj02;//다른곳에서 값을 넣어줄 수 있게함
    }
    public String[] borditemdate(){
        return borditem;
    }//다른곳에서 이 값을 쓸수있게 설정
    public String borditemdate(int index){//배열 값을 받아쓸때 if문을 한번거침 값이 없거나 인덱스 값이 배열이 가지고 있는 데이터 갯수보다 같거나 크면 null값을 return 해줌
        if (borditem == null || index >= borditem.length) {
            return null;
        }
        return borditem[index];
    }
}
cs

ItemView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.example.ntsysmac01.sampledatabase;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 * Created by ntsysMac01 on 2015-12-22.
 */
public class ItemView extends LinearLayout {//ItemView는 보여지는 역할을 해주는 클래스
    //값을 보여줘야 하기 때문에 보여줄때 필요한 타입을 변수로 선언
    private TextView numtext;//번호
    private TextView subtext;//제목
    private TextView nametext;//이름
    private TextView daytext;
    public ItemView(Context context, Item date) {
        super(context);
        LayoutInflater inflater = (LayoutInflater)//컨텐츠가 보여질 xml을 내가만든 xml로 설정하기 위해 inflater을 설정
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.bordlist_content, thistrue);
        //어느 변수에 무엇이 어떤값이 들어가야 되는지 각각 설정
        numtext = (TextView)findViewById(R.id.textView6);
        numtext.setText(date.borditemdate(0));
        subtext = (TextView)findViewById(R.id.textView7);
        subtext.setText(date.borditemdate(1));
        nametext = (TextView)findViewById(R.id.textView8);
        nametext.setText(date.borditemdate(2));
        daytext = (TextView)findViewById(R.id.textView9);
        daytext.setText(date.borditemdate(3));
    }
    //배열로 처리된 값들을 setText로 쪼개줌
    //위에서 쓰게되는것을 보면 이해가 쉬움
    public void setText(int index, String data){
        if (index == 0 ){
            numtext.setText(data);
        } else if (index == 1 ){
            subtext.setText(data);
        } else if (index == 2){
            nametext.setText(data);
        } else if (index == 3){
            daytext.setText(data);
        } else {
            throw new IllegalArgumentException();
        }
    }
    public ItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public ItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ItemView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
}
cs

itemListAdapter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.example.ntsysmac01.sampledatabase;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by ntsysMac01 on 2015-12-22.
 */
//BaseAdapter에 상속받기 때문에 extends 해줌
public class itemListAdapter extends BaseAdapter{
    private Context mContext;
    //어댑터를 사용할것이기 때문에 리스트를 생성해줌
    private List<Item> mItems = new ArrayList<Item>();
    itemListAdapter(Context context){
        mContext = context;
    }
    void additem(Item it){
        mItems.add(it);
    }
    private void setListItems(List<Item> list){
        mItems = list;
    }
    @Override
    public int getCount() {
        return mItems.size();
    }
    @Override
    public Object getItem(int position) {
        return mItems.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    //저번 예제에서 살펴봤던거와 동일하게 작업해주면 됨
    //퍼포먼스역할과 View 보여주는 역할을 해주는 기능
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemView itemView;
        if(convertView == null) {
            itemView = new ItemView(mContext, mItems.get(position));
        } else {
            itemView = (ItemView) convertView;
            itemView.setText(0, mItems.get(position).borditemdate(0));
            itemView.setText(1, mItems.get(position).borditemdate(1));
            itemView.setText(2, mItems.get(position).borditemdate(2));
            itemView.setText(3, mItems.get(position).borditemdate(3));
        }
        return itemView;
    }
}
cs

listview.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.example.ntsysmac01.sampledatabase;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
public class listview extends AppCompatActivity {
    SQLiteDatabase db;
    MySQLiteOpenHelper helper;
    ListView listView;
    itemListAdapter adapter;
    String num;
    String sub;
    String name;
    String day;
    String content;
    Button writebtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        //list를 불러와야하기 때문에 db를 연결시켜준다
        helper = new MySQLiteOpenHelper(listview.this,
                "customer.db",
                null,
                1);
        //그리고 listview와 adapter를 설정해준다
        listView = (ListView)findViewById(R.id.listView);
        adapter = new itemListAdapter(this);
        String[] arr= new String[5];
        //쿼리문을 설정해주고
        db = helper.getReadableDatabase();
        Cursor c = db.rawQuery("select * from bord"null);
        //while문으로 원하는값을 변수에 담아준다
        //그리고 곧바로 뿌려준다
        while (c.moveToNext()){
            arr[0= num = c.getString(c.getColumnIndex("Num"));
            arr[1= sub = c.getString(c.getColumnIndex("Subject"));
            arr[2= name = c.getString(c.getColumnIndex("Name"));
            arr[3= day = c.getString(c.getColumnIndex("Day"));
            arr[4= content = c.getString(c.getColumnIndex("Content"));
            adapter.additem(new Item(arr));
            arr = new String[5];
        }
        listView.setAdapter(adapter);
        //해당 listView를 클릭하게 되면 상세보기 화면으로 넘어가게끔 설정
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), look.class);
                Item curItem = (Item)adapter.getItem(position);
                String[] curData = curItem.borditemdate();
                intent.putExtra("Item",curData);
                startActivity(intent);
            }
        });
        //글쓰기 버튼을 클릭하게 되면 글쓰기 화면으로 넘어게가끔 설정
        writebtn = (Button)findViewById(R.id.button7);
        writebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), write.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
cs

write.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="제목"
            android:id="@+id/textView10" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText6" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="작성자"
            android:id="@+id/textView11" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText7" />
    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="내용 : "
            android:id="@+id/textView12" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/editText8" />
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="확인"
        android:id="@+id/button6"
        android:layout_gravity="center_horizontal" />
</LinearLayout>
cs

write.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.example.ntsysmac01.sampledatabase;
import android.app.Application;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
//글쓰기페이지 역할
public class write extends AppCompatActivity {
    SQLiteDatabase db;
    MySQLiteOpenHelper helper;
    EditText sub;
    EditText name;
    EditText content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write);
        sub = (EditText)findViewById(R.id.editText6);
        name = (EditText)findViewById(R.id.editText7);
        content = (EditText)findViewById(R.id.editText8);
        Button button = (Button)findViewById(R.id.button6);
        //사용할 db를 연동 시켜준다
        helper = new MySQLiteOpenHelper(write.this"customer.db"null1);
        db = helper.getWritableDatabase();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //글을 다 입력하고 클릭하는 동시에
                GregorianCalendar calendar = new GregorianCalendar();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int min = calendar.get(Calendar.MINUTE);
                int sec = calendar.get(Calendar.SECOND);
                //변수에 각각의 값을 담아주고
                String now = year + "-" + month + "-" + day + "\n" + hour + ":" + min + ":" + sec; //글쓴시간을 저장
                db.execSQL("insert into bord values(null,'"+sub.getText().toString()+"','" +name.getText().toString()+ "','"+now+"','" +content.getText().toString()+ "');");
                //db에 insert시켜준다
                Intent intent = new Intent(getApplicationContext(), listview.class);
                startActivity(intent);
                finish();
                //그다음 값을 intent에 실어주고 intent를 실행시켜준후 finish로 페이지를 닫아준다
            }
        });
    }
}
cs

예제 실행화면은 아래와 같습니다


초기화면에서 db와 테이블의 기능을 사용했고
그 다음 테이블에 담긴 값들을 검색해봤습니다
그리고 로그인버튼을 누르게 되면 아래로 이동하게 됩니다


ID와 PW는 db에 저장되어있는 이름값과 나이값으로 설정해뒀습니다
그래서 db에 연결후 확인하고 값과 동일하다면 다음페이지로 이동이 가능합니다
(상태에서 로그인 성공이 뜬 후 곧바로 자동으로 페이지 이동)


초기화면에 list가 보입니다 모두 db에 저장된 게시글 들이구요
작성시간 또한 저장되어 있습니다 글쓰러가기 버튼을 클릭한 후


제목과 작성자 내용을 입력하게 되면


다시 list로 넘어가게 되면서 밑에 금방 쓴 글이 추가된것을 확인할 수 있습니다


그 다음 그 글을 클릭하게되면 상세보기 페이지로 넘어가서
해당 글을 볼 수 있습니다

출처 : http://bestkkha.blogspot.com/2015/12/db-table.html

LIST
블로그 이미지

SeoHW

,