如何实现viewModel和Live数据?

时间:2018-04-28 09:43:09

标签: android android-livedata

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

模特课:

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;
    }
}

UsersViewModel:

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();

    }

我在网上搜索过但没有找到好的资源或者说我听不懂。我需要一些帮助。

1 个答案:

答案 0 :(得分:0)

这就是它的完成方式

@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;
    }
}