无法在Android中使用MVVM架构显示来自远程服务器的数据

时间:2019-01-15 08:44:02

标签: java json android-studio android-volley android-mvvm

我无法解析来自远程服务器的json数据。我正在使用MVVM体系结构和凌空库来解析json数据。我尝试调试,并且消息显示“尝试在空对象引用上调用虚拟方法”。 我认为问题是由于LiveData类造成的,所以我将其删除了。然后,它也不起作用。还请告诉我们如何使用LiveData类。

BikesRepository.java

package com.example.osama.dashbike.Repository;

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.osama.dashbike.Models.BikesInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;



public class BikesRepository {
    Context context;
    MutableLiveData<ArrayList<BikesInfo>> mutableLiveData;
    ArrayList<BikesInfo> arrayList;
    Listener mListener;
    String json_url = "http://491ab6f9.ngrok.io/api/note/";

public BikesRepository(Context context, Listener listener){
    this.context = context;
   mListener = listener;
}
public /*LiveData<ArrayList<BikesInfo>*/void getArrayList(){

    mutableLiveData = new MutableLiveData<>();
    arrayList = new ArrayList<>();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    JSONArray jsonArray ;
                    try {
                        jsonArray = response.getJSONArray("objects");
                        int i;
                        for (i = 0; i < jsonArray.length(); i++){
                            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                            String c = jsonObject.getString("image");
                            String a = jsonObject.getString("title");
                            String b = jsonObject.getString("body");
                            BikesInfo bikesinfo = new BikesInfo(a,b,c);
                            arrayList.add(bikesinfo);
                            //mutableLiveData.postValue(arrayList);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    // if listener has been set, send data
                    if (mListener != null){
                        mListener.onDataReceived(arrayList/*mutableLiveData*/);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // if listener has been set, send error
            if (mListener != null) {
                mListener.onError(error.networkResponse.statusCode);
            }

        }
    });
    Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
    //return arrayList;
    //return mutableLiveData;
}
}

BikesViewModel.java

package com.example.osama.dashbike.ViewModels;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
import com.example.osama.dashbike.ApplicatonContext;
import com.example.osama.dashbike.Models.BikesInfo;
import com.example.osama.dashbike.Repository.BikesRepository;
import com.example.osama.dashbike.Repository.Listener;
import java.util.ArrayList;

public class BikesViewModel extends AndroidViewModel {
    BikesRepository bikesRepository;
    ArrayList<BikesInfo> bikesinfolistobservable;
    //LiveData<ArrayList<BikesInfo>> bikesinfolistobservable;

    public BikesViewModel(@NonNull Application application) {
        super(application);
        bikesRepository = new BikesRepository(application, new Listener() {
            @Override
            public void onDataReceived(/*MutableLiveData<*/ArrayList<BikesInfo> mutableLiveData) {
                bikesinfolistobservable = mutableLiveData;


            }

            @Override
            public void onError(int error) {

            }
        });
        bikesRepository.getArrayList();

    }

    public /*LiveData<*/ArrayList<BikesInfo> getbikesinfolistobservable(){

        return bikesinfolistobservable;
    }

}

BikesInfo.java

package com.example.osama.dashbike.Models;

public class BikesInfo {
    private String txt1,txt2;
    private String imageurl;
    public BikesInfo(String txt1, String txt2, String imageurl){
        this.setTxt1(txt1);
        this.setTxt2(txt2);
        this.setImageUrl(imageurl);
    }

    public String getTxt1() {
        return txt1;
    }

    public void setTxt1(String txt1) {
        this.txt1 = txt1;
    }

    public String getTxt2() {
        return txt2;
    }

    public void setTxt2(String txt2) {
        this.txt2 = txt2;
    }

    public String getImageUrl() {
        return imageurl;
    }

    public void setImageUrl(String imageurl) {
        this.imageurl = imageurl;
    }
}

BikesListAdapter.java

package com.example.osama.dashbike.Views.Adapters;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.osama.dashbike.ApplicatonContext;
import com.example.osama.dashbike.Models.BikesInfo;
import com.example.osama.dashbike.R;
import com.example.osama.dashbike.Repository.Singleton;
import java.util.ArrayList;

public class BikesListAdapter extends RecyclerView.Adapter<BikesListAdapter.BikesListHolder> {

    ArrayList<BikesInfo> arrayList1;
    private ImageLoader imageLoader;

    public BikesListAdapter(ArrayList<BikesInfo> arrayList){
        this.arrayList1 = arrayList;

        //very costly method i.e. slow performance. Modify it.
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public BikesListHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.fragment_bikes, viewGroup, false);
        BikesListHolder bikesListHolder = new BikesListHolder(view);
        return bikesListHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull BikesListHolder thugHolder, int i) {

        thugHolder.text.setText(arrayList1.get(i).getTxt1());
        thugHolder.text2.setText(arrayList1.get(i).getTxt2());
        imageLoader = Singleton.getInstance(ApplicatonContext.getAppContext()).getmImageLoader();
      thugHolder.image.setImageUrl(arrayList1.get(i).getImageUrl(),imageLoader);


    }

    @Override
    public int getItemCount() {
        return arrayList1.size();
    }

    public class BikesListHolder extends RecyclerView.ViewHolder{

        TextView text,text2;
        NetworkImageView image;
        public BikesListHolder(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.textView1);
            text2 = itemView.findViewById(R.id.textView2);
            image = itemView.findViewById(R.id.imageView1);
        }
    }
}

MainActivity.java

package com.example.osama.dashbike.Views.ui;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.example.osama.dashbike.ApplicatonContext;
import com.example.osama.dashbike.Models.BikesInfo;
import com.example.osama.dashbike.R;
import com.example.osama.dashbike.Repository.BikesRepository;
import com.example.osama.dashbike.ViewModels.BikesViewModel;
import com.example.osama.dashbike.Views.Adapters.BikesListAdapter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    BikesViewModel bikesViewModel;
    BikesListAdapter bikesListAdapter;
    LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bikes_recycler);//activity_main);
        recyclerView = findViewById(R.id.recycler);
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);
        bikesViewModel = ViewModelProviders.of(this).get(BikesViewModel.class);
        bikesListAdapter = new BikesListAdapter(bikesViewModel.getbikesinfolistobservable());
        recyclerView.setAdapter(bikesListAdapter);
                       // observeViewModel(bikesViewModel);
      //  FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
       // fragmentTransaction.replace(R.id.bikes_fragment_frame, new BikesFragment());
       // fragmentTransaction.commit();

    }
   /* private void observeViewModel (BikesViewModel bikesViewModel){
        bikesViewModel.getbikesinfolistobservable().observe(this, new Observer<ArrayList<BikesInfo>>() {
            @Override
            public void onChanged(@Nullable ArrayList<BikesInfo> bikesInfo) {
                if (bikesInfo != null) {
                    bikesListAdapter = new BikesListAdapter(bikesInfo);
                    recyclerView.setAdapter(bikesListAdapter);
                }
            }
        });
    } */
}

编辑: Listener.java

package com.example.osama.dashbike.Repository;

import android.arch.lifecycle.MutableLiveData;
import com.example.osama.dashbike.Models.BikesInfo;
import java.util.ArrayList;

public interface Listener {
    void onDataReceived(/*MutableLiveData<*/ArrayList<BikesInfo> mutableLiveData);
    void onError(int error);
}

Singleton.java

package com.example.osama.dashbike.Repository;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class Singleton {
    private static Singleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private Singleton(Context context){
        mCtx = context;
        mRequestQueue =getRequestQueue();

                mImageLoader = new ImageLoader(mRequestQueue,
                        new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);
                            @Override
                            public Bitmap getBitmap(String url) {
                                return cache.get(url);
                            }

                            @Override
                            public void putBitmap(String url, Bitmap bitmap) {

                                cache.put(url, bitmap);
                            }
                        });
    }

    public static synchronized Singleton getInstance(Context context){
        if (mInstance == null){
            mInstance = new Singleton(context);
        }
        return mInstance;
    }
    public RequestQueue getRequestQueue(){
        if (mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }
    public <T> void addToRequestQueue(Request<T> request){
        getRequestQueue().add(request);
    }
    public ImageLoader getmImageLoader(){
        return mImageLoader;
    }

}

0 个答案:

没有答案