按ID,更新和返回值查找房间的实体

时间:2019-03-22 18:56:40

标签: android android-room

  

我已经使用改型,房间和空间获取并缓存了一系列程序   模型-视图-视图-模型模式。当每个项目为   单击后,将显示一个对话框片段,其中包含要填充的详细信息。的   这里的问题是我必须进行网络呼叫以添加新属性   实体,例如地名和会话列表。

     

我尝试通过传递ID从   适配器以使用序列化分段并将ID发送到视图   模型,以便存储库可以从那里访问它并执行数据库   使用ID查找和更新操作。

     

发送ID到片段代码:

   viewholder.itemView.setOnClickListener(v -> {
        ProgramDetailsFragment fragment = new ProgramDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.PROGRAM_DETAIL_KEY, programs);
        fragment.setArguments(bundle);
        fragment.setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Light_NoTitleBar_Fullscreen);
        fragment.show(((AppCompatActivity)context).getSupportFragmentManager(), "ProgramSessionsFragment");
    });
  

和片段中的内容已检索并发送到如下视图模型:

```
     private void set() {

        Bundle bundle = getArguments();
        programs = (Programs) bundle.getSerializable(Constants.PROGRAM_DETAIL_KEY);

        if (programs != null)
            progId = programs.progId;
            name_programTV.setText(programs.programName);
        Log.d(TAG, "Program Name:\t" + programs.programName);
         //            placeNameTV.setText(programs.placeName != null ? programs.placeName: "This Program Has No Venue Yet");
        //            desc_programTV.setText(programs.programDesc);
    }

    private void setUpRV() {

        programsSessionsRV.setHasFixedSize(true);
        programsSessionsRV.setLayoutManager(new GridLayoutManager(getActivity(), 3));

        ProgramsViewModel viewModel = ViewModelProviders.of(getActivity()).get(ProgramsViewModel.class);
        viewModel.setProgramId(progId);

    }
     ```
  

在视图模型中,我收到了ID:

``` public class ProgramsViewModel extends AndroidViewModel {

    private static final String TAG = ProgramsViewModel.class.getSimpleName();

    private ProgramsRepository repository;
    private MutableLiveData<Boolean> loadingState;
    private LiveData<List<Programs>> livePrograms;
    private Programs upDatedProgram;
    private String progId;

    public ProgramsViewModel (@NonNull Application application){
        super(application);
        repository = new ProgramsRepository(application);
        livePrograms = repository.getSavedPrograms();
        loadingState = new MutableLiveData<>();
        repository.fetchProgramDetail(progId);
    }

    public void getNetworkPrograms(){
        repository.fetchPrograms();
    }

    public MutableLiveData<Boolean> getLoadingState() {
        return loadingState;
    }

    public LiveData<List<Programs>> getLivePrograms() {
        return livePrograms;
    }

    public Programs getUpdatedPrograms(){
        return upDatedProgram;
    }

    public void setProgramId(String progId) {
        Log.d(TAG, "Prog id in view model:\t" + progId);
        this.progId = progId;
    } } ```
  

在存储库中,我进行了网络通话以获取更多详细信息,并   尝试使用以下值更新我的实体:


       public class ProgramsRepository {

        private static final String TAG = ProgramsRepository.class.getSimpleName();

        private ProgramsDAO dao;
        private static ProgramsRepository repository;
        private SessionsRepository sessionsRepository;

        private LiveData<List<Programs>> allPrograms;
        private MutableLiveData<Boolean> loadingState;

        private Sports-Database database;
        private Context context;
        private ProgramSessionDetails sessionDetails;
        private String place, desc;

        public ProgramsRepository(Application application) {
            database = SportsDatabase.getInstance(application);
            dao = database.programsDAO();
            allPrograms = dao.getAllPrograms();
            loadingState = new MutableLiveData<>();
            context = application.getApplicationContext();
            sessionsRepository = SessionsRepository.getRepository(application);
        }

        private static ProgramsRepository getInstance(Application application) {
            if (repository == null) {
                repository = new ProgramsRepository(application);
            }
            return repository;
        }

        public void fetchPrograms() {
            String coachId = new PrefsUtils(context).getCoachId();

            Call<ProgramDetails> call = RestClient.getRestInstance().getProgramsService().getAllPrograms(coachId);

            call.enqueue(new Callback<ProgramDetails>() {
                @Override
                public void onResponse(Call<ProgramDetails> call, Response<ProgramDetails> response) {
                    if (response.isSuccessful()) {
                        loadingState.postValue(false);
                        ProgramDetails details = response.body();
                        List<Programs> programs = details.getPrograms();
                        savePrograms(programs);
                    }
                }

                @Override
                public void onFailure(Call<ProgramDetails> call, Throwable t) {
                    loadingState.postValue(false);
                    Toast.makeText(context, "Error Fetching Programs", Toast.LENGTH_SHORT).show();
                }
            });
        }

        public void fetchProgramDetail(String programId) {
            Call<ProgramDetails> call = RestClient.getRestInstance().getProgramsService()
                    .getProgramDetails(new PrefsUtils(context).getCoachId(), programId);

            call.enqueue(new Callback<ProgramDetails>() {
                @Override
                public void onResponse(Call<ProgramDetails> call, Response<ProgramDetails> response) {
                    if (response.isSuccessful()) {

                        ProgramDetails details = response.body();

                        place = details.getPlaceName();
                        Log.d(TAG, "Place Names:\t" + place);

                        desc = details.getProgDesc();

                        // TODO: 3/22/2019 Update program with info and update each session with numDrills and programId
                        sessionDetails = details.getProgramSessions();


                        //                    List<Sessions> list = sessionDetails.getSessions();

                        findProgram(programId);

                    }
                }

                @Override
                public void onFailure(Call<ProgramDetails> call, Throwable t) {

                }
            });

        }

        private void findProgram(String programId) {
            new FindProgramTask(dao).execute(programId);
        }

        private void savePrograms(List<Programs> programs) {
            new SaveProgramsTask(dao).execute(programs);
        }

        public LiveData<List<Programs>> getSavedPrograms() {
            return allPrograms;
        }

        public class SaveProgramsTask extends AsyncTask<List<Programs>, Void, Void> {

            private ProgramsDAO dao;

            public SaveProgramsTask(ProgramsDAO dao) {
                this.dao = dao;
            }

            @Override
            protected Void doInBackground(List<Programs>... lists) {
                dao.addPrograms(lists[0]);
                return null;
            }
        }

        public class FindProgramTask extends AsyncTask<String, Void, Programs> {

            private ProgramsDAO dao;

            public FindProgramTask(ProgramsDAO dao) {
                this.dao = dao;
            }

            @Override
            protected Programs doInBackground(String... strings) {
                dao.findById(strings[0]);
                return null;
            }

            @Override
            protected void onPostExecute(Programs programs) {
                super.onPostExecute(programs);
    //            new Thread(() -> Log.d(TAG, "Found program name:\t" + programs.programName));
                repository.getFoundProgram(programs);
            }
        }

        public class UpDateProgramsTask extends AsyncTask<Programs, Void, Void>{

            private ProgramsDAO dao;

            public UpDateProgramsTask(ProgramsDAO dao) {
                this.dao = dao;
            }

            @Override
            protected Void doInBackground(Programs... programs) {
                dao.upDateProgram(programs[0]);
                return null;
            }
        }

        private void getFoundProgram(Programs programs) {
            Log.d(TAG, "Found program name:\t" + programs.programName);
            programs.setPlaceName(place);
            programs.setProgramDesc(desc);
            programs.setSessionDetails(sessionDetails);

            updateProgram(programs);

        }

        private void updateProgram(Programs programs) {
            new UpDateProgramsTask(dao).execute(programs);
        }

    }
    ```

> I am yet to observer the updated entity in fragment but I don't think
> it worked. How do I save these new fields to program entity? Here's my
> DAO: ````

    @Dao
    public interface ProgramsDAO {

        @Insert
        void addPrograms(List<Programs> programs);

        @Query("select * from programs")
        LiveData<List<Programs>> getAllPrograms();

        @Query("select * from programs where progId = :progId")
        Programs findById(String progId);

        @Update
        void upDateProgram(Programs programs);

    }
    ````

> In my programs entity I have created an embedded model class whose
> attributes have to be tied to the program based on id like below:
> Programs Entity ````

    @Entity(tableName = "programs")
    public class Programs implements Serializable {

        @PrimaryKey(autoGenerate = true)
        int id;

        @Embedded(prefix = "psd")
        public ProgramSessionDetails sessionDetails;

        @SerializedName("prg_name")
        public String programName;

        @SerializedName("prg_id")
        public String progId;

        @SerializedName("prg_start_date")
        public String startDate;

    //    @SerializedName("")
    //    public String endDate;

        @SerializedName("")
        public String numSessions;

        //    @SerializedName("")
        public String programDesc;

        //    @SerializedName("")
        public String placeName;

        @SerializedName("prg_image")
        public String progImg;

        @SerializedName("player_count")
        public String player_count;
    ````

    Embedded Model Class
    ````
    public class ProgramSessionDetails {

        @SerializedName("prg_session_name")
        public String session_name;

        @SerializedName("prg_session_id")
        public String prog_sessionId;

        @SerializedName("prg_id")
        public String progId;

        @SerializedName("prg_session_no_drills")
        public String numDrills;

        @SerializedName("prg_image")
        public String prgImg;

    }
    ````

    Here's my API response call:
    ````
    {
                    "program_details": [
                        {
                            `prg_id`: "211",
                            "prg_name": "cricket coaching",
                            "prg_description": "gfhfgh",
                            "prg_place_name": "",
                            "session_details": [
                                {
                                    "prg_session_id": "987",
                                    "prg_session_name": "Session-16",
                                    "prg_session_no_drills": "8",
                                    "prg_image": "http://devsports.copycon.in/includes/uploads/Jellyfish5.jpg",
                                    "prg_id": "211"
                                },
                                {
                                    "prg_session_id": "1021",
                                    "prg_session_name": "sess 55",
                                    "prg_session_no_drills": "4",
                                    "prg_image": "http://devsports.copycon.in/includes/uploads/Hydrangeas1.jpg",
                                    "prg_id": "211"
                                }
                            ]
                        }
                    ],
                    "status": 1,
                    "message": "success"
                }
    ````

and program details model class for API call:
public class ProgramDetails {

    @Expose
    @SerializedName("program_details")
    private List<Programs> programs;

    @Expose
    @SerializedName("session_details")
    public ProgramSessionDetails programSessions;

    @Expose
    @SerializedName("prg_name")
    String progName;

    @Expose
    @SerializedName("prg_description")
    String progDesc;

    @Expose
    @SerializedName("prg_place_name")
    String placeName;

    @SerializedName("status")
    private String status;

    @SerializedName("message")
    private String msg;
    ````
  

我省略了所有实体和模型类的吸气剂和吸气剂   为简洁起见。

     

如何解析此响应并更新程序实体?谢谢

0 个答案:

没有答案