I have FB, Google and normal login in my app.when I log in with FB or google everything is fine, but whenever I signup from the app and sign in instantly I am not getting data in CartActivity RecyclerView, but data is showing in postman or browser.Again when I uninstall the app and reinstall data start showing that old login credentials.
CartActivity:
try {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url2,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.dismiss();
// Toast.makeText(CartActivity.this, "responce"+response.toString(), Toast.LENGTH_SHORT).show();
System.out.println("Response is : " + response);
try {
JSONObject jsono = new JSONObject(response);
if (jsono.getString("status").equals("success")) {
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String total = object.getString("cart_total");
jarray = jsono.getJSONArray("data");
JSONArray jarray1 = object.getJSONArray("product_description");
for (int j = 0; j < jarray1.length(); j++) {
JSONObject object1 = jarray1.getJSONObject(j);
JSONArray jarray2 = object1.getJSONArray("data");
for (int k = 0; k < jarray2.length(); k++) {
JSONObject object2 = jarray2.getJSONObject(k);
String Name = object2.getString("product_name");
String Image = object2.getString("product_image");
String Price = object2.getString("product_price");
String Qty = object2.getString("product_qty");
String sku = object2.getString("product_sku");
String ProId = object2.getString("product_id");
System.out.println("VALUES: " + Name + "price" + Price + "qty" + Qty + sku + "proid" + ProId);
}
}
}
rccart.setAdapter(cartAdapter);
cartAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "Something went wrong...", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
System.out.println("EXCPTION IN SUCCESS REQUEST : " + ex.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
System.out.println("ERROR IN REQUEST : " + error.getMessage());
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(CartActivity.this);
requestQueue.add(stringRequest);
pd = new ProgressDialog(CartActivity.this);
pd.setMessage("Loading...");
pd.show();
} catch (Exception ex) {
}
}
make one pojo class that define all the field if you getting at a response time like below code..
public class DataClass {
String Name ;
String Image ;
String Price ;
String Qty ;
String sku ;
String ProId;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getQty() {
return Qty;
}
public void setQty(String qty) {
Qty = qty;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getProId() {
return ProId;
}
public void setProId(String proId) {
ProId = proId;
}
}
Add list in recycler view adapter like ....
private List<DataClass> mDataList=new ArrayList<>();
public CustomAdapter(List<DataClass> mDataList) {
this.mDataList = mDataList;
}
then after get response data to add into array list and pass into adapter..
private List<DataClass> mListData=new ArrayList<>();// define in type-array in your pojo class name
for (int k = 0; k < jarray2.length(); k++) {
JSONObject object2 = jarray2.getJSONObject(k);
DataClass dataClass=new DataClass();
String Name = object2.getString("product_name");
String Image = object2.getString("product_image");
String Price = object2.getString("product_price");
String Qty = object2.getString("product_qty");
String sku = object2.getString("product_sku");
String ProId = object2.getString("product_id");
dataClass.setName(Name);
dataClass.setImage(Image);
dataClass.setPrice(Price);
dataClass.setQty(Qty);
dataClass.setSku(sku);
dataClass.setProId(ProId);
mListData.add(dataClass);
System.out.println("VALUES: " + Name + "price" + Price + "qty" + Qty + sku + "proid" + ProId);
}
if (!mListData.isEmpty()){
cartAdapter=new CartAdapter(mListData);
rccart.setAdapter(cartAdapter);
cartAdapter.notifyDataSetChanged();
}
Got the solution.That was happening because of cache. just cleared cache and problem solve.
Related
I would like to visualize the Json data on a listview, but I don't know how to do it ... I tried to use a TextView to verify the correct passage of the data and it seems to work, but I would need to display them on the listView ... ideas?
{"Esito":true,"Dati":[{"id":"357","id_utente":"16","nome_prodotto":"cozze"},{"id":"358","id_utente":"16","nome_prodotto":"riso"},{"id":"362","id_utente":"16","nome_prodotto":"patate"},{"id":"366","id_utente":"16","nome_prodotto":"cozze"},{"id":"367","id_utente":"16","nome_prodotto":null}]}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.G[enter image description here][1]ET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
String id = dato.getString("id");
String id_utente = dato.getString("id_utente");
String nome_prodotto = dato.getString("nome_prodotto");
mTextViewResult.append(id + ", " + id_utente + ", " + nome_prodotto + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Just make new object class and collect data to list :
class YourObiekt {
private String id;
private String idUtente;
private String nomeProdotto;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdUtente() {
return idUtente;
}
public void setIdUtente(String idUtente) {
this.idUtente = idUtente;
}
public String getNomeProdotto() {
return nomeProdotto;
}
public void setNomeProdotto(String nomeProdotto) {
this.nomeProdotto = nomeProdotto;
}
}
List<YourObiekt> yourObiektList = new ArrayList<YourObiekt>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
YourObiekt yo = new YourObiekt();
yo.setId(dato.getString("id"));
yo.setIdUtente(dato.getString("id_utente"));
yo.setNomeProdotto(dato.getString("nome_prodotto"));
yourObiektList.add(yo);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And now you get yourObiektList as data for your listView
JSON:
{
"videos":[
[
{
"video_id":"DKOLynNhWxo",
"video_url":"https:\/\/www.youtube.com\/watch?v=DKOLynNhWxo",
"video_host":"youtube",
"created_at":"2017-08-08 11:17:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"English"
},
{
"video_id":"haYm5k6h5yc",
"video_url":"https:\/\/www.youtube.com\/watch?v=haYm5k6h5yc",
"video_host":"Youtube",
"created_at":"2017-08-10 10:05:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"English"
}
],
[
{
"video_id":"VSkRU8eXFII",
"video_url":"https:\/\/www.youtube.com\/watch?v=VSkRU8eXFII",
"video_host":"youtube",
"created_at":"2017-08-08 11:18:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"Maths"
}
],
[],
[]
]
}
Code:
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(JsonExp.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
AppController sh = new AppController();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("videos");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
//JSONObject cjsnobj = contacts.getJSONObject(i);
JSONArray c = contacts.getJSONArray(i);
for (int y = 0; y < c.length(); y++)
{
JSONObject obj=c.getJSONObject(i);
String aid = obj.getString("video_id");
String url = obj.getString("video_url");
// String name = obj.getString("video_host");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("video_id", aid);
contact.put("video_url", url);
// contact.put("video_host", name);
// adding contact to contact list
contactList.add(contact);
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
JsonExp.this, contactList,
R.layout.list_item, new String[]{"video_id","video_url"//, "video_host"//, "ProductDetails", "rectimestamp"
}, new int[]{R.id.aid, R.id.name
});
lv.setAdapter(adapter);
}
}
replace JSONObject obj=c.getJSONObject(i); with JSONObject obj=c.getJSONObject(y);
I strongly suggest you to use Gson
The example:
Create a model class
public class Video {
private String id;
private String url;
private String host;
private String date;
private String branch;
private String semester;
private String subject;
public Video(String id, String url, String host, String date, String branch, String semester, String subject) {
this.id = id;
this.url = url;
this.host = host;
this.date = date;
this.branch = branch;
this.semester = semester;
this.subject = subject;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public String getHost() {
return host;
}
public String getDate() {
return date;
}
public String getBranch() {
return branch;
}
public String getSemester() {
return semester;
}
public String getSubject() {
return subject;
}
}
Create an arraylist
JSONArray contacts = jsonObj.getJSONArray("videos");
ArrayList<Video> videos = new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
JSONObject contact = contacts.getJSONObject(i);
for (int y = 0; y < contact.length(); y++) {
JSONObject obj = contact.getJSONObject(y);
String id = obj.getString("video_id");
String url = obj.getString("video_url");
String host = obj.getString("video_host");
String date = obj.getString("created_at");
String branch = obj.getString("branch_name");
String semester = obj.getString("semester_name");
String subject = obj.getString("subject_name");
Video video = new Video(id, url, host, date, branch, semester, subject);
videos.add(video);
}
}
try{
JSONObject obj = nes JSONObject(yourResponse);
JSONArray video = obj.getJSONArray("videos");
for(i=0; i<video.length; i++){
JSONObject object = video.getJSONObject(i);
String subject_name = object.getString("subject_name");
}
}
catch(JSONException e){
}
how to retrieve below json data from server in android? can you please guide me with an example? how to get UserRole from the below url?
http://beta.json-generator.com/api/json/get/4y2NmxAYf
Here's an example to retrieve json data from server
Add this dependency of the Gson library to the App's gradle:
compile 'com.google.code.gson:gson:2.4'
Create a model class
public class UserModel{
public String UserRole;
public String UserName;
public int Id;
public String Email;
public String getUserRole(){
return UserRole;
}
public void setUserRole(String _userRole){
UserRole = _userRole;
}
public String getUserName(){
return UserName;
}
public void setUserName(String _userName){
UserName = _userName;
}
public int getId(){
return Id;
}
public void setId(int _id){
Id = _id;
}
public String getEmail(){
return Email;
}
public void setEmail(String _email){
Email = _email;
}
}
Now use Gson library to convert data from server's response to the above model.(Note: Write these lines in the onPostExecute() of the AsyncTask Class)
#Override
protected void onPostExecute(final Boolean success) {
try {
if (success) {
if (responsecode == 200) {
//GSON responsedata
if(responsedata!=null) {
if (responsedata != "") {
List<UserModel> userlist = new ArrayList<UserModel>();
JSONArray jsonArray = new JSONArray(responsedata);
for (int i = 0; i < jsonArray.length(); i++) {
UserModel item = new UserModel();
item = new Gson().fromJson(jsonArray.getJSONObject(i).toString(), UserModel.class);
userlist.add(item);
}
}
}
} else if(responsecode==401){
// use toast display the specific error
}
}
else {
Toast.makeText(context, responsedata, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Access denied!", Toast.LENGTH_LONG).show();
}
}
catch (Exception e){
if(e!=null){
}
}
}
You are getting json array in response. You can get details from array like:
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0; i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String userRole = jsonObject.getString("UserRole");
//Rest of the code....
}
} catch (Exception e) {
e.printStackTrace();
}
Use Below Code to get JsonRespone :
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String API_URL = "http://beta.json-generator.com/api/json/get/4y2NmxAYf";
// Do some validation here
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
// progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
parseJsonData(response);
}
}
And Parse your data using below method:
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String UserRole = jsonObject1.optString("UserRole");
String UserName = jsonObject1.optString("UserName");
String Id = jsonObject1.optString("Id");
String Email = jsonObject1.optString("Email");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
find API calling code from below Link :
How to use a web API from your Android app
You can use OkHttp to fetch json data from server and use fastjson to parse data.
Add these dependencies to the App's build.gradle:
compile 'com.alibaba:fastjson:1.2.24'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'
Then 1.Create a model class:
public class JsonModel {
private String UserRole;
private String UserName;
private int Id;
private String Email;
public String getUserRole() {
return UserRole;
}
public void setUserRole(String UserRole) {
this.UserRole = UserRole;
}
public String getUserName() {
return UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
#Override
public String toString() {
return "JsonModel{" +
"Email='" + Email + '\'' +
", UserRole='" + UserRole + '\'' +
", UserName='" + UserName + '\'' +
", Id=" + Id +
'}';
}
2.Use OkHttp to fetch json data and use fastjson to parse the data.
class GetJson extends Thread {
private String url;
public GetJson(String url) {
this.url = url;
}
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
final String text = response.body().string();
List<JsonModel> models = JSON.parseArray(text, JsonModel.class);
//Do other things based on models
}
} catch (IOException e) {
e.printStackTrace();
}
}
you can take a look at http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ and try to search more before you start a new topic next time !
Try this,
StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://beta.json-generator.com/api/json/get/4y2NmxAYf",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray result = new JSONArray(response);
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String UserRole = c.getString("UserRole");
String UserName = c.getString("UserName");
int Id = c.getInt("Id");
String Email = c.getString("Email");
}
} catch (JSONException e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
gradle dependencies for your Android project's app module:
compile 'com.android.volley:volley:1.0.0'
I am using volley library to achive network operation when i try to ru the program using below program i am gettin warning and getting size less than what i have in the url the warning message is org.json.JSONException: Index 3 out of range [0..3).
public class MainActivity extends AppCompatActivity {
TextView results;
String JsonURL = "http://184.73.181.186/jsondata.php";
String data = "";
RequestQueue requestQueue;
MyCustomBaseAdapter myCustomBaseAdapter;
ArrayList<StudentInfo> studentInfoList = new ArrayList<StudentInfo>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue = Volley.newRequestQueue(this);
results = (TextView) findViewById(R.id.jsonData);
JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i=0;i<lenghthofarray;i++){
JSONObject jresponse = response.getJSONObject(i);
final int numberOfItemsInResp = jresponse.length();
StudentInfo studentInfo = new StudentInfo();
String fname = jresponse.getString("fName");
String lName = jresponse.getString("lName");
String rollNo = jresponse.getString("rollNo");
String profilePic = jresponse.getString("profilePic");
studentInfo.setFname(fname);
studentInfo.setLname(lName);
studentInfo.setRoolNo(rollNo);
studentInfo.setStudpic(profilePic);
studentInfoList.add(studentInfo);
list.add(profilePic);
myCustomBaseAdapter = new MyCustomBaseAdapter(getApplicationContext(),studentInfoList);
JSONObject colorObj = response.getJSONObject(0);
JSONArray colorArry = colorObj.getJSONArray("marks");
for (int ii = 0; ii < colorArry.length(); ii++) {
JSONObject jsonObject = colorArry.getJSONObject(i);
String subjectName, marks;
subjectName = jsonObject.getString("subjectName");
marks = jsonObject.getString("marks");
}
data += "\nfName " + fname +
"\nHex Value : " + lName + "\n\n\n"+rollNo+"\n"+profilePic+"\n";
}
results.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
}
}
The problem is in(i),replace i with ii
JSONObject jsonObject = colorArry.getJSONObject(i);
solved one
JSONObject jsonObject = colorArry.getJSONObject(ii);
I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
But i have strange problem! when added this line in my codes, json and RecyclerView has limited and show 5 post instance of 10 posts!
code :
JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");
when added this line limited for 5 post, when delete this line it's ok and show 10 posts!
Json Link: Json link
AsyncTask codes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
JSONObject images=postObject.getJSONObject("thumbnail_images");
JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString("thumbnail")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
How can i fix this problem and when added above code, show 10 posts and run success application ? Thanks
how to use Gson here
first, add in your build.gradle this
dependencies {
compile 'com.google.code.gson:gson:2.4'
//your all other dependencies
}
second, create class PostsResponse and write in it
package your.package.here;
import android.text.TextUtils;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class PostsResponse {
private static final String DEFAULT_IMAGE_URL = "put your default image url here";
public static class Post {
#SerializedName("id")
private int mId;
#SerializedName("title")
private String mTitle;
#SerializedName("content")
private String mContent;
#SerializedName("thumbnail")
private String mThumbnail;
#SerializedName("thumbnail_images")
private Images mImages;
public static class Images {
#SerializedName("martial-frontpage-blog")
private String mMartialFrontpageBlogUrl;
public String getMartialFrontpageBlogImage() {
return TextUtils.isEmpty(mMartialFrontpageBlogUrl) ?
DEFAULT_IMAGE_URL :
mMartialFrontpageBlogUrl;
}
}
public int getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public String getContent() {
return mContent;
}
public String getThumbnail() {
return mThumbnail;
}
public String getMartialFrontpageBlogImage() {
return mImages.getMartialFrontpageBlogImage();
}
}
#SerializedName("posts")
private ArrayList<Post> mPosts;
public ArrayList<Post> getPosts() {
return mPosts;
}
}
and change part of your MainDataInfo from
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
JSONObject images=postObject.getJSONObject("thumbnail_images");
JSONObject imagesPair=images.getJSONObject("martial-frontpage-blog");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString("thumbnail")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
to this new one
if (!TextUtils.isEmpty(ou_response)) {
try {
PostsResponse postsResponse = new Gson().fromJson(ou_response, PostsResponse.class);
infoModels = new ArrayList<>();
for (PostsResponse.Post post : postsResponse.getPosts()) {
infoModels.add(new MainDataModel(
post.getId(),
post.getTitle(),
post.getContent(),
post.getThumbnail())
);
//// TODO: 26.04.16 use post.getMartialFrontpageBlogImage()
//// as you want here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
don't forget to properly fill DEFAULT_IMAGE_URL and package
and see TODO section
feel free to add new fields to Post class and provide getters for them
THE END )
"post" with index 5 in your server response has no "martial-frontpage-blog" in "thumbnail_images", so your parsing cycle simply stops and drops exception.
to fix it - use optJSONObject();imagesPair = images.optJSONObject("..."); and check it for null
one else moment )
fix your cycle from for (int i = 0; i <= infoModels.size(); i++) {
to for (int i = 0; i < postsArray.length(); i++) {
in your current realization cycle stops work by exception )