roomの作成

daoは追加がいる
This commit is contained in:
nemukemo 2024-06-18 14:07:39 +09:00
parent aa189688d3
commit e64b2f6c11
9 changed files with 138 additions and 142 deletions

View File

@ -0,0 +1,12 @@
package com.example.oplogy;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
@Database(entities = {QuestionnaireForm.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
// データベースにアクセスするためのメソッドを提供する
public abstract QuestionnaireFormDao questionnaireFormDao();
}

View File

@ -0,0 +1,39 @@
package com.example.oplogy;
import androidx.room.TypeConverter;
import com.google.firebase.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Converters {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.JAPAN);
// タイムスタンプを文字列(yyyy-mm-dd,日時)に変換
@TypeConverter
public static List<String> fromTimestampList(List<Timestamp> timestamps) {
List<String> strings = new ArrayList<>();
for (Timestamp timestamp : timestamps) {
strings.add(format.format(timestamp.toDate()));
}
return strings;
}
@TypeConverter
public static List<Timestamp> toTimestampList(List<String> strings) {
List<Timestamp> timestamps = new ArrayList<>();
for (String string : strings) {
try {
Date date = format.parse(string);
timestamps.add(new Timestamp(date));
} catch (Exception e) {
e.printStackTrace();
}
}
return timestamps;
}
}

View File

@ -1,7 +1,13 @@
package com.example.oplogy;
import static android.content.Context.MODE_PRIVATE;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.room.Room;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
@ -16,28 +22,58 @@ import java.util.Map;
public class FirestoreReception {
private FirebaseFirestore db;
private Context context;
private AppDatabase appDatabase;
public FirestoreReception() {
public FirestoreReception(Context context) {
db = FirebaseFirestore.getInstance();
this.context = context;
this.appDatabase = Room.databaseBuilder(context, AppDatabase.class, "FormsRoom").build();
}
//ClassIdを引数にデータの作成を行う
public void getDocumentsByClassId(int classId) {
CollectionReference collectionRef = db.collection("QuestionnaireForms");
SharedPreferences sharedPreferences = context.getSharedPreferences("FirestoreData", MODE_PRIVATE);
// classIdが引数のものを取得する
collectionRef.whereEqualTo("classId", classId).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
// データの取得に成功した場合
for (QueryDocumentSnapshot document : task.getResult()) {
// すでに取得済みのドキュメントは除外
if (sharedPreferences.getBoolean(document.getId(), false)) {
Log.w("FirestoreReception", "すでに取得済みのドキュメントです.");
continue;
}
// firestoreのドキュメントのデータを取得
Map<String, Object> data = document.getData();
// デバッグ用のログ出力
// Log.d("FirestoreReception", "Document ID: " + document.getId());
Log.d("FirestoreReception", "Data: " + data);
// データをエンティティクラスのインスタンスに変換
QuestionnaireForm form = new QuestionnaireForm();
form.classId = Integer.parseInt(data.get("classId").toString());
form.patronName = data.get("patronName").toString();
form.address = data.get("address").toString();
form.firstDay = Converters.fromTimestampList((List<Timestamp>) data.get("firstDay")).toString();
form.studentNumber = Integer.parseInt(data.get("studentNumber").toString());
form.childName = data.get("childName").toString();
form.thirdDay = Converters.fromTimestampList((List<Timestamp>) data.get("thirdDay")).toString();
form.secondDay = Converters.fromTimestampList((List<Timestamp>) data.get("secondDay")).toString();
// データベースに保存
new Thread(new Runnable() {
@Override
public void run() {
appDatabase.questionnaireFormDao().insertAll(form);
Log.w("FirestoreReception", "成功.");
}
}).start();
// ドキュメントのIDを保存
// すでに取得済みのドキュメントは再度取得しないようにする
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(document.getId(), true);
editor.apply();
}
} else {
Log.w("FirestoreReception", "Error getting documents.", task.getException());

View File

@ -1,26 +0,0 @@
package com.example.oplogy;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import java.util.Map;
@Entity(
foreignKeys = @ForeignKey(entity = SetupTable.class,//外部キーとしてSetupTableクラスを指定
parentColumns = "id",//親クラスのidと結びつけ
childColumns = "data",//子クラスのprofileIdと結びつけ
onDelete = ForeignKey.CASCADE//親クラスが削除されたら子クラスも削除
)
)
public class FormTable {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "data")
public Map<String, Object> data;
// Getters and setters if needed
}

View File

@ -65,7 +65,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
// firestoreの受信関連の宣言
db = FirebaseFirestore.getInstance();
firestoreReception = new FirestoreReception();
firestoreReception = new FirestoreReception(this);
// 受信するメソッドの呼び出し
firestoreReception.getDocumentsByClassId(100);
@ -85,12 +85,12 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
}
// セットアップのクリック処理
if(view == setUp){
imageSetup.setImageResource(R.drawable.ischecked_uuid);
Intent toSetup = new Intent(MainActivity.this,SetupActivity.class);
startActivity(toSetup);
}
// if(view == setUp){
// imageSetup.setImageResource(R.drawable.ischecked_uuid);
// Intent toSetup = new Intent(MainActivity.this,SetupActivity.class);
// startActivity(toSetup);
//
// }
// ルート作成のクリック処理
if(view == root){
imageRoot.setImageResource(R.drawable.pin);

View File

@ -0,0 +1,20 @@
package com.example.oplogy;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class QuestionnaireForm {
//主キー
@PrimaryKey(autoGenerate = true)
public int id;
//その他フィールド
public int classId;
public String patronName;
public String address;
public String firstDay;
public int studentNumber;
public String childName;
public String thirdDay;
public String secondDay;
}

View File

@ -0,0 +1,17 @@
package com.example.oplogy;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface QuestionnaireFormDao {
@Query("SELECT * FROM QuestionnaireForm")
List<QuestionnaireForm> getAll();
// このメソッドはQuestionnaireFormのリストを受け取りそれらをデータベースに挿入します
@Insert
void insertAll(QuestionnaireForm... questionnaireForms);
}

View File

@ -1,14 +0,0 @@
package com.example.oplogy;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class SetupActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup);
}
}

View File

@ -1,88 +0,0 @@
package com.example.oplogy;
import androidx.room.ColumnInfo;
import androidx.room.Embedded;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import androidx.room.Relation;
import java.util.Date;
import java.util.List;
@Entity(tableName = "teacher_table")
public class SetupTable {
//フィールド
@PrimaryKey()
public int classId;
@ColumnInfo(name = "teacher_name")
public String teacherName;
@ColumnInfo(name = "startpoint")
public String startpoint;
@ColumnInfo(name = "subject")
public String startTime;
@ColumnInfo(name = "end_time")
public String endTime;
@ColumnInfo(name = "break_time")
public String breakTime;
@ColumnInfo(name = "total_students")
public int totalStudents;
//コンストラクタ
public SetupTable(int classId,String startpoint , String teacherName, String startTime, String endTime, String breakTime, int totalStudents) {
this.classId = classId;
this.startpoint = startpoint;
this.teacherName = teacherName;
this.startTime = startTime;
this.endTime = endTime;
this.breakTime = breakTime;
this.totalStudents = totalStudents;
}
//ゲッター
public int getClassId() {
return classId;
}
public String getTeacherName() {
return teacherName;
}
public String getStartTime() {
return startTime;
}
public String getEndTime() {
return endTime;
}
public String getBreakTime() {
return breakTime;
}
public int getTotalStudents() {
return totalStudents;
}
public String getStartpoint() {
return startpoint;
}
//セッター
public void setClassId(int classId) {
this.classId = classId;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public void setBreakTime(String breakTime) {
this.breakTime = breakTime;
}
public void setTotalStudents(int totalStudents) {
this.totalStudents = totalStudents;
}
public void setStartpoint(String startpoint) {
this.startpoint = startpoint;
}
}