━━━━ ◇ ━━━━
Android/Android 프로젝트

Android 일기장 만들기

주제 : 일기장 만들기


요구사항 : 

1. TabLayout, PagerAdapter 기능을 사용할 것.

2. ListView, ListAdapter 기능을 사용할 것.

3. Intent 기능을 사용할 것.

4. Dialog 기능을 사용할 것.

5. SQLite 기능을 사용할 것.


계획 :

1. 일기를 쓴다 -> DB에 저장한다. 

2. 일기를 본다 -> DB에서 불러온다.

3. 비밀번호를 설정한다 -> 일기를 볼때 비밀번호가 일치해야 볼수 있다.

4. 리스트뷰에서 클릭하여 수정, 롱클릭하여 삭제

5. 알림창은 다이얼로그와 새로운 액티비티를 만들어서 intent를 사용한다.

6. 각각의 카테고리는 탭레이아웃과 페이저어댑터를 이용하여 만든다.




실행 사진들








새 프로젝트를 생성하고 가장 먼저 할일은 Dependency 에 사용할 라이브러리 들을 추가하는 것이다.




▲ File -> Project Structure 




▲ app -> Dependency -> 더하기 단추 -> Library dependency




▲ design 추가




두번째로 할 일은 기본으로 설정되어 있는 액션바를 없애주는 것이다.




▲ res -> values -> styles.xml -> NoActionBar 로 바꿔준다.




▲ 메인 레이아웃에 툴바와 탭레이아웃, 뷰어페이저 등을 등록한다.




▼ 일기장 DB에서 사용할 Diary 클래스를 생성하고, 적당한 필드값들을 만든 후 getter, setter 를 생성한다.






▼ SQLiteOpenHelper 를 상속받는 클래스를 생성하고, 메소드를 오버라이드 한다.



▼ 생성자도 만들어 준다.





▼ FragmentStatePagerAdater 를 상속받는 클래스를 생성하고 필요한 메소드 들을 오버라이드 해준다.





이하는 코드 소스들


1. 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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    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.aristata.a0720_01_diary_ver2.MainActivity">
 
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
 
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
 
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</LinearLayout>
 
cs



2. tab_setting.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
<?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="50dp"
        android:layout_marginTop="5dp">
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="비밀번호 사용"
            android:id="@+id/text_secret"
            android:textSize="20dp"
            android:layout_weight="1"
            android:gravity="center" />
 
        <Switch
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:id="@+id/switch1"
            android:layout_gravity="right"
            android:layout_weight="1"
            android:gravity="center" />
    </LinearLayout>
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp">
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="비밀번호 설정"
            android:id="@+id/textView"
            android:textSize="20dp"
            android:gravity="center"
            android:layout_weight="1" />
 
        <EditText
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/secret_editText"
            android:gravity="center"
            android:layout_weight="1"
            android:visibility="invisible" />
    </LinearLayout>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="저장"
        android:id="@+id/secret_save_btn" />
 
</LinearLayout>
cs



3. tab_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
<?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" >
 
    <EditText
        android:id="@+id/edit_title_write"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="제목을 입력하세요."
        android:background="#e1f1cb"
        android:layout_weight="5" />
    <EditText
        android:id="@+id/edit_contents_write"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#efedbf"
        android:lines="15"
        android:hint="내용을 입력하세요."
        android:gravity="top|left"
        android:layout_weight="1" />
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="#e1f1cb">
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="저장"
            android:id="@+id/save_btn_write"
            android:layout_weight="1" />
 
    </LinearLayout>
 
</LinearLayout>
cs


4. tab_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
<?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">
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="목록 보기"
        android:id="@+id/refresh_btn_list" />
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="7"
        android:gravity="center">
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="코드"
            android:id="@+id/textCode"
            android:gravity="center" />
 
        <TextView
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="제목"
            android:id="@+id/textTitle"
            android:gravity="center" />
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="날짜"
            android:id="@+id/textDate"
            android:layout_weight="1"
            android:gravity="center" />
    </LinearLayout>
 
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_diary"
        android:layout_weight="1" />
 
</LinearLayout>
cs


5. list_layout.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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView_code"
        android:gravity="center" />
 
    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView_title"
        android:gravity="center" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView_date"
        android:layout_weight="1"
        android:gravity="center" />
</LinearLayout>
cs


6. passwd.xml


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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">
 
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/key" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/check_pass"
        android:layout_gravity="center_horizontal"
        android:hint="비밀번호를 입력하세요" />
 
</LinearLayout>
cs


7. activity_diary_update.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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    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.aristata.a0720_01_diary_ver2.Diary_Update">
 
    <EditText
        android:id="@+id/edit_title_update"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="제목을 입력하세요."
        android:background="#e1f1cb"
        android:layout_weight="5" />
    <EditText
        android:id="@+id/edit_contents_update"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#efedbf"
        android:lines="15"
        android:hint="내용을 입력하세요."
        android:gravity="top|left"
        android:layout_weight="1" />
 
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="#e1f1cb">
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="저장"
            android:id="@+id/save_btn_update"
            android:layout_weight="1" />
 
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="돌아가기"
            android:id="@+id/return_btn_update"
            android:layout_weight="1" />
 
    </LinearLayout>
</LinearLayout>
 
cs


8. Diary.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
package com.aristata.a0720_01_diary_ver2;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class Diary {
 
    private int code;
    private String title;
    private String date;
    private String contents;
 
    public int getCode() {
        return code;
    }
 
    public void setCode(int code) {
        this.code = code;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getDate() {
        return date;
    }
 
    public void setDate(String date) {
        this.date = date;
    }
 
    public String getContents() {
        return contents;
    }
 
    public void setContents(String contents) {
        this.contents = contents;
    }
}
 
cs


9. DiaryDBHelper.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class DiaryDBHelper extends SQLiteOpenHelper {
 
 
    public DiaryDBHelper(Context context) {
        super(context, "Diary"null1);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE diary (" +
                "'code' INTEGER PRIMARY KEY AUTOINCREMENT," +
                "`title` TEXT," +
                "`date` TEXT," +
                "`contents` TEXT);";
        db.execSQL(sql);
 
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "drop table if exists diary";
        db.execSQL(sql);
 
        onCreate(db);
    }
}
 
cs


10. DiaryPassDBHelper.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.aristata.a0720_01_diary_ver2;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class DiaryPassDBHelper extends SQLiteOpenHelper {
    public DiaryPassDBHelper(Context context) {
        super(context, "Password"null1);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE passwd (" +
                "'pass' TEXT);";
        db.execSQL(sql);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sql = "drop table if exists passwd";
        db.execSQL(sql);
 
        onCreate(db);
    }
}
 
cs


11. DiaryListAdapter.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
 
import java.util.ArrayList;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class DiaryListAdapter extends BaseAdapter {
    private Context ctx;
    private int layout;
    private ArrayList<Diary> data;
    private LayoutInflater inflater;
 
    public DiaryListAdapter(Context ctx, int layout, ArrayList<Diary> data) {
        this.ctx = ctx;
        this.layout = layout;
        this.data = data;
        inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return data.size();
    }
 
    @Override
    public Object getItem(int position) {
        return data.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null){
            convertView = inflater.inflate(layout,parent,false);
        }
        TextView textView_code_list = (TextView)convertView.findViewById(R.id.textView_code);
        TextView textView_title_list = (TextView)convertView.findViewById(R.id.textView_title);
        TextView textView_date_list = (TextView)convertView.findViewById(R.id.textView_date);
        textView_code_list.setText(data.get(position).getCode()+"");
        textView_title_list.setText(data.get(position).getTitle()+"");
        textView_date_list.setText(data.get(position).getDate()+"");
        return convertView;
    }
}
 
cs


12. Tab_Pager_Adapter.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
package com.aristata.a0720_01_diary_ver2;
 
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
 
/**
 * Created by aristata on 2016-07-20.
 */
public class Tab_Pager_Adapter extends FragmentStatePagerAdapter {
    private int tabCount;
 
    public Tab_Pager_Adapter(FragmentManager fm, int tabCount) {
        super(fm);
        this.tabCount = tabCount;
    }
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 1:
                MainActivity.Diary_Write diaryWrite = new MainActivity.Diary_Write();
                return diaryWrite;
            case 2:
 
                MainActivity.Diary_List diaryList = new MainActivity.Diary_List();
                return diaryList;
            case 0:
                MainActivity.Diary_Setting diarySetting = new MainActivity.Diary_Setting();
                return diarySetting;
            default:
                return null;
        }
    }
 
    @Override
    public int getCount() {
        return tabCount;
    }
}
 
cs


13. MainActivity.java


package com.aristata.a0720_01_diary_ver2;
 
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;
 
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
 
public class MainActivity extends AppCompatActivity {
 
    //메인 엑티비티 전역변수
    private static TabLayout tabLayout;
    private static ViewPager viewPager;
    private static ArrayList<Diary> data;
    public static DiaryDBHelper dbHelper;
    public static DiaryPassDBHelper pdbHelper;
    public static SQLiteDatabase db;
 
 
    //Tab_Write 전역변수
    public static EditText edit_title, edit_contents;
    public static Button save_btn;
 
    //Tab_List 전역변수
    public static Button refresh_btn;
    public static ListView list_diary;
    public static DiaryListAdapter listAdapter;
 
    //Tab_Setting 전역변수
    public static Switch secretSwitch;
    public static EditText secretEditText;
    public static Button secretSaveBtn;
 
    public static EditText checkPass;
    public static int flag = 0;
    public static int flag2 = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //디비 핼퍼 객체 생성
        dbHelper = new DiaryDBHelper(this);
        pdbHelper = new DiaryPassDBHelper(this);
        data = new ArrayList<>();
 
        //커스텀 툴바의 리소스 연결
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
 
        //액션바를 커스텀 툴바로 설정
        setSupportActionBar(toolbar);
 
        //커스텀 탭 레이아웃 리소스 연결
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
 
        //탭 레이아웃에 탭 추가
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_settings_white_48dp));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_create_white_48dp));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_visibility_white_48dp));
 
 
        //탭 배치 설정
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
 
        //커스텀 뷰페이지 리소스 연결
        viewPager = (ViewPager) findViewById(R.id.pager);
 
        //페이지 어답터 객체 생성
        Tab_Pager_Adapter pagerAdapter = new Tab_Pager_Adapter(getSupportFragmentManager(), tabLayout.getTabCount());
 
        //뷰 페이지 어답터 설정
        viewPager.setAdapter(pagerAdapter);
 
        //페이지에 변화가 생기면 ?
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        //viewPager.addOnPageChangeListener();
 
        //탭 선택 이벤트
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
 
            }
 
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
 
            }
 
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
 
            }
        });
 
 
    }//end of onCreate -------------------------------------------------------
 
    //Diary_Write inner class
    public static class Diary_Write extends Fragment{
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.tab_write, container, false);
            edit_title = (EditText) view.findViewById(R.id.edit_title_write);
            edit_contents = (EditText) view.findViewById(R.id.edit_contents_write);
            save_btn = (Button) view.findViewById(R.id.save_btn_write);
            save_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    InsertDB();
                }
            });
            return view;
        }
    }
 
    //Diary_List inner class
    public static class Diary_List extends Fragment{
 
        @Nullable
        @Override
        public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
            final View view = inflater.inflate(R.layout.tab_list, container, false);
            flag = 1;
            refresh_btn = (Button) view.findViewById(R.id.refresh_btn_list);
            refresh_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(secretSwitch.isChecked()){
                        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                        alertDialog.setMessage("비밀번호를 입력하세요");
                        View dialogview = inflater.inflate(R.layout.passwd, container, false);
                        alertDialog.setView(dialogview);
                        checkPass = (EditText)dialogview.findViewById(R.id.check_pass);
 
                        alertDialog.setPositiveButton("확인"new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String cp = checkPass();
                                if(checkPass.getText().toString().equals(cp)){
                                    list_diary = (ListView) view.findViewById(R.id.list_diary);
                                    data = showDB();
                                    listAdapter = new DiaryListAdapter(getContext(), R.layout.list_layout, data);
                                    list_diary.setAdapter(listAdapter);
                                    list_diary.setOnItemClickListener( new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            Intent intent = new Intent(getContext(), Diary_Update.class);
                                            int code = data.get(position).getCode();
                                            intent.putExtra("code", code);
                                            startActivity(intent);
                                        }
                                    });
                                    list_diary.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                                        @Override
                                        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                                            alertDialog.setMessage(data.get(position).getTitle()+"을(를) 삭제하시겠습니까?");
                                            alertDialog.setPositiveButton("삭제"new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    int code = data.get(position).getCode();
                                                    deleteDB(code);
                                                    showDB();
                                                    listAdapter.notifyDataSetChanged();
                                                }
                                            });
                                            alertDialog.setNegativeButton("취소"new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.cancel();
                                                }
                                            });
                                            alertDialog.show();
                                            return false;
                                        }
                                    });
                                }else{
                                    Toast.makeText(getContext(), "비밀번호가 틀렸습니다.", Toast.LENGTH_SHORT).show();
                                    list_diary = (ListView) view.findViewById(R.id.list_diary);
                                    data = showDB();
                                    listAdapter = null;
                                    list_diary.setAdapter(listAdapter);
                                }
                            }
                        });
                        alertDialog.show();
                    }else{
                        list_diary = (ListView) view.findViewById(R.id.list_diary);
                        data = showDB();
                        listAdapter = new DiaryListAdapter(getContext(), R.layout.list_layout, data);
                        list_diary.setAdapter(listAdapter);
                        list_diary.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(getContext(), Diary_Update.class);
                                int code = data.get(position).getCode();
                                intent.putExtra("code", code);
                                startActivity(intent);
                            }
                        });
                        list_diary.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                            @Override
                            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                                alertDialog.setMessage(data.get(position).getTitle()+"을(를) 삭제하시겠습니까?");
                                alertDialog.setPositiveButton("삭제"new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        int code = data.get(position).getCode();
                                        deleteDB(code);
                                        showDB();
                                        listAdapter.notifyDataSetChanged();
                                    }
                                });
                                alertDialog.setNegativeButton("취소"new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                });
                                alertDialog.show();
                                return false;
                            }
                        });
                    }
 
 
                }
            });
            if(flag == 1){
                return view;
            }else{
                return null;
            }
 
 
        }
    }
 
    //환경설정 inner class
    public static class Diary_Setting extends Fragment{
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.tab_setting, container, false);
            secretSwitch = (Switch)view.findViewById(R.id.switch1);
            secretEditText = (EditText)view.findViewById(R.id.secret_editText);
            secretSaveBtn = (Button)view.findViewById(R.id.secret_save_btn);
            secretSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        //On
                        secretEditText.setVisibility(View.VISIBLE);
 
                    }else{
                        //Off
                        secretEditText.setVisibility(View.INVISIBLE);
 
 
                    }
                }
            });
            secretSaveBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str = secretEditText.getText().toString();
                    passDB(str);
                }
            });
            return view;
        }
    }
 
 
    //일기 쓰기 메소드
    public static void InsertDB(){
        db = dbHelper.getWritableDatabase();
        String sql = "insert into diary ('title', 'date', 'contents') values(?,?,?)";
        SQLiteStatement st = db.compileStatement(sql);
        st.bindString(1,edit_title.getText().toString());
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yy년 MM월 dd일 HH시 mm분 ss초");
        String writeTime = sdf.format(date);
        st.bindString(2,writeTime);
        st.bindString(3,edit_contents.getText().toString());
        st.execute();
        db.close();
        edit_title.setText("");
        edit_contents.setText("");
    }
 
    //일기 목록 보기 메소드
    public static ArrayList<Diary> showDB(){
        data.clear();
        db = dbHelper.getReadableDatabase();
        String sql = "select * from diary";
        Cursor cursor = db.rawQuery(sql, null);
        while(cursor.moveToNext()){
            Diary diary = new Diary();
            diary.setCode(cursor.getInt(0));
            diary.setTitle(cursor.getString(1));
            diary.setDate(cursor.getString(2));
            diary.setContents(cursor.getString(3));
            data.add(diary);
        }
        cursor.close();
        db.close();
        return data;
    }
 
    //일기 삭제 메소드
    public static void deleteDB(int code){
        db = dbHelper.getReadableDatabase();
        String sql = "delete from diary where code="+code;
        db.execSQL(sql);
        db.close();
    }
 
    //비밀번호 입력 메소드
    public static void passDB(String str){
        db = pdbHelper.getWritableDatabase();
        String sql = "insert into passwd values('"+str+"')";
        db.execSQL(sql);
        db.close();
        secretEditText.setText("");
    }
    //비밀번호 확인 메소드
    public static String checkPass(){
        db = pdbHelper.getReadableDatabase();
        String sql = "select * from passwd";
        Cursor cursor = db.rawQuery(sql, null);
        String pass="";
        while(cursor.moveToNext()){
            pass = cursor.getString(0);
        }
        cursor.close();
        db.close();
        return pass;
    }
 
}
 
cs


14. Diary_Update.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
package com.aristata.a0720_01_diary_ver2;
 
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class Diary_Update extends AppCompatActivity {
    private Intent intent;
    private EditText editText1, editText2;
    private int code;
    private Button btn1, btn2;
    private DiaryDBHelper dbHelper;
    private SQLiteDatabase db;
    private Diary diary = new Diary();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary__update);
        intent = getIntent();
 
        dbHelper = new DiaryDBHelper(getApplicationContext());
 
        editText1 = (EditText)findViewById(R.id.edit_title_update);
        editText2 = (EditText)findViewById(R.id.edit_contents_update);
 
        code = intent.getExtras().getInt("code");
 
        btn1 = (Button)findViewById(R.id.save_btn_update);
        btn2 = (Button)findViewById(R.id.return_btn_update);
 
        searchDiary(code);
        editText1.setText(diary.getTitle().toString());
        editText2.setText(diary.getContents().toString());
 
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDB(code);
                finish();
            }
        });
 
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    public Diary searchDiary(int code){
        db = dbHelper.getReadableDatabase();
        String sql = "select * from diary where code="+code;
        Cursor cursor = db.rawQuery(sql, null);
        while(cursor.moveToNext()){
            diary.setTitle(cursor.getString(1));
            diary.setContents(cursor.getString(3));
        }
        cursor.close();
        db.close();
        return diary;
    }
    public void updateDB(int code){
        db = dbHelper.getWritableDatabase();
        String sql = "update diary set title=?, contents=? where code="+code;
        SQLiteStatement st = db.compileStatement(sql);
        st.bindString(1,editText1.getText().toString());
        st.bindString(2,editText2.getText().toString());
        st.execute();
        db.close();
    }
}
 
cs


COMMENT