---
# System prepended metadata

title: 'AN25 課題10,11,12'
tags: [課題]

---

# AN25 課題10,11,12
###### tags: `課題`


## １
activity_main.xml
```xml=
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dip"
        android:gravity="left">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="キー"
            />
        <EditText
            android:id="@+id/EditKey"
            android:layout_width="400dp"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="カテゴリー"
        />
    <EditText
        android:id="@+id/CategoryKey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="本文"
        />
    <EditText
        android:id="@+id/Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.93"
        android:gravity="top"
        />

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            >
            <Button
                android:id="@+id/KeyWrite"
                android:layout_width="70dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyWrite"
                android:text="保存"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyUpdate"
                android:layout_width="70dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyUpdate"
                android:text="更新"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyClear"
                android:layout_width="90dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyClear"
                android:text="クリア"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyList"
                android:layout_width="70dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyList"
                android:text="一覧"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyDelete"
                android:layout_width="70dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyDelete"
                android:text="削除"
                android:textSize="20sp"
                />
        </TableRow>
    </TableLayout>

</LinearLayout>
```

list_view.xml
```xml=
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="select a item"/>

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:textSize="30sp"/>

    <Button
        android:id="@+id/KeyList"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="functionKeySelect"
        android:text="検索"
        android:textSize="20sp"
        />

    <TextView
        android:id="@+id/mylistTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dip"
        android:textSize="20sp"
        android:textColor="#FF0000"
        />

    <ListView
        android:id="@+id/myListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.93"
        />

    <Button
        android:text="戻る"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="buttonMethod"
        />

</LinearLayout>
```

MainActivity.java
```java=
package nhs00650.hal.ac.mylibrary;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Calendar;
import java.util.Date;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.database.*;
import android.database.sqlite.*;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {

    EditText et;
    EditText ekey;
    EditText ckey;
    SQLiteDatabase db;
    SQLiteDatabase db2;
    String write_dateStr;
    int key_flag = 0;

    String select_key;
    String id_listshow = "";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText)findViewById(R.id.Text);
        ekey = (EditText)findViewById(R.id.EditKey);
        ckey = (EditText)findViewById(R.id.CategoryKey);

        //↓は一度実効したあとコメントアウトしなおす
       //first_database();

        //インテントからキーを取得
        Bundle extras = getIntent().getExtras();
        if(extras != null){
            select_key = extras.getString("select_key");
            id_listshow = extras.getString("id_primary");

            String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
            db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
            String query_read = "SELECT * FROM memopad WHERE id = '" + id_listshow + "'";
            System.out.println(query_read);

            Cursor db_row = db.rawQuery(query_read,null);

            int id = 0;
            String keyword = "";
            String memo = "";
            Toast toast_read;
            String category = "";

            while (db_row.moveToNext()){
                key_flag = 1;
                int index_id = db_row.getColumnIndex("id");
                int index_keyword = db_row.getColumnIndex("keyword");
                int index_memo = db_row.getColumnIndex("memo");
                int index_category = db_row.getColumnIndex("category");
                id = db_row.getInt(index_id);
                keyword = db_row.getString(index_keyword);
                memo = db_row.getString(index_memo);
                category = db_row.getString(index_category);
            }

            //intのidをString変換
            String id_str = String.valueOf(id);

            //一覧から取得した主キーを基にキーワードとメモ表示
            ekey.setText(keyword);
            et.setText(memo);
            ckey.setText(category);

            //Toastで表示
            if(key_flag == 0) {
                toast_read = Toast.makeText(this,
                        "指定されたキーはありません", Toast.LENGTH_SHORT);
                toast_read.show();
            }
            else {
                toast_read = Toast.makeText(this,
                        id_str + "の内容を読み込みました", Toast.LENGTH_SHORT);
                toast_read.show();
            }
            key_flag = 0;
        }
    }

    public void functionKeyList(View v){
        //「一覧」のSQL
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        String query_list = "SELECT * FROM memopad";
        System.out.println(query_list);

        Cursor db_row = db.rawQuery(query_list,null);
        System.out.println(db_row);

        String keyword = "";
        String write_date = "";

        //ListShow.javaで一覧表示するためのデータ格納
        String id_continue = "";
        String keyword_continue = "";
        String keywordanddate_continue = "";

        //,区切りのデータ作成 id,keyword,memo,write_date
        while (db_row.moveToNext()){
            int index_id = db_row.getColumnIndex("id");
            int index_keyword = db_row.getColumnIndex("keyword");
            int index_write_date = db_row.getColumnIndex("write_date");
            int id = db_row.getInt(index_id);
            keyword = db_row.getString(index_keyword);
            write_date = db_row.getString(index_write_date);

            //id(int)をString変換
            String id_str = String.valueOf(id);

            //ID
            if(id_continue != ""){
                id_continue += "," + id_str;
            }else {
                id_continue += id_str;
            }

            //キーワード
            if(keyword_continue != ""){
                keyword_continue += "," + keyword;
            }else {
                keyword_continue += keyword;
            }

            //キーワード＋日付
            if(keywordanddate_continue != ""){
                keywordanddate_continue += "," + keyword + "    " + write_date;
            }else {
                keywordanddate_continue += keyword + "    " + write_date;
            }
        }

        //ListViewアクティビティを起動
        Intent result_act = new Intent(MainActivity.this, ListShow.class);
        result_act.putExtra("id_continue",id_continue);
        result_act.putExtra("keywordanddate_continue",keywordanddate_continue);
        startActivity(result_act);
    }

    //「保存」(書き込み)のSQL
    public void functionKeyWrite(View v){
        //「保存」のSQL
        String key = ekey.getText().toString();
        String text = et.getText().toString();
        String keyc = ckey.getText().toString();
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        write_dateStr = now_date();
        String query_read = "SELECT * FROM memopad WHERE keyword = '" + key + "'";
        String query_insert = "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('" + key + "','" + text + "','" + write_dateStr + "','" + keyc + "')";

        Cursor db_row = db.rawQuery(query_read,null);

        db.execSQL(query_insert);
        System.out.println(query_insert);

        Toast toast_save;

        //Toastで表示
        toast_save = Toast.makeText(this,
                key + "をキーに書き込みました", Toast.LENGTH_SHORT);
        toast_save.show();

        key_flag = 0;
    }

    //本文クリア
    public void functionKeyClear(View v){
        //「クリア」のSQL

        et.getEditableText().clear();
    }

    //削除
    public void functionKeyDelete(View v){
        //「削除」のSQL
        String key = ekey.getText().toString();
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        db2 = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        String query_read = "SELECT * FROM memopad WHERE keyword = '" + key + "'";
        Cursor db_row = db.rawQuery(query_read,null);

        while (db_row.moveToNext()){
            key_flag = 1;
            ekey.getEditableText().clear();
            et.getEditableText().clear();
        }

        String query_delete = "DELETE FROM memopad WHERE keyword = '" + key + "'";
        db2.execSQL(query_delete);

        Toast toast_delete;

        //Toastで表示
        if(key_flag == 0) {
            toast_delete = Toast.makeText(this,
                    "指定されたキーはありません", Toast.LENGTH_SHORT);
            toast_delete.show();
        }
        else {
            toast_delete = Toast.makeText(this,
                    key + "を削除しました", Toast.LENGTH_SHORT);
            toast_delete.show();
        }

        key_flag = 0;
    }

    public void functionKeyUpdate(View KeyUpdate){
        int count = 0;
        String ekeyStr = ekey.getText().toString();
        String etStr = et.getText().toString();
        String query_count = "SELECT * FROM memopad WHERE keyword = '" + ekeyStr + "'";
        Cursor db_row = db.rawQuery(query_count, null);
        write_dateStr = now_date();
        while (db_row.moveToNext()) {
            int index_key = db_row.getColumnIndex("keyword");
            String key = db_row.getString(index_key);
            if(key.equals(ekeyStr)){
                count = 1;
                break;
            } else {
                count = 0;
            }
        }
        if(count == 1){
            String query_record_update = "UPDATE memopad SET memo = '" + etStr + "', write_date = '" + write_dateStr +"' WHERE keyword = '" + ekeyStr +  "'";
            db.execSQL(query_record_update);
            Toast myToast = Toast.makeText(this,
                    ekeyStr + "を更新しました", Toast.LENGTH_SHORT);
            myToast.show();
        } else if(count == 0){
            Toast myToast = Toast.makeText(this,
                    "指定されたキーはありません", Toast.LENGTH_SHORT);
            myToast.show();
        }

    }

    //初期にデータベース動かすコード
    private void first_database(){
        //データベースを作成
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);

        //テーブル作成用のクエリ文
        String query_table1 = "DROP TABLE IF EXISTS memopad";
        String query_table2 = "CREATE TABLE memopad(id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "keyword TEXT,memo TEXT,write_date TEXT, category TEXT)";

        //テーブルの作成
        db.execSQL(query_table1);
        db.execSQL(query_table2);

        //レコード追加
        write_dateStr = now_date();//本日日付取得
        String query_record_set[] = {
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('入門Python3','オライリーのPython本','" + write_dateStr +"', 'Python')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('Pythonチュートリアル','Pythonのチュートリアル','" + write_dateStr +"', 'Python')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('分かるPython','Pythonの基本','" + write_dateStr +"', 'Python')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('今時のプログラマーのためのReact','Reactの基本','" + write_dateStr +"', 'React')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('React実践の教科書','React実践編','" + write_dateStr +"', 'React')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('Pythonによるデータ分析の教科書','データ分析初心者','" + write_dateStr +"', 'AI')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('Pythonによるデータ分析入門','データ分析入門','" + write_dateStr +"', 'AI')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('Kaggle入門','kaggle初心者','" + write_dateStr +"', 'AI')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('データ分析の技術','データ分析応用・実践編','" + write_dateStr +"', 'AI')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('zero to one','君に何ができるのか','" + write_dateStr +"', 'Tech本')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('隷属なき道','ベーシックインカムとテクノロジー','" + write_dateStr +"', 'Tech本')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('AIは人間を超えるのか','人工知能についての本','" + write_dateStr +"', 'Tech本')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('Airbnb story','Airbnbの創業秘話','" + write_dateStr +"', 'Tech本')"
        };

        for (int i=0; i<query_record_set.length; i++){
            db.execSQL(query_record_set[i]);
        }
    }



    //本日の日付を返すメソッド
    private String now_date(){
        //現在日取得
        Date today = new Date();

        //Calendarクラスオブジェクト生成
        Calendar cal = Calendar.getInstance();

        //Calendarオブジェクトに現在日付設定
        cal.setTime(today);

        //年月日時分秒所得
        int yy = cal.get(Calendar.YEAR);
        int mm = cal.get(Calendar.MONTH) + 1;
        int dd = cal.get(Calendar.DATE);
        int hour = cal.get(Calendar.HOUR);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);

        String now_dateStr = yy + "/" + mm + "/" + dd + " " + hour + ":" + minute + ":" + second;

        return now_dateStr;
    }
}

```

ListShow.java
```java=
package nhs00650.hal.ac.mylibrary;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Intent;
import android.widget.Spinner;

public class ListShow extends AppCompatActivity{
    private TextView List_title;
    private ListView List_View;
    String[] listKey;
    String[] id_primary;
    String[] keywordanddate;
    private TextView aTextView;
    private Spinner aSpinner;
    String ss = "";
    private String[] listStrings = {
            "Python", "React", "AI", "Tech本"
    };
    SQLiteDatabase db;
    String[] selectlist;
    int index_id_p;
    int id_p;
    String keyword = "";

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view);

        //IDから目的のウィジェットを得る
        List_title = (TextView)findViewById(R.id.mylistTitle);
        List_View= (ListView)findViewById(R.id.myListView);

        aTextView = (TextView)findViewById(R.id.myTextView);
        aSpinner = (Spinner)findViewById(R.id.mySpinner);


        ArrayAdapter<String> myAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listStrings);
        aSpinner.setAdapter(myAdapter);

        aSpinner.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                        Spinner spinner = (Spinner) parent;
                        ss = (String) spinner.getSelectedItem();
                        aTextView.setText(String.format(" %s selected", ss));
                    }

                    public void onNothingSelected(AdapterView<?> parent){

                    }
                }
        );


        //インテントからキーを取得
        Bundle extras = getIntent().getExtras();
        if(extras != null){
            String id_continue = extras.getString("id_continue");
            String keywordanddate_continue = extras.getString("keywordanddate_continue");
            id_primary = id_continue.split(",");
            keywordanddate = keywordanddate_continue.split(",");
        }

        //リストに表示する名称

        //ヘッダ設定
        String head_title = "メモ一覧(" + keywordanddate.length + "件)";
        List_title.setText(head_title);

        //リストアダプタを作成
        ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(
                this,android.R.layout.simple_list_item_1,keywordanddate);

        //リストアダプタをリストビューにセット
        List_View.setAdapter(myAdapter2);

        //リスト選択処理
        List_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(
                    AdapterView<?> parent,View v,int position, long id){
                Log.d("onItemClick","position:" + String.valueOf(position));
                String select_key = id_primary[position];
                //int listshow_flag = 1;

                //ListShowアクティビティを起動
                Intent result_act = new Intent(ListShow.this, MainActivity.class);
                result_act.putExtra("select_key",select_key);
                result_act.putExtra("id_primary",id_primary[position]);
                startActivity(result_act);
            }
        });
    }

    public void functionKeySelect(View v) {
        //「一覧」のSQL
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr, null);
        String query_list = "SELECT * FROM memopad WHERE category = '" + ss + "'";
        System.out.println(query_list);

        Cursor db_row = db.rawQuery(query_list, null);
        System.out.println(db_row);


        String write_date = "";

        //ListShow.javaで一覧表示するためのデータ格納
        String id_continue = "";
        String keyword_continue = "";
        String keywordanddate_continue = "";

        //,区切りのデータ作成 id,keyword,memo,write_date
        while (db_row.moveToNext()) {
            index_id_p = db_row.getColumnIndex("id");
            int index_keyword = db_row.getColumnIndex("keyword");
            int index_write_date = db_row.getColumnIndex("write_date");
            id_p = db_row.getInt(index_id_p);
            keyword = db_row.getString(index_keyword);
            write_date = db_row.getString(index_write_date);

            //id(int)をString変換
            String id_str = String.valueOf(id_p);

            //ID
            if (id_continue != "") {
                id_continue += "," + id_str;
            } else {
                id_continue += id_str;
            }


            //キーワード
            if (keyword_continue != "") {
                keyword_continue += "," + keyword;
            } else {
                keyword_continue += keyword;
            }

            //キーワード＋日付
            if (keywordanddate_continue != "") {
                keywordanddate_continue += "," + keyword + "    " + write_date;
            } else {
                keywordanddate_continue += keyword + "    " + write_date;
            }

            id_primary = id_continue.split(",");

        }


        selectlist = keywordanddate_continue.split(",");

        String head_title = ss +"メモ一覧(" + selectlist.length + "件)";
        List_title.setText(head_title);

        ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(
                this,android.R.layout.simple_list_item_1,selectlist);

        //リストアダプタをリストビューにセット
        List_View.setAdapter(myAdapter2);

        List_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(
                    AdapterView<?> parent,View v,int position, long id){
                Log.d("onItemClick","position:" + String.valueOf(position));
                String select_key = id_primary[position];

                //ListShowアクティビティを起動
                Intent result_act = new Intent(ListShow.this, MainActivity.class);
                result_act.putExtra("select_key",select_key);
                result_act.putExtra("id_primary",id_primary[position]);
                startActivity(result_act);
            }
        });


    }

    //ボタンの処理
    public void buttonMethod(View myButton){
        Intent result_act = new Intent(ListShow.this, MainActivity.class);
        startActivity(result_act);
    }
}
```

AndroidManifest.xml
```xml=
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="nhs00650.hal.ac.mylibrary">

    <application
        android:allowBackup="true"
        android:appComponentFactory="androidx.core.app.CoreComponentFactory"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:testOnly="true"
        android:theme="@style/AppTheme" >
        <activity android:name="nhs00650.hal.ac.mylibrary.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="nhs00650.hal.ac.mylibrary.ListShow"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

```


## 改訂版

改善点
 - 保存を押したときすでに存在するキーでも保存できてしまう問題を解決
 - 更新ボタンが使えるようにした
 - スピナーでカテゴリを選択できるように変更
 - リストで0件の場合でも1件と表示されてしまう問題を解決
 (AndroidManifest.xmlは上と同じ感じ)
 
 それぞれが変更する場所
 - .javaのパッケージ名
 - MainActivity.java20行目くらいにあるliststringsの内容
 - MainActivity.javaの100行目くらいにあるif文の内容
 - ListShow.javaの20行目くらいにあるliststringsの内容
 
 

activity_main.xml
```xml=
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dip"
        android:gravity="left">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="キー"
            />
        <EditText
            android:id="@+id/EditKey"
            android:layout_width="400dp"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dip"
        android:gravity="left">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="カテゴリー"
            />
        <Spinner
            android:id="@+id/mySpinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>




    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="本文"
        />
    <EditText
        android:id="@+id/Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.93"
        android:gravity="top"
        />

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            >
            <Button
                android:id="@+id/KeyWrite"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="functionKeyWrite"
                android:text="保存"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyUpdate"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="functionKeyUpdate"
                android:text="更新"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyClear"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="functionKeyClear"
                android:text="クリア"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyList"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="functionKeyList"
                android:text="一覧"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyDelete"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="functionKeyDelete"
                android:text="削除"
                android:textSize="20sp"
                />
        </TableRow>
    </TableLayout>

</LinearLayout>
```

list_view.xml
```xml=
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Spinner
        android:id="@+id/mySpinner"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:textSize="20sp"/>

    <Button
        android:id="@+id/KeyList"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="functionKeySelect"
        android:text="検索"
        android:textSize="20sp"
        />

    <TextView
        android:id="@+id/mylistTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dip"
        android:textSize="20sp"
        android:textColor="#FF0000"
        />

    <ListView
        android:id="@+id/myListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.93"
        />

    <Button
        android:text="戻る"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="buttonMethod"
        />

</LinearLayout>
```

MainActivity.java
```java=
package nhs00402.hal.ac.mylibrary2;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Calendar;
import java.util.Date;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.database.*;
import android.database.sqlite.*;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {

    EditText et;
    EditText ekey;
    Spinner spkey;
    SQLiteDatabase db;
    SQLiteDatabase db2;
    String write_dateStr;
    int key_flag = 0;
    int index = 0;

    String keyc = "";
    String select_key;
    String id_listshow = "";

    private String[] listStrings = {
            "tops", "outer", "bottoms", "onepiece",
            "shoes", "bag", "komono"
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText)findViewById(R.id.Text);
        ekey = (EditText)findViewById(R.id.EditKey);
        spkey=(Spinner)findViewById(R.id.mySpinner);

        //↓は一度実効したあとコメントアウトしなおす
        //first_database();



        //スピナーの値の取得
        ArrayAdapter<String> myAdapter =
                new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, listStrings);
        spkey.setAdapter(myAdapter);

        spkey.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> parent, View v, int position, long id){
                        Spinner spinner = (Spinner) parent;
                        keyc = (String) spinner.getSelectedItem();
                    }
                    public void onNothingSelected(AdapterView<?> parent){

                    }
                });

        //インテントからキーを取得
        Bundle extras = getIntent().getExtras();
        if(extras != null){
            select_key = extras.getString("select_key");
            id_listshow = extras.getString("id_primary");

            String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
            db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
            String query_read = "SELECT * FROM memopad WHERE id = '" + id_listshow + "'";
            System.out.println(query_read);

            Cursor db_row = db.rawQuery(query_read,null);

            int id = 0;
            String keyword = "";
            String memo = "";
            Toast toast_read;
            String category = "";

            while (db_row.moveToNext()){
                key_flag = 1;
                int index_id = db_row.getColumnIndex("id");
                int index_keyword = db_row.getColumnIndex("keyword");
                int index_memo = db_row.getColumnIndex("memo");
                int index_category = db_row.getColumnIndex("category");
                id = db_row.getInt(index_id);
                keyword = db_row.getString(index_keyword);
                memo = db_row.getString(index_memo);
                category = db_row.getString(index_category);
            }

            //intのidをString変換
            String id_str = String.valueOf(id);

            //カテゴリに数字をあてる
            if(category.equals("tops")){
                index = 0;
            }
            else if (category.equals("outer")){
                index = 1;
            }
            else if (category.equals("bottoms")){
                index = 2;
            }
            else if (category.equals("onepiece")){
                index = 3;
            }
            else if (category.equals("shoes")){
                index = 4;
            }
            else if (category.equals("bag")){
                index = 5;
            }
            else if (category.equals("komono")){
                index = 6;
            }
            else {
                index = 4;
            }
            //カテゴリの初期値
            spkey.setSelection(index);

            //一覧から取得した主キーを基にキーワードとメモ表示
            ekey.setText(keyword);
            et.setText(memo);

            //Toastで表示
            if(key_flag == 0) {
                toast_read = Toast.makeText(this,
                        "指定されたキーはありません", Toast.LENGTH_SHORT);
                toast_read.show();
            }
            else {
                toast_read = Toast.makeText(this,
                        "<" + keyword + ">の内容を読み込みました", Toast.LENGTH_SHORT);
                toast_read.show();
            }
            key_flag = 0;
        }
    }

    public void functionKeyList(View v){
        //「一覧」のSQL
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        String query_list = "SELECT * FROM memopad";
        System.out.println(query_list);

        Cursor db_row = db.rawQuery(query_list,null);
        System.out.println(db_row);

        String keyword = "";
        String write_date = "";

        //ListShow.javaで一覧表示するためのデータ格納
        String id_continue = "";
        String keyword_continue = "";
        String keywordanddate_continue = "";

        //,区切りのデータ作成 id,keyword,memo,write_date
        while (db_row.moveToNext()){
            int index_id = db_row.getColumnIndex("id");
            int index_keyword = db_row.getColumnIndex("keyword");
            int index_write_date = db_row.getColumnIndex("write_date");
            int id = db_row.getInt(index_id);
            keyword = db_row.getString(index_keyword);
            write_date = db_row.getString(index_write_date);

            //id(int)をString変換/
            String id_str = String.valueOf(id);

            //ID
            if(id_continue != ""){
                id_continue += "," + id_str;
            }else {
                id_continue += id_str;
            }

            //キーワード
            if(keyword_continue != ""){
                keyword_continue += "," + keyword;
            }else {
                keyword_continue += keyword;
            }

            //キーワード＋日付
            if(keywordanddate_continue != ""){
                keywordanddate_continue += "," + keyword + "    " + write_date;
            }else {
                keywordanddate_continue += keyword + "    " + write_date;
            }
        }

        //ListViewアクティビティを起動
        Intent result_act = new Intent(MainActivity.this, ListShow.class);
        result_act.putExtra("id_continue",id_continue);
        result_act.putExtra("keywordanddate_continue",keywordanddate_continue);
        startActivity(result_act);
    }

    //「保存」(書き込み)のSQL
    public void functionKeyWrite(View v){
        //「保存」のSQL
        String key = ekey.getText().toString();
        String text = et.getText().toString();
//        String keyc = ckey.getText().toString();

        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        write_dateStr = now_date();
        String query_read = "SELECT * FROM memopad WHERE keyword = '" + key + "'";
        String query_insert = "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('" + key + "','" + text + "','" + write_dateStr + "','" + keyc + "')";

        Cursor db_row = db.rawQuery(query_read,null);


        Toast toast_save;
        Toast toast_notsave;

        //Toastで表示
        toast_save = Toast.makeText(this,
                key + "をキーに書き込みました", Toast.LENGTH_SHORT);
        toast_notsave = Toast.makeText(this,
                key + "はすでに存在します", Toast.LENGTH_SHORT);


        if (db_row.moveToFirst()){
            toast_notsave.show();
        }
        else{
            db.execSQL(query_insert);
            toast_save.show();
//            System.out.println(query_insert);
        }
        key_flag = 0;
    }

    //本文クリア
    public void functionKeyClear(View v){
        //「クリア」のSQL

        et.getEditableText().clear();
    }

    //削除
    public void functionKeyDelete(View v){
        //「削除」のSQL
        String key = ekey.getText().toString();
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        db2 = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        String query_read = "SELECT * FROM memopad WHERE keyword = '" + key + "'";
        Cursor db_row = db.rawQuery(query_read,null);

        while (db_row.moveToNext()){
            key_flag = 1;
            ekey.getEditableText().clear();
            et.getEditableText().clear();
        }

        String query_delete = "DELETE FROM memopad WHERE keyword = '" + key + "'";
        db2.execSQL(query_delete);

        Toast toast_delete;

        //Toastで表示
        if(key_flag == 0) {
            toast_delete = Toast.makeText(this,
                    "指定されたキーはありません", Toast.LENGTH_SHORT);
            toast_delete.show();
        }
        else {
            toast_delete = Toast.makeText(this,
                    key + "を削除しました", Toast.LENGTH_SHORT);
            toast_delete.show();
        }

        key_flag = 0;
    }

    //更新のSQL
    public void functionKeyUpdate(View KeyUpdate){
        String key = ekey.getText().toString();
        String text = et.getText().toString();
//        String keyc = ckey.getText().toString();

        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);
        write_dateStr = now_date();
        String query_read = "SELECT * FROM memopad WHERE keyword = '" + key + "'";
        String query_update = "UPDATE memopad SET memo = '" + text + "', write_date = '" + write_dateStr +"', category = '" + keyc +"' WHERE keyword = '" + key +  "'";
        Cursor db_row = db.rawQuery(query_read,null);


        Toast toast_update;
        Toast toast_notupdate;

        //Toastで表示
        toast_update = Toast.makeText(this,
                key + "を更新しました", Toast.LENGTH_SHORT);
        toast_notupdate = Toast.makeText(this,
                "指定されたキーはありません", Toast.LENGTH_SHORT);


        if (db_row.moveToFirst()){
            db.execSQL(query_update);
            toast_update.show();
        }
        else{
            toast_notupdate.show();
//            System.out.println(query_insert);
        }
        key_flag = 0;
    }

    //初期にデータベース動かすコード
    private void first_database(){
        //データベースを作成
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr,null);

        //テーブル作成用のクエリ文
        String query_table1 = "DROP TABLE IF EXISTS memopad";
        String query_table2 = "CREATE TABLE memopad(id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "keyword TEXT,memo TEXT,write_date TEXT, category TEXT)";

        //テーブルの作成
        db.execSQL(query_table1);
        db.execSQL(query_table2);

        //レコード追加
        write_dateStr = now_date();//本日日付取得
        String query_record_set[] = {
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('パーカー','白、GU','" + write_dateStr +"', 'tops')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('ニットスウェット','白、spiralgirl','" + write_dateStr +"', 'tops')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('スニーカー','黒、Reebok','" + write_dateStr +"', 'shoes')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('ニットワンピ','グレー、spiralgirl','" + write_dateStr +"', 'onepiece')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('ダウン','黒、革、spiralgirl','" + write_dateStr +"', 'outer')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('マーメイドスカート','黒、GRL','" + write_dateStr +"', 'bottoms')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('リュック','黒、不明','" + write_dateStr +"', 'bag')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('マフラー','チェック柄、妹からのプレゼント','" + write_dateStr +"', 'komono')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('手袋','チェック柄、友達からのプレゼント','" + write_dateStr +"', 'komono')",
                "INSERT INTO memopad(keyword,memo,write_date,category) VALUES('スキニー','黒、GU','" + write_dateStr +"', 'bottoms')"
        };

        for (int i=0; i<query_record_set.length; i++){
            db.execSQL(query_record_set[i]);
        }
    }



    //本日の日付を返すメソッド
    private String now_date(){
        //現在日取得
        Date today = new Date();

        //Calendarクラスオブジェクト生成
        Calendar cal = Calendar.getInstance();

        //Calendarオブジェクトに現在日付設定
        cal.setTime(today);

        //年月日時分秒所得
        int yy = cal.get(Calendar.YEAR);
        int mm = cal.get(Calendar.MONTH) + 1;
        int dd = cal.get(Calendar.DATE);
        int hour = cal.get(Calendar.HOUR);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);

        String now_dateStr = yy + "/" + mm + "/" + dd + " " + hour + ":" + minute + ":" + second;

        return now_dateStr;
    }
}
```

ListShow.java
```java=
package nhs00402.hal.ac.mylibrary2;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Intent;
import android.widget.Spinner;

public class ListShow extends AppCompatActivity{
    private TextView List_title;
    private ListView List_View;
    String[] listKey;
    String[] id_primary;
    String[] keywordanddate;
    private TextView aTextView;
    private Spinner aSpinner;
    String ss = "";
    private String[] listStrings = {
            "tops", "outer", "bottoms", "onepiece",
            "shoes", "bag", "komonno"
    };
    SQLiteDatabase db;
    String[] selectlist;
    int index_id_p;
    int id_p;
    String keyword = "";

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view);

        //IDから目的のウィジェットを得る
        List_title = (TextView)findViewById(R.id.mylistTitle);
        List_View= (ListView)findViewById(R.id.myListView);

//        aTextView = (TextView)findViewById(R.id.myTextView);
        aSpinner = (Spinner)findViewById(R.id.mySpinner);


        ArrayAdapter<String> myAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listStrings);
        aSpinner.setAdapter(myAdapter);

        aSpinner.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
                        Spinner spinner = (Spinner) parent;
                        ss = (String) spinner.getSelectedItem();
//                        aTextView.setText(String.format(" %s selected", ss));
                    }

                    public void onNothingSelected(AdapterView<?> parent){

                    }
                }
        );


        //インテントからキーを取得
        Bundle extras = getIntent().getExtras();
        if(extras != null){
            String id_continue = extras.getString("id_continue");
            String keywordanddate_continue = extras.getString("keywordanddate_continue");
            id_primary = id_continue.split(",");
            keywordanddate = keywordanddate_continue.split(",");
        }

        //リストに表示する名称

        //ヘッダ設定
        String head_title = "メモ一覧(" + keywordanddate.length + "件)";
        List_title.setText(head_title);

        //リストアダプタを作成
        ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(
                this,android.R.layout.simple_list_item_1,keywordanddate);

        //リストアダプタをリストビューにセット
        List_View.setAdapter(myAdapter2);

        //リスト選択処理
        List_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(
                    AdapterView<?> parent,View v,int position, long id){
                Log.d("onItemClick","position:" + String.valueOf(position));
                String select_key = id_primary[position];
                //int listshow_flag = 1;

                //ListShowアクティビティを起動
                Intent result_act = new Intent(ListShow.this, MainActivity.class);
                result_act.putExtra("select_key",select_key);
                result_act.putExtra("id_primary",id_primary[position]);
                startActivity(result_act);
            }
        });
    }

    public void functionKeySelect(View v) {
        //「一覧」のSQL
        String dbStr = "data/data/" + getPackageName() + "/nhs00650db";
        db = SQLiteDatabase.openOrCreateDatabase(dbStr, null);
        String query_list = "SELECT * FROM memopad WHERE category = '" + ss + "'";
        System.out.println(query_list);

        Cursor db_row = db.rawQuery(query_list, null);
        System.out.println(db_row);


        String write_date = "";

        //ListShow.javaで一覧表示するためのデータ格納
        String id_continue = "";
        String keyword_continue = "";
        String keywordanddate_continue = "";

        //,区切りのデータ作成 id,keyword,memo,write_date
        while (db_row.moveToNext()) {
            index_id_p = db_row.getColumnIndex("id");
            int index_keyword = db_row.getColumnIndex("keyword");
            int index_write_date = db_row.getColumnIndex("write_date");
            id_p = db_row.getInt(index_id_p);
            keyword = db_row.getString(index_keyword);
            write_date = db_row.getString(index_write_date);

            //id(int)をString変換
            String id_str = String.valueOf(id_p);

            //ID
            if (id_continue != "") {
                id_continue += "," + id_str;
            } else {
                id_continue += id_str;
            }


            //キーワード
            if (keyword_continue != "") {
                keyword_continue += "," + keyword;
            } else {
                keyword_continue += keyword;
            }

            //キーワード＋日付
            if (keywordanddate_continue != "") {
                keywordanddate_continue += "," + keyword + "    " + write_date;
            } else {
                keywordanddate_continue += keyword + "    " + write_date;
            }

            id_primary = id_continue.split(",");

        }


        selectlist = keywordanddate_continue.split(",");

        String head_title;
        if (db_row.moveToFirst()){
            head_title = ss +"一覧(" + selectlist.length + "件)";
        }
        else {
            head_title = ss +"一覧(0件)";
        }
        List_title.setText(head_title);

        ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(
                this,android.R.layout.simple_list_item_1,selectlist);

        //リストアダプタをリストビューにセット
        List_View.setAdapter(myAdapter2);

        List_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(
                    AdapterView<?> parent,View v,int position, long id){
                Log.d("onItemClick","position:" + String.valueOf(position));
                String select_key = id_primary[position];

                //ListShowアクティビティを起動
                Intent result_act = new Intent(ListShow.this, MainActivity.class);
                result_act.putExtra("select_key",select_key);
                result_act.putExtra("id_primary",id_primary[position]);
                startActivity(result_act);
            }
        });


    }

    //ボタンの処理
    public void buttonMethod(View myButton){
        Intent result_act = new Intent(ListShow.this, MainActivity.class);
        startActivity(result_act);
    }
}
```


## 雑談 (0→やまぴ 1→みや 2→やすい 3→りょうくん 4→アミカ 5→やの 6→山田)












---
<span style="color: #ff3333">aaa</span>
<span style="text-decoration: underline">aaa</span>