teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

貼り付けるコードを間違えた

2024/11/29 04:24

投稿

ta.ta.ta.
ta.ta.ta.

スコア1

title CHANGED
File without changes
body CHANGED
@@ -3,214 +3,196 @@
3
3
 
4
4
  ### 発生している問題・分からないこと
5
5
  androidstudioのjavaでSQliteに接続しようとしてるのですが、データベースがcloseのままでデータを入れることができません。keep database connections openというところ押したら接続できてデータが入ってることは確認できたのですが調べたところこれは根本解決になってないとのことだったので、誰がこの現象がわかる人教えてくれるとありがたいです。エラーは何も出でおらず接続時にエラー文を出すようにしてるのですが何も出ずエラーが一個もないことで困っています。
6
- ```java
7
- private void saveCheckTime(String checkinDate_data, String checkinTime_data, String checkoutDate_data, String checkoutTime_data) {
8
- SQLiteDatabase db = null; // db を try の外で宣言
9
- SQLiteStatement stmtInsert = null; // stmtInsert を try の外で宣言
10
6
 
11
- try {
12
- // 書き込み可能なデタベースを取得
7
+ ```これが全体コドです(main)java
13
- db = _helper.getWritableDatabase();
8
+ package com.example.attendance_management;
14
9
 
15
- // 新しいデータを挿入するSQL文
16
- String sqlInsert = "INSERT INTO worktimetable (checkindate, checkin, checkoutdate, checkout) VALUES (?, ?, ?, ?)";
17
- stmtInsert = db.compileStatement(sqlInsert); // 挿入用のSQL文を準備
18
-
19
- // データをバインド
20
- if (checkinDate_data.isEmpty()) {
21
- stmtInsert.bindNull(1); // checkindate に null を挿入
22
- stmtInsert.bindNull(2); // checkin 時間に null を挿入
23
- } else {
24
- stmtInsert.bindString(1, checkinDate_data);
25
- stmtInsert.bindString(2, checkinTime_data);
26
- }
27
-
28
- if (checkoutDate_data.isEmpty()) {
29
- stmtInsert.bindNull(3); // checkoutdate に null を挿入
30
- stmtInsert.bindNull(4); // checkout 時間に null を挿入
31
- } else {
32
- stmtInsert.bindString(3, checkoutDate_data);
33
- stmtInsert.bindString(4, checkoutTime_data);
34
- }
35
-
36
- stmtInsert.executeInsert(); // 挿入実行
37
-
38
- } catch (Exception e) {
39
- Log.e("DatabaseError", "Error occurred while accessing the database", e);
40
- } finally {
41
- // クローズ処理を必ず行う
42
- if (stmtInsert != null) {
43
- stmtInsert.close(); // stmtInsert のクローズ
44
- }
45
- if (db != null) {
46
- db.close(); // db のクローズ
47
- }
48
- }
49
- }
50
- ```
51
- ```これが全体コードです(main)
52
- package com.example.myapplication;
53
-
54
- import android.database.Cursor;
10
+ import android.content.Intent;
55
11
  import android.database.sqlite.SQLiteDatabase;
56
12
  import android.database.sqlite.SQLiteStatement;
57
13
  import android.os.Bundle;
14
+ import android.os.Handler;
58
15
  import android.util.Log;
59
16
  import android.view.View;
60
- import android.widget.AdapterView;
61
17
  import android.widget.Button;
62
- import android.widget.EditText;
63
- import android.widget.ListView;
64
18
  import android.widget.TextView;
65
- import android.widget.Toast;
66
19
 
67
20
  import androidx.appcompat.app.AppCompatActivity;
68
21
 
69
- import org.apache.poi.ss.usermodel.Row;
70
- import org.apache.poi.ss.usermodel.Sheet;
22
+ import java.text.SimpleDateFormat;
23
+ import java.util.Date;
71
- import org.apache.poi.ss.usermodel.Workbook;
24
+ import java.util.Locale;
72
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
73
25
 
74
- import java.io.File;
75
- import java.io.FileOutputStream;
76
- import java.io.IOException;
77
-
78
26
  public class MainActivity extends AppCompatActivity {
79
27
 
28
+ private com.example.attendance_management.DatabaseHelper databaseHelper; // データベースヘルパーのインスタンス
80
- private int _cocktailId = -1;
29
+ private TextView timeLabel;
81
- private String _cocktailName = "";
30
+ private Handler handler = new Handler();
31
+ private SimpleDateFormat displayFormat; // 表示用フォーマット
82
32
 
83
- private DatabaseHelper _helper;
33
+ private com.example.attendance_management.DatabaseHelper _helper; // DatabaseHelperインスタンス
84
34
 
85
35
  @Override
86
36
  protected void onCreate(Bundle savedInstanceState) {
87
37
  super.onCreate(savedInstanceState);
88
38
  setContentView(R.layout.activity_main);
39
+ _helper = new DatabaseHelper(MainActivity.this);
89
40
 
90
- ListView lvCocktail = findViewById(R.id.lvCocktail);
91
41
 
42
+ // DatabaseHelper インスタンスを初期化
92
- lvCocktail.setOnItemClickListener(new ListItemClickListener());
43
+ databaseHelper = new com.example.attendance_management.DatabaseHelper(this);
93
44
 
45
+ // TextViewのIDを取得
94
- _helper = new DatabaseHelper(MainActivity.this);
46
+ timeLabel = findViewById(R.id.timelabel);
95
- }
96
47
 
48
+ // フォーマットの設定
49
+ displayFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
97
50
 
98
- @Override
99
- protected void onDestroy(){
51
+ // menu1ボタンのIDを取得
100
- _helper.close();
101
- super.onDestroy();
52
+ Button menucalendar = findViewById(R.id.menu1);
53
+ Button menutotalsalary = findViewById(R.id.menu2);
54
+ Button menubasicin = findViewById(R.id.menu3);
55
+ Button checkinbutton = findViewById(R.id.checkin);
56
+ Button checkoutbutton = findViewById(R.id.checkout);
102
57
 
58
+ // ボタンが押されたときの処理
59
+ checkinbutton.setOnClickListener(new View.OnClickListener() {
103
- }
60
+ @Override
61
+ public void onClick(View v) {
62
+ // 現在時刻を取得
63
+ Date now = new Date();
104
64
 
105
- public void onSaveButtonClick(View view) {
106
- EditText etNote = findViewById(R.id.etNote);
65
+ // 日付の部分を取得 (yyyy-MM-dd)
66
+ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
107
- String note = etNote.getText().toString();
67
+ String checkinDate_data = dateFormat.format(now);
108
68
 
69
+ // 時刻の部分を取得 (HH:mm:ss)
70
+ SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
71
+ String checkinTime_data = timeFormat.format(now);
109
72
 
73
+ // データベースに保存
110
- SQLiteDatabase db = _helper.getWritableDatabase();
74
+ saveCheckTime(checkinDate_data, checkinTime_data, "", "");
75
+ }
76
+ });
111
77
 
78
+ // ボタンが押されたときの処理
112
- String sqlDelete = "DELETE FROM cocktailmemos WHERE _id = ?";
79
+ checkoutbutton.setOnClickListener(new View.OnClickListener() {
80
+ @Override
81
+ public void onClick(View v) {
82
+ // 現在時刻を取得
83
+ Date now = new Date();
113
84
 
85
+ // 日付の部分を取得 (yyyy-MM-dd)
86
+ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
114
- SQLiteStatement stmt = db.compileStatement(sqlDelete);
87
+ String checkoutDate_data = dateFormat.format(now);
115
88
 
116
- stmt.bindLong(1, _cocktailId);
89
+ // 時刻の部分を取得 (HH:mm:ss)
90
+ SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
91
+ String checkoutTime_data = timeFormat.format(now);
117
92
 
118
- stmt.executeUpdateDelete();
93
+ // データベースに保存
94
+ saveCheckTime("", "", checkoutDate_data, checkoutTime_data);
95
+ }
96
+ });
119
97
 
120
- String sqlInsert ="INSERT INTO cocktailmemos (_id, name, note) VALUES (?, ?, ?)";
121
98
 
99
+ // menu1ボタンにクリックリスナーを設定
100
+ menucalendar.setOnClickListener(new View.OnClickListener() {
101
+ @Override
102
+ public void onClick(View view) {
103
+ Intent intent = new Intent(MainActivity.this, calendar.class);
122
- stmt = db.compileStatement(sqlInsert);
104
+ startActivity(intent);
105
+ }
106
+ });
123
107
 
108
+ menutotalsalary.setOnClickListener(new View.OnClickListener() {
109
+ @Override
124
- stmt.bindLong(1, _cocktailId);
110
+ public void onClick(View view) {
125
- stmt.bindString(2, _cocktailName);
111
+ Intent intent = new Intent(MainActivity.this, totalsalary.class);
126
- stmt.bindString(3, note);
127
- stmt.executeInsert();
112
+ startActivity(intent);
113
+ }
114
+ });
128
115
 
116
+ menubasicin.setOnClickListener(new View.OnClickListener() {
117
+ @Override
118
+ public void onClick(View view) {
119
+ Intent intent = new Intent(MainActivity.this, basic_information.class);
129
- etNote.setText("");
120
+ startActivity(intent);
121
+ }
122
+ });
130
123
 
124
+ // Runnableを使って1秒ごとに時刻を更新
125
+ handler.post(updateTimeTask);
126
+ }
131
127
 
132
- TextView tvCocktailName = findViewById(R.id.tvCocktailName);
133
- tvCocktailName.setText(getString(R.string.tv_name));
134
128
 
135
- Button btnSave = findViewById(R.id.btnSave);
129
+ private Runnable updateTimeTask = new Runnable() {
136
- btnSave.setEnabled(false);
137
- }
138
-
139
- private class ListItemClickListener implements AdapterView.OnItemClickListener {
140
130
  @Override
141
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
131
+ public void run() {
132
+ // 現在の日時を取得
142
- _cocktailId = position;
133
+ Date now = new Date();
143
- _cocktailName = (String) parent.getItemAtPosition(position);
144
134
 
135
+ // 表示用の時刻をフォーマット
145
- TextView tvCocktailName = findViewById(R.id.tvCocktailName);
136
+ String currentTime = displayFormat.format(now);
146
- tvCocktailName.setText(_cocktailName);
137
+ timeLabel.setText(currentTime);
147
138
 
148
- Button btnSave = findViewById(R.id.btnSave);
139
+ // 1秒後に再実行
149
- btnSave.setEnabled(true);
140
+ handler.postDelayed(this, 1000);
141
+ }
142
+ };
150
143
 
144
+ @Override
151
- SQLiteDatabase db = _helper.getWritableDatabase();
145
+ protected void onDestroy() {
146
+ _helper.close();
147
+ super.onDestroy();
148
+ }
152
149
 
150
+ private void saveCheckTime(String checkinDate_data, String checkinTime_data, String checkoutDate_data, String checkoutTime_data) {
151
+ SQLiteDatabase db = null; // db を try の外で宣言
153
- String sql = "SELECT * FROM cocktailmemos WHERE _id = " + _cocktailId;
152
+ SQLiteStatement stmtInsert = null; // stmtInsert try の外で宣言
154
153
 
154
+ try {
155
+ // 書き込み可能なデータベースを取得
155
- Cursor cursor = db.rawQuery(sql, null);
156
+ db = _helper.getWritableDatabase();
156
157
 
157
- String note = "";
158
+ // 新しいデータを挿入するSQL文
159
+ String sqlInsert = "INSERT INTO worktimetable (checkindate, checkin, checkoutdate, checkout) VALUES (?, ?, ?, ?)";
160
+ stmtInsert = db.compileStatement(sqlInsert); // 挿入用のSQL文を準備
158
161
 
162
+ // データをバインド
159
- while(cursor.moveToNext()){
163
+ if (checkinDate_data.isEmpty()) {
164
+ stmtInsert.bindNull(1); // checkindate に null を挿入
165
+ stmtInsert.bindNull(2); // checkin 時間に null を挿入
166
+ } else {
160
- int idxNote = cursor.getColumnIndex("note");
167
+ stmtInsert.bindString(1, checkinDate_data);
168
+ stmtInsert.bindString(2, checkinTime_data);
169
+ }
161
170
 
171
+ if (checkoutDate_data.isEmpty()) {
172
+ stmtInsert.bindNull(3); // checkoutdate に null を挿入
173
+ stmtInsert.bindNull(4); // checkout 時間に null を挿入
174
+ } else {
162
- note = cursor.getString(idxNote);
175
+ stmtInsert.bindString(3, checkoutDate_data);
176
+ stmtInsert.bindString(4, checkoutTime_data);
163
177
  }
164
178
 
165
- EditText etNote = findViewById(R.id.etNote);
179
+ stmtInsert.executeInsert(); // 挿入実行
180
+
166
- etNote.setText(note);
181
+ } catch (Exception e) {
182
+ Log.e("DatabaseError", "Error occurred while accessing the database", e);
183
+ } finally {
184
+ // クローズ処理を必ず行う
185
+ if (stmtInsert != null) {
186
+ stmtInsert.close(); // stmtInsert のクローズ
187
+ }
188
+ if (db != null) {
189
+ db.close(); // db のクローズ
190
+ }
167
191
  }
168
192
  }
169
193
 
170
194
 
171
-
172
- public void exportDatabaseToExcel() {
173
- SQLiteDatabase db = _helper.getReadableDatabase();
174
- String sql = "SELECT * FROM cocktailmemos";
175
- Cursor cursor = db.rawQuery(sql, null);
176
-
177
- // Excelファイル作成
178
- Workbook workbook = new XSSFWorkbook();
179
- Sheet sheet = workbook.createSheet("Cocktail Memos");
180
-
181
- // ヘッダー行を作成
182
- Row headerRow = sheet.createRow(0);
183
- headerRow.createCell(0).setCellValue("_id");
184
- headerRow.createCell(1).setCellValue("Name");
185
- headerRow.createCell(2).setCellValue("Note");
186
-
187
- // データ行を作成
188
- int rowIndex = 1;
189
- while (cursor.moveToNext()) {
190
- Row row = sheet.createRow(rowIndex++);
191
-
192
- row.createCell(0).setCellValue(cursor.getInt(cursor.getColumnIndex("_id")));
193
- row.createCell(1).setCellValue(cursor.getString(cursor.getColumnIndex("name")));
194
- row.createCell(2).setCellValue(cursor.getString(cursor.getColumnIndex("note")));
195
- }
196
- cursor.close();
197
-
198
- // ファイル保存パスを指定
199
- File file = new File(getExternalFilesDir(null), "CocktailMemos.xlsx");
200
- try (FileOutputStream fos = new FileOutputStream(file)) {
201
- workbook.write(fos);
202
- workbook.close();
203
- } catch (IOException e) {
204
- e.printStackTrace();
205
- }
206
- Log.d("FilePath", "Excel file saved to: " + file.getAbsolutePath());
207
-
208
- // ファイル保存後の通知
209
- Toast.makeText(this, "Excel file exported: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
210
- }
211
-
212
195
  }
213
-
214
196
  ```
215
197
  ```(DatabaseHelper)
216
198
  package com.example.attendance_management;
@@ -272,7 +254,7 @@
272
254
  ```
273
255
  private static final int DATABASE_VERSION = 2;
274
256
  ```
275
- これを2にすることでカラムのエラーが治った
257
+ 2にすることでカラムのエラーが治った
276
258
 
277
259
  ### 補足
278
260
  特になし