使用Volley填充RecyclerView

时间:2015-11-26 16:37:08

标签: android json android-recyclerview android-volley

我是Android编程新手,我用这个post学习材料设计。

但是当我尝试使用RecyclerView

填充json时,我遇到了问题

nullPointerException中的getItemCount方法中获取RecyclerViewAdapter

这个fragment加载了recyclerView并解析了json

package supporter.majid.com.supporter;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

import supporter.majid.com.supporter.app.AppController;

/**
 * Created by majid on 11/25/2015.
 */
public class SupporterFragment extends Fragment {

    private static final String TAB_POSITION = "tab_position";
    String url ="http://javatechig.com/?json=get_recent_posts&count=20";

    ArrayList<String> aTitle;
    ArrayList<String> aAuthor;
    //ArrayList<String> aUrl;


    //constructor
    public SupporterFragment() {

    }

    //new instance
    public static SupporterFragment newInstance(int tabPosition) {
        Bundle args = new Bundle();

        SupporterFragment fragment = new SupporterFragment();
        args.putInt(TAB_POSITION ,tabPosition);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendJsonRequest();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       Bundle args = getArguments();
        int tabPosition = args.getInt(TAB_POSITION);

        View view = inflater.inflate(R.layout.fragment_list_view , container ,false);

        RecyclerView cRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewFragmentXml);
        cRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        cRecyclerView.setAdapter(new SupporterRecyclerAdapter(aTitle ,aAuthor ));

        return view;
    }
    // ==========================================sendJsonRequest method
    public void sendJsonRequest(){

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                parsJsonResponse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Toast.makeText(getActivity(),"We have a problem in error listener" , Toast.LENGTH_SHORT).show();
            }
        });
        AppController.getInstance().addToRequestQueue(request);
    }


//    ================================ #send Json Request methoe
    private void parsJsonResponse(JSONObject response){

        aTitle = new ArrayList<String>();
        aAuthor = new ArrayList<String>();
        //aUrl = new ArrayList<String>();

        if(response == null || response.length() == 0){
            return;
        }

        if(response.has("posts")){
            try {
                JSONArray arrayPosts = response.getJSONArray("posts");
                for (int i=0; i<arrayPosts.length();i++){
                    JSONObject currentPost = arrayPosts.getJSONObject(i);
                    //get Title post
                     String title = currentPost.getString("title");
                    //add to array list
                    aTitle.add(title);
                    //get JsonObjectAuthor
                    JSONObject authorObject = currentPost.getJSONObject("author");
                    //get Author first name
                   String  authorFirstName = authorObject.getString("first_name");
                    //add to author array list
                    aAuthor.add(authorFirstName);

//                  //getting url string
//                    //get thumbnail_images object
//                    JSONObject objectthumbnail_images = currentPost.getJSONObject("thumbnail_images");
//                    //get JsonObject thumbnail
//                    JSONObject objectThumbnail = objectthumbnail_images.getJSONObject("thumbnail");
//                    //get thumbnail url
//                    String url = objectThumbnail.getString("url");
//                    //add to url array list
//                    aUrl.add(url);
                }


            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(),"We have a JsonException" , Toast.LENGTH_SHORT).show();
            }

        }
    }

//    ================================================= #parsJsonResponse


}

这是SupporterRecyclerViewAdapter

package supporter.majid.com.supporter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by majid on 11/26/2015.
 */
public class SupporterRecyclerAdapter extends RecyclerView.Adapter<SupporterRecyclerAdapter.ViewHolder> {

    private List<String> cTitle;
    private List<String> cDesc;
    private List<Integer> cImageProduct;


    //constructor

    SupporterRecyclerAdapter(List<String> title, List<String> Desc ) {

        cTitle = title;
        cDesc = Desc;
        //cImageProduct = ImgProduct;
    }

    //on create View Holder

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);

        return new ViewHolder(view);
    }


    //onBindViewHolder

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String title = cTitle.get(position);
        String desc = cDesc.get(position);
        //int imgProduct = cImageProduct.get(position);

        holder.vTxtTitle.setText(title);
        holder.vTxtDesc.setText(desc);
       // holder.vImageView.setImageResource(imgProduct);
    }


    //getItemCount


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

    }

    //View Holder Pattern
    public class ViewHolder extends RecyclerView.ViewHolder {

        //private final ImageView vImageView;
        private final TextView vTxtDesc;
        private final TextView vTxtTitle;

        public ViewHolder(View itemView) {
            super(itemView);
            //vImageView = (ImageView) itemView.findViewById(R.id.imgListRowXml);
            vTxtTitle = (TextView) itemView.findViewById(R.id.txtTitleListRowXml);
            vTxtDesc = (TextView) itemView.findViewById(R.id.txtDescListRowXml);
        }
    }


}

当我用静态数据填充此recyclerView时,每件事情都可以,但现在我有一个问题谢谢你。

1 个答案:

答案 0 :(得分:2)

只需在cRecyclerView.setAdapter(new SupporterRecyclerAdapter(aTitle ,aAuthor ));

之后的onResponse()中添加parsJsonResponse(response);即可

由于互联网连接较少,您的JSON数据不会被解析,但您的onCreateView()会使用 aTitle aAuthor 以及空值传递适配器。

并修改您的getItemCount()方法,如下所示:

@Override
    public int getItemCount() {
        return (cTitle.size()!= null ? cTitle.size() : 0);
    }