0

i'm new to android programming and i learn material design with this post.

but i have a problem when i'm trying to populate RecyclerView with json and

get nullPointerException in getItemCount method in the RecyclerViewAdapter.

this fragment load the recyclerView and Parse the 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


}

and This is the 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);
        }
    }


}

when i populate this recyclerView with static data every thing is ok but now i have a problem Thankyou.

majid
  • 812
  • 1
  • 12
  • 36
  • MTitles should have some titles in it otherwise is gonna be null so exception. Have a null check in getItemCount () and also make sure you're receiving few items to it when you parse. – cgr Nov 26 '15 at 17:29
  • is it my code true ? – majid Nov 26 '15 at 17:52
  • I am not sure. But at first look, I could see this. Replace your getItem() method with this: @Override public int getItemCount() { if (cTitle != null) { return cTitle.size(); } } – cgr Nov 26 '15 at 19:04
  • are you know good tutorial about populating RecyclerView with json and Volley ? – majid Nov 26 '15 at 19:42
  • For RecyclerView it does not matter what HTTP library you use. What it needs is the Data sets (List) which can be put in views (ViewHolders). Read ReyclerVIew docs first. – cgr Nov 26 '15 at 19:46

1 Answers1

2

Just add cRecyclerView.setAdapter(new SupporterRecyclerAdapter(aTitle ,aAuthor )); in onResponse() after parsJsonResponse(response);

Because may be due to low internet connection, your JSON data is not parsed but your onCreateView() passes the adapter with aTitle and aAuthor with null values.

and modify your getItemCount() method like this :

@Override
    public int getItemCount() {
        return (cTitle.size()!= null ? cTitle.size() : 0);
    }
Vipul Asri
  • 8,903
  • 3
  • 46
  • 71
  • now if i want have a thumbnail url (in parsed json) . how can i send to the recyclerView . – majid Nov 27 '15 at 09:06
  • Simple solution(not ideal) is you can get the url same as you are getting _aTitle_ and _aAuthor_ in adapter. I would suggest you to parse the JSON in a `Serializable` class and accessing data from object as a whole. – Vipul Asri Nov 27 '15 at 09:14
  • this is my first internet android project and it's practical. but if i want send list of url there are be String but , i think for setting to the imageview , we need the list of integer , am i right ? – majid Nov 27 '15 at 09:22
  • No, for this you will pass URL as string only and for downloading image/thumbnail from internet i would suggest you to use simple Image Downloading library [Picasso](http://square.github.io/picasso/). Once you go through Picasso you will understand how it works. – Vipul Asri Nov 27 '15 at 09:39
  • in onbindViewHolder i need Context for picaso , but i dont have a viewGroup like a oncreateViewHolder – majid Nov 27 '15 at 09:55
  • thanks Vipol , it download image and json very well , but it need to optimize . :D – majid Nov 27 '15 at 10:30