首页 > 解决方案 > 如何实现 viewModel 和 Live 数据?

问题描述

我正在尝试实现 Viewmodel 和 Live 数据架构。但我无法做到这一点。谁能帮我解决这个问题。下面是我尝试过的代码。我不明白如何将 json 数据添加到列表和显示 recyclerview 适配器和显示。

模型类:

public class User {

    private String id;
    private String name;
    private String address;
    private String createdAt;
    private String updatedAt;

    public User() {
    }

    public User(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }
}

用户视图模型:

public class UsersViewModel extends ViewModel {

    AsyncTaskTest asyncTask;
    Context context;
    private LiveData<ArrayList<User>> list1 = null;

    UsersViewModel(Context context){
        list1=loadUsers();
    }

    private LiveData<ArrayList<User>> list;

    public LiveData<ArrayList<User>> user(){

        if (list==null){
            list=loadUsers();
        }

        return list;
    }

    private LiveData<ArrayList<User>> loadUsers(){

        String query;

        try {
            query= URLEncoder.encode("getChatRooms","UTF-8")+"="+URLEncoder.encode("getChatRooms","UTF-8");

            asyncTask=new AsyncTaskTest(/*context, */new AsyncTaskResult() {

                @Override
                public void AsyncTaskResult(String result) throws JSONException {

//                    list1=new ArrayList<>();
                    Log.v("DFJGHK",result);

                    JSONObject jsonObject=new JSONObject(result);
                    JSONArray jsonArray=jsonObject.getJSONArray("result");

                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject object=jsonArray.optJSONObject(i);



                    }

                }
            });
            asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"POST","mobileApi/chatRooms",query);

        } catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return list1;
    }
}

活动:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_show);

        recyclerView=(RecyclerView)findViewById(R.id.recyclerViewId);
        viewModel= ViewModelProviders.of(this).get(UsersViewModel.class);
        viewModel.user();

    }

我在网上搜索过,但没有找到好的资源,或者我无法理解。我需要一些帮助。

标签: androidandroid-livedata

解决方案


这就是它的完成方式

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_show);

    recyclerView=(RecyclerView)findViewById(R.id.recyclerViewId);
    viewModel= ViewModelProviders.of(this).get(UsersViewModel.class)
    viewModel.user().observe(this, new Observer<List<User>>() {
        @Override
        public void onChanged(@Nullable List<User> users) {
            //You now have users
        }
    });

}

你的视图模型应该是这样的

public class UsersViewModel extends AndroidViewModel {

    public UsersViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<ArrayList<User>> user() {
        ....
        return list;
    }
}

推荐阅读