Android Studio 如何用自定义列表而不是所有对象填充LiveData?

yeotifhr  于 2022-11-16  发布在  Android
关注(0)|答案(1)|浏览(136)

我对Room有一些问题,我有点迷失了正确的方法。我正在尝试创建一个RecyclerView,显示所有拥有特定termId的课程。
在“活动”中调用查询时,它给出一个错误:

public class RelatedCourses extends AppCompatActivity {
    private TermDao termDao;
    List<Course> coursesInTerm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        int termId = Integer.parseInt(intent.getStringExtra("EXTRA_ID"));
        coursesInTerm = termDao.getRelatedCourses(termId);
        setContentView(R.layout.activity_related_courses);

        CourseViewModel courseViewModel;

    }
}

2022-03-04 20:18:30.260 23510-23510/com.example.architectureexample E/AndroidRuntime: FATAL 

EXCEPTION: main
    Process: com.example.architectureexample, PID: 23510
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.architectureexample/com.example.wgu_student_scheduler.Activities.RelatedCourses}: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.List com.example.wgu_student_scheduler.Database.TermDao.getRelatedCourses(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.List com.example.wgu_student_scheduler.Database.TermDao.getRelatedCourses(int)' on a null object reference
        at com.example.wgu_student_scheduler.Activities.RelatedCourses.onCreate(RelatedCourses.java:31)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

在我的CourseDao中,它是最后一个Query:

@Dao
public interface CourseDao {

    @Insert
    void insert(Course course);

    @Update
    void update(Course course);

    @Delete
    void delete(Course course);

    @Query("DELETE FROM course_table")
    void deleteAllCourses();

    @Query("SELECT * FROM course_table ORDER BY startDate ASC")
    LiveData<List<Course>> getAllCourses();

    @Query("SELECT * FROM course_table WHERE termId = :termId")
    LiveData<List<Course>> getCoursesInTerm(int termId);
}

我需要将它添加到课程库中吗?我不确定如何在参数中使用变量来实现它,如果是这样的话...

public class CourseRepository {

    private CourseDao courseDao;
    private LiveData<List<Course>> allCourses;

    public CourseRepository(Application application) {
        Database database = Database.getInstance(application);
        courseDao = database.courseDao();

        allCourses = courseDao.getAllCourses();
    }

    public void insert(Course course) {
        new InsertCourseAsyncTask(courseDao).execute(course);
    }

    public void update(Course course) {
        new UpdateCourseAsyncTask(courseDao).execute(course);
    }

    public void delete(Course course) {
        new DeleteCourseAsyncTask(courseDao).execute(course);
    }

    public void deleteAllCourses() {
        new DeleteCourseAsyncTask(courseDao).execute();
    }

    public LiveData<List<Course>> getAllCourses() {
        return allCourses;
    }

    private static class InsertCourseAsyncTask extends AsyncTask<Course, Void,Void> {
        private CourseDao courseDao;

        private InsertCourseAsyncTask(CourseDao courseDao) {
            this.courseDao = courseDao;
        }

        @Override
        protected Void doInBackground(Course... courses) {
            courseDao.insert(courses[0]);
            return null;
        }
    }

    private static class UpdateCourseAsyncTask extends AsyncTask<Course, Void,Void> {
        private CourseDao courseDao;

        private UpdateCourseAsyncTask(CourseDao courseDao) {
            this.courseDao = courseDao;
        }

        @Override
        protected Void doInBackground(Course... courses) {
            courseDao.update(courses[0]);
            return null;
        }
    }

    private static class DeleteCourseAsyncTask extends AsyncTask<Course, Void,Void> {
        private CourseDao courseDao;

        private DeleteCourseAsyncTask(CourseDao courseDao) {
            this.courseDao = courseDao;
        }

        @Override
        protected Void doInBackground(Course... courses) {
            courseDao.delete(courses[0]);
            return null;
        }
    }

    private static class DeleteAllCoursesAsyncTask extends AsyncTask<Void, Void,Void> {
        private CourseDao courseDao;

        private DeleteAllCoursesAsyncTask(CourseDao courseDao) {
            this.courseDao = courseDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            courseDao.deleteAllCourses();
            return null;
        }
    }
}

或者,这是需要添加到ViewModel类中以支持添加到recyclerview中的内容吗?

public class CourseViewModel extends AndroidViewModel {

    private CourseRepository repository;
    private LiveData<List<Course>> allCourses;

    public CourseViewModel(@NonNull Application application) {
        super(application);
        repository = new CourseRepository(application);
        allCourses = repository.getAllCourses();
    }

    public void insert(Course course) {
        repository.insert(course);
    }

    public void update(Course course) {
        repository.update(course);
    }

    public void delete(Course course) {
        repository.delete(course);
    }

    public void deleteAllCourses() {
        repository.deleteAllCourses();
    }

    public LiveData<List<Course>> getAllCourses() {
        return allCourses;
    }

这是我第一次与Room互动,对我来说有点困惑。我很感激这段时间。

cwxwcias

cwxwcias1#

您正在RelatedCoursesonCreate()中的termDao上调用getRelatedCourses(termId),而没有初始化termDao
这就是导致错误Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.List com.example.wgu_student_scheduler.Database.TermDao.getRelatedCourses(int)' on a null object reference的原因。

相关问题