1

I have following JSON returned from server

{
  "matches": [
    {
      "unique_id": 1122278,
      "date": "2018-01-24T00:00:00.000Z",
      "team-2": "India",
      "team-1": "South Africa",
      "type": "Test",
      "dateTimeGMT": "2018-01-24T08:00:00.000Z",
      "squad": true,
      "toss_winner_team": "India",
      "matchStarted": true
    },
    {
      "unique_id": 1116929,
      "team-2": "India Under-19s",
      "team-1": "Bangladesh Under-19s",
      "type": "YouthODI",
      "date": "2018-01-25T00:00:00.000Z",
      "dateTimeGMT": "2018-01-25T21:30:00.000Z",
      "squad": true,
      "toss_winner_team": "India Under-19s",
      "winner_team": "India Under-19s",
      "matchStarted": true
    },

    {
      "unique_id": 1115781,
      "team-2": "England",
      "team-1": "New Zealand",
      "type": "Test",
      "date": "2018-03-29T00:00:00.000Z",
      "dateTimeGMT": "2018-03-29T22:00:00.000Z",
      "squad": false,
      "matchStarted": false
    }
  ],
  "v": "1",
  "ttl": 43,
  "provider": {
    "source": "Various",
    "url": "https://cricapi.com/",
    "pubDate": "2018-01-27T13:18:55.717Z"
  },
  "creditsLeft": 250
}

Using Volley library and gson.

I am trying to push JSON array match to Match Model(Pojo). I think I can insert it using a loop, but there any other way to add all JSON array to model?

public class Main2Activity extends AppCompatActivity {

    RecyclerView recyclerView;
    ArrayList<Match> matches;
    MyAdapter myAdapter;

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

       recyclerView=(RecyclerView) findViewById(R.id.recyler);
        myAdapter=new MyAdapter(matches);
        RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAnimation(n);
        recyclerView.setAdapter(myAdapter);
        callCricket();
    }

    public void callCricket() {

        CallApi callApi = new CallApi();
        callApi.setVolleyInterface(new VolleyInterface() {
            @Override
            public void onSucess(String string) {
                Log.d("ApiCall_success", string);

                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<Match>>(){}.getType();
                JSONObject jsonObject = null;
                try {

                    jsonObject = new JSONObject(string);
                    JSONArray jsonArray = jsonObject.getJSONArray("matches");
                    matches.addAll(gson.fromJson(jsonArray,type));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String string) {

            }
        }); 
    }
}

I have tried using gson but I got an error.

5
  • where are you getting error ? in gson Commented Jan 28, 2018 at 6:03
  • matches.addAll(gson.fromJson(String.valueOf(jsonArray),type)); addAll in arraylist canot be compiled Commented Jan 28, 2018 at 6:13
  • wait i'm posting an answer to solve your issue Commented Jan 28, 2018 at 6:14
  • @Abhishekkumar.ok.thanks Commented Jan 28, 2018 at 6:19
  • @Abhishekkumar.ya i got it thanks i will try now Commented Jan 28, 2018 at 6:23

1 Answer 1

1

Create pojo classes as below as per your JSON by using jsonschema2pojo:

There are No Need of loop in GSON to insert data in pojo classes.

Example.java

 package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("matches")
@Expose
private List<Match> matches = null;
@SerializedName("v")
@Expose
private String v;
@SerializedName("ttl")
@Expose
private Integer ttl;
@SerializedName("provider")
@Expose
private Provider provider;
@SerializedName("creditsLeft")
@Expose
private Integer creditsLeft;

public List<Match> getMatches() {
return matches;
}

public void setMatches(List<Match> matches) {
this.matches = matches;
}

public String getV() {
return v;
}

public void setV(String v) {
this.v = v;
}

public Integer getTtl() {
return ttl;
}

public void setTtl(Integer ttl) {
this.ttl = ttl;
}

public Provider getProvider() {
return provider;
}

public void setProvider(Provider provider) {
this.provider = provider;
}

public Integer getCreditsLeft() {
return creditsLeft;
}

public void setCreditsLeft(Integer creditsLeft) {
this.creditsLeft = creditsLeft;
}

}

Match.java

    package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Match {

@SerializedName("unique_id")
@Expose
private Integer uniqueId;
@SerializedName("date")
@Expose
private String date;
@SerializedName("team-2")
@Expose
private String team2;
@SerializedName("team-1")
@Expose
private String team1;
@SerializedName("type")
@Expose
private String type;
@SerializedName("dateTimeGMT")
@Expose
private String dateTimeGMT;
@SerializedName("squad")
@Expose
private Boolean squad;
@SerializedName("toss_winner_team")
@Expose
private String tossWinnerTeam;
@SerializedName("matchStarted")
@Expose
private Boolean matchStarted;
@SerializedName("winner_team")
@Expose
private String winnerTeam;

public Integer getUniqueId() {
return uniqueId;
}

public void setUniqueId(Integer uniqueId) {
this.uniqueId = uniqueId;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getTeam2() {
return team2;
}

public void setTeam2(String team2) {
this.team2 = team2;
}

public String getTeam1() {
return team1;
}

public void setTeam1(String team1) {
this.team1 = team1;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getDateTimeGMT() {
return dateTimeGMT;
}

public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}

public Boolean getSquad() {
return squad;
}

public void setSquad(Boolean squad) {
this.squad = squad;
}

public String getTossWinnerTeam() {
return tossWinnerTeam;
}

public void setTossWinnerTeam(String tossWinnerTeam) {
this.tossWinnerTeam = tossWinnerTeam;
}

public Boolean getMatchStarted() {
return matchStarted;
}

public void setMatchStarted(Boolean matchStarted) {
this.matchStarted = matchStarted;
}

public String getWinnerTeam() {
return winnerTeam;
}

public void setWinnerTeam(String winnerTeam) {
this.winnerTeam = winnerTeam;
}

}

Provider.java

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Provider {

@SerializedName("source")
@Expose
private String source;
@SerializedName("url")
@Expose
private String url;
@SerializedName("pubDate")
@Expose
private String pubDate;

public String getSource() {
return source;
}

public void setSource(String source) {
this.source = source;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getPubDate() {
return pubDate;
}

public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}

}

In your Activity class do coding like this :

public static final String TAG = DoctorHome.class.getSimpleName();
ArrayList<DoctorsCatPojo> doctorCatList = new ArrayList<>();
DoctorsCatAdapter doctorsCatAdapter;
RecyclerView recyclerView;



 private void getDoctorCategory() {
    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();
    String url = Constant.DOCTOR_CATEGORY;
    Log.e("URL",""+url);

    JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("onResponse",""+response);
                    try {
                        status = response.getString("status");
                        if(status.equals("success")){
                            String info = response.getString("list");
                            JSONArray jsonArray = new JSONArray(info);

                            Gson gson = new Gson();
                            Type listType = new TypeToken<ArrayList<DoctorsCatPojo>>() {
                            }.getType();
                            doctorCatList = gson.fromJson(jsonArray.toString(), listType);

                            if(doctorCatList!=null && doctorCatList.size()!=0){
                                doctorsCatAdapter = new DoctorsCatAdapter(DoctorHome.this,doctorCatList);
                                recyclerView.setAdapter(doctorsCatAdapter);
                                Log.d(TAG, response.toString());
                            }


                        }
                        else {
                            message = response.getString("message");
                            // Toast.makeText(getApplicationContext(),""+message,Toast.LENGTH_SHORT).show();
                            pDialog.hide();
                        }



                    } catch (Exception e) {
                        Log.e("Exception",""+e);
                        e.printStackTrace();
                    }
                    pDialog.hide();




                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e("error",""+error.getMessage());
            pDialog.hide();
        }
    });
    AppController.getInstance(DoctorHome.this).addToRequestQueue(request, "doctor_category");


}

your adapter class will be like this :

public class DoctorsCatAdapter extends RecyclerView.Adapter<DoctorsCatAdapter.MyViewHolder> {
    ArrayList <DoctorsCatPojo> doctorCatList;
    Context context;

    public DoctorsCatAdapter( Context context,ArrayList<DoctorsCatPojo> doctorCatList) {
         this.doctorCatList = doctorCatList;
        this.context= context;
    }




    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctors_category_row, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        DoctorsCatPojo doc = doctorCatList.get(position);
      //  holder.doctorsCatImg.setImageURI(doc.getCategory_img());



        if(doc.getCategory_name()!=null){
            holder.doctorsCatName.setText(doc.getCategory_name());
        }
        if(doc.getCategory_img()!=null){
            Picasso.with(context)
                    .load(doc.getCategory_img().replace(" ", "%20").trim())
                    .placeholder(R.drawable.no_image)
                    .into(holder.doctorsCatImg);

        }








    }

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

     class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
         ImageView doctorsCatImg;
         TextView doctorsCatName;

         MyViewHolder(final View view) {
            super(view);
            itemView.setOnClickListener(this);

            doctorsCatImg = (ImageView)view.findViewById(R.id.doctorsCatImg);
            doctorsCatName = (TextView) view.findViewById(R.id.doctorsCatName);

        }


         @Override
         public void onClick(View view) {
             doctorCatList.get(getPosition()).getCategory_id();
             ((DoctorHome)context).callDoctorListActivity(doctorCatList.get(getPosition()).getCategory_id(),doctorCatList.get(getPosition()).getCategory_name());
         }
     }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @PrateekBhardwaj for you reply.
Just follow developer.android.com/index.html , for volley i haven't use common class , you can use common class for url's,dialog,toast,internet connectivity etc. Sorry i don't have uploaded github code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.