---
# System prepended metadata

title: AN25 課題No.09
tags: [課題]

---

# AN25 課題No.09
###### 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/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="120dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyWrite"
                android:text="保存"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyClear"
                android:layout_width="120dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyClear"
                android:text="クリア"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyList"
                android:layout_width="120dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyList"
                android:text="一覧"
                android:textSize="20sp"
                />
            <Button
                android:id="@+id/KeyDelete"
                android:layout_width="120dp"
                android:layout_height="match_parent"
                android:onClick="functionKeyDelete"
                android:text="削除"
                android:textSize="20sp"
                />
        </TableRow>
    </TableLayout>

</LinearLayout>
```


listview.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"
    android:gravity="center"
    android:background="#ffffff"
    >

    <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="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="buttonMethod"
        />
</LinearLayout>
```


AndroidManifest.xml
```xml=
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="nhs00605.hal.ac.note_listview"
    android:targetSandboxVersion="2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="30" />

    <application
        android:allowBackup="true"
        android:appComponentFactory="androidx.core.app.CoreComponentFactory"
        android:debuggable="true"
        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="nhs00605.hal.ac.note_listview.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
```


MainActivity.java
```java=
package nhs00605.hal.ac.note_listview;

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;
    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);//keyを取得

        //↓は一度実効したあとコメントアウトしなおす
        //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() + "/nhs00605db";
            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;

            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");
                id = db_row.getInt(index_id);
                keyword = db_row.getString(index_keyword);
                memo = db_row.getString(index_memo);
            }

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

            //一覧から取得した主キーを基にキーワードとメモ表示
            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,
                        id_str + "の内容を読み込みました", Toast.LENGTH_SHORT);
                toast_read.show();
            }
            key_flag = 0;
        }
    }

    //while文を使ってsqlから配列にすればできる…？
    public void functionKeyList(View v){
        //「一覧」のSQL
        String dbStr = "data/data/" + getPackageName() + "/nhs00605db";
        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 dbStr = "data/data/" + getPackageName() + "/nhs00605db";
        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) VALUES('" + key + "','" + text + "','" + write_dateStr + "')";

        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() + "/nhs00605db";
        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;
    }

    //初期にデータベース動かすコード
    private void first_database(){
        //データベースを作成
        String dbStr = "data/data/" + getPackageName() + "/nhs00605db";
        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)";

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

        //レコード追加
        write_dateStr = now_date();//本日日付取得
        String query_record_set[] = {
                "INSERT INTO memopad(keyword,memo,write_date) VALUES('test01','テスト01','" + write_dateStr +"')",
                "INSERT INTO memopad(keyword,memo,write_date) VALUES('test02','テスト02','" + write_dateStr +"')",
                "INSERT INTO memopad(keyword,memo,write_date) VALUES('test03','テスト03','" + write_dateStr +"')"
        };

        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 nhs00605.hal.ac.note_listview;

import androidx.appcompat.app.AppCompatActivity;
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;

public class ListShow extends AppCompatActivity{
    private TextView List_title;
    private ListView List_View;
    String[] listKey;
    String[] id_primary;
    String[] keywordanddate;

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

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

        //インテントからキーを取得
        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> myAdapter = new ArrayAdapter<String>(
                this,android.R.layout.simple_list_item_1,keywordanddate);

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

        //リスト選択処理
        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 buttonMethod(View myButton){
        Intent result_act = new Intent(ListShow.this, MainActivity.class);
        startActivity(result_act);
    }
}
```

河原
まだ私作ってないから動くはしらない
動きました
mainactivity.javaが癖あるからそこだけちゃんと読んだほうがいい
ﾏﾆｱｯﾃﾖｶｯﾀ

ありがとうございます！！！！！

ありがとー！！！！！🙇‍♂️
