簡體   English   中英

Dao Room 數據庫無法訪問

[英]Dao Room database no access

所以我制作了這個數據庫,出於某種原因,我收到一條錯誤消息: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. 日志說錯誤在: wordList = (ArrayList<Note>) wDb.noteDao().getAllNotes(); ,但我看不出我做錯了什么?

列表活動.java

    private NoteDatabase wDb;
    ArrayList<Note> wordList;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        s1 = getResources().getStringArray(R.array.PL);//Kald denne først
        startService(new Intent(ListActivity.this,WordLeanerService.class).putExtra("inputExtra", s1));
        setupConnectionToWLservice();

        LoadData(); //Load SharedPreferences
        setContentView(R.layout.activity_main);
        s2 = getResources().getStringArray(R.array.DC);
        s3 = getResources().getStringArray(R.array.DC2);

        recyclerView = findViewById(R.id.recyclerView);
        Exit = findViewById(R.id.CloseApp);
        editSearch = findViewById(R.id.EditText);
        searchBtn = findViewById(R.id.search_button);
        getData(); //get set data from EditActivity and set Arrays

        wDb = NoteDatabase.getInstance(getApplicationContext());
        wordList = (ArrayList<Note>) wDb.noteDao().getAllNotes();
        if(wordList.isEmpty()){
            for (int i = 0; i < images.length; i++) {
                Note nWord = new Note(s1[i], s3[i], s2[i], images[i], items[i], Notes[i]);
                wDb.noteDao().insert(nWord);
            }
        }
    }

筆記.java

package com.example.word_learner_app;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName = "note_table")
public class Note {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "wordTitle")
    private String title;
    @ColumnInfo(name = "description")
    private String description;
    @ColumnInfo(name = "prounciation")
    private String prounciation;
    @ColumnInfo(name = "image")
    private int Image;
    @ColumnInfo(name = "rating")
    private String rating;
    @ColumnInfo(name = "notes")
    private String notes;

    public Note(String title, String description, String prounciation, int Image, String rating, String notes) {
        this.title = title;
        this.description = description;
        this.prounciation = prounciation;
        this.Image = Image;
        this.rating = rating;
        this.notes = notes;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getProunciation() {
        return prounciation;
    }

    public int getImage() {
        return Image;
    }

    public String getRating() {
        return rating;
    }

    public String getNotes() {
        return notes;
    }
}

NoteDao.java

package com.example.word_learner_app;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao
public interface NoteDao {
    @Insert
    void insert(Note note);

    @Update
    void update(Note note);

    @Delete
    void delete(Note note);

    @Query("SELECT * FROM note_table")
    List<Note> getAllNotes();
}

注意數據庫.java

package com.example.word_learner_app;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

@Database(entities = {Note.class}, version = 1, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {

    private static NoteDatabase instance;

    public abstract NoteDao noteDao();

    public static synchronized NoteDatabase getInstance(Context contexte){
        if(instance == null){
            instance = Room.databaseBuilder(contexte.getApplicationContext(),
                    NoteDatabase.class, "note_database")
                    .fallbackToDestructiveMigration()
                    .build();
        }
        return instance;
    }
}

邏輯貓

2020-03-27 16:40:06.697 18007-18007/? E/ord_learner_ap: Unknown bits set in runtime_flags: 0x8000
2020-03-27 16:40:08.226 18007-18007/com.example.word_learner_app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.word_learner_app, PID: 18007
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.word_learner_app/com.example.word_learner_app.ListActivity}: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:267)
        at androidx.room.RoomDatabase.query(RoomDatabase.java:323)
        at androidx.room.util.DBUtil.query(DBUtil.java:83)
        at com.example.word_learner_app.NoteDao_Impl.getAllNotes(NoteDao_Impl.java:158)
        at com.example.word_learner_app.ListActivity.onCreate(ListActivity.java:67)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 

您試圖做的是在 Android 中未經授權,您試圖從MainThread獲取數據庫中的數據,這可能會導致應用程序凍結。 這就是為什么建議使用Coroutines來完成這些功能的原因。

編輯:在 Java 中,您可以像在此代碼實驗室中一樣使用回調

使用allowMainThreadQueries()允許主線程查詢房間默認情況下標志為false否則你需要插入后台線程。

因此,要同步插入數據,請將其與構建器一起使用。

instance = Room.databaseBuilder(contexte.getApplicationContext(),
                    NoteDatabase.class, "note_database")
                    .fallbackToDestructiveMigration()
                    .allowMainThreadQueries() // this allows u to build in main thread
                    .build();

編輯

但是正如@CommonsWare 建議嘗試使用后台線程插入可能使用Rx / Executors / AsyncTasks for Kotlin 您可以使用Coroutines 由於主線程插入可能會凍結 UI

還有@看到這個

您需要在后台線程中執行您的操作。 將結果發布到 UI 線程

  • 您可以使用 Async task/Rx java/Kotlin Coroutines 實現此目的

不建議在主線程中運行數據庫操作,但您可以使用 allowMainThreadQueries() 訪問主線程上的數據庫

MyApp.database =  Room.databaseBuilder(this, AppDatabase::class.java, "MyDatabase").allowMainThreadQueries().build()

您正在嘗試在主線程中訪問 Room 數據庫,這就是為什么您得到java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. .

每當您執行具有不確定性或長時間的操作時,您必須在 Worker(后台)線程而不是主線程中執行。

有幾種方法可以執行后台線程,例如AsyncTaskExecutors

注意AsyncTask從 android R 開始被棄用。

在您提供的代碼中,您確實訪問了數據庫幾次(獲取所有筆記並將筆記插入數據庫),因此我將使用Executors修復它們,特別是使用ExecutorService

您也可以考慮使用LiveData異步返回數據庫列表,它可以免費處理所有后台線程。

LoadNoteListListener創建為每當列表從數據庫返回時觸發,因此現在是時候使用onNotesListLoaded()回調處理主線程中的列表了。

class MainActivity extends AppCompatActivity implements LoadNoteListListener {

    private NoteDatabase wDb;
    ArrayList<Note> wordList;

    private static Executor executor = Executors.newSingleThreadExecutor(); // to run DB access operations in background thread

    // Listen when the list of notes are returned back from Room database
    public interface LoadNoteListListener {
        void onNotesListLoaded(ArrayList<Note> notes);
    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        s1 = getResources().getStringArray(R.array.PL);//Kald denne først
        startService(new Intent(ListActivity.this,WordLeanerService.class).putExtra("inputExtra", s1));
        setupConnectionToWLservice();

        LoadData(); //Load SharedPreferences
        setContentView(R.layout.activity_main);
        s2 = getResources().getStringArray(R.array.DC);
        s3 = getResources().getStringArray(R.array.DC2);

        recyclerView = findViewById(R.id.recyclerView);
        Exit = findViewById(R.id.CloseApp);
        editSearch = findViewById(R.id.EditText);
        searchBtn = findViewById(R.id.search_button);
        getData(); //get set data from EditActivity and set Arrays

        wDb = NoteDatabase.getInstance(getApplicationContext());

        getAllNotes(this);

    }



    public void getAllNotes(LoadNoteListListener listener) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                listener.onNotesListLoaded((ArrayList<Note>) wDb.noteDao().getAllNotes());
            }
        });
    }



    @Override
    void onNotesListLoaded(ArrayList<Note> notes) {
        wordList = notes;
        if(wordList.isEmpty()){
            for (int i = 0; i < images.length; i++) {
                Note nWord = new Note(s1[i], s3[i], s2[i], images[i], items[i], Notes[i]);
                insertNote(nWord);
            }
        }       
    }


    public void insertNote(Note note) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                wDb.noteDao().insertNote(note);
            }
        });
    }

    ....
}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM