I am new to android , and I need an example to use / consume the following Web service in an application developed on android studio :
http://www.myweather2.com/developer/weather.ashx?uac=ENHRNh-psb&uref=53694bca-82a0-4de3-8a9b-70e4fe0b3e94
I would be very useful to be very specific.
Use JSON API instead of XML, that will make your task easier.
public class QueryBuilder {
//This is your unique key as I can see in the URL
private static final String KEY = "ENHRNh-psb";
// Take output as JSON instead of XML
private static final String OUTPUT = "json";
private static final String BASE_URL = "http://www.myweather2.com/developer/weather.ashx?";
private String query;
public QueryBuilder() {
//build the base query with key and output
this.query = BASE_URL + "uac=" + KEY + "&output=" + OUTPUT;
}
//Example of methods which you can add according to your requirement
public QueryBuilder setLocalityFilter(String locality) {
this.query = this.query + "&filters={\"locality\":{\"$eq\":\"" + locality + "\"}}";
return this;
}
public String build() {
return this.query;
}
}
Example of JSON parser class
public class JsonParser {
public static ArrayList<Restaurant> parseHTTPResponse(String responseString) {
ArrayList<Restaurant> restaurantArrayList= new ArrayList<>();
try {
JSONObject baseObject = new JSONObject(responseString);
JSONObject responseObject = baseObject.getJSONObject("response");
JSONArray restaurantArray = responseObject.getJSONArray("data");
for (int i =0; i<restaurantArray.length();i++) {
Restaurant restaurant = new Restaurant();
JSONObject restaurantObject = restaurantArray.getJSONObject(i);
restaurant.setName(restaurantObject.getString("name"));
restaurant.setAddress(restaurantObject.getString("address"));
restaurant.setRating(restaurantObject.getDouble("rating"));
// Check if the restaurant has its cuisine listed, if yes add it to type
if(restaurantObject.has("cuisine")) {
JSONArray cuisineArray = restaurantObject.getJSONArray("cuisine");
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < cuisineArray.length(); j++) {
String cuisine = cuisineArray.getString(j);
stringBuilder.append(cuisine);
stringBuilder.append(" ,");
}
restaurant.setType(stringBuilder.toString());
}
restaurantArrayList.add(restaurant);
}
}
catch (JSONException ex) {
ex.printStackTrace();
}
return restaurantArrayList;
}
}
Build the query like this
String httpQuery = new QueryBuilder().setLocalityFilter(query).build();
try {
HttpRequest request = HttpRequest.get(httpQuery);
if (request.ok()) {
String response = request.body();
restaurantArrayList = JsonParser.parseHTTPResponse(response);
}
return restaurantArrayList;
} catch (HttpRequest.HttpRequestException exception) {
return null;
}
Related
I am trying to get the data from the Api but an error ocurred.
i have parameters like:
oauth_consumer_key- String --Your API key when you registered as a developer
oauth_signature_method- String-- The method used to generate the signature (only HMAC-SHA1 is supported)
oauth_timestamp -Int --The date and time, expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value must be a positive integer and must be equal or greater than the timestamp used in previous requests
oauth_nonce -String-- A randomly generated string for a request that can be combined with the timestamp to produce a unique value
oauth_version -String --MUST be "1.0"
oauth_signature- String-- The signature, a consistent reproducible concatenation of the request elements into a single string. The string is used as an input in hashing or signing algorithms.
method -String --MUST be "recipes.search"
and my class for this looks where i am using using Volley library to fetch the data:
final static private String APP_METHOD = "GET";
final static private String APP_KEY = "app key is here";
final static private String APP_SECRET = "secret key is here&";
final static private String APP_URL = "http://platform.fatsecret.com/rest/server.api";
private static final String HMAC_SHA1_ALGORITHM = "HMAC-SHA1";
private static String paramify(String[] params) {
String[] p = Arrays.copyOf(params, params.length);
Arrays.sort(p);
return join(p, "&");
}
private static String join(String[] array, String separator) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0)
b.append(separator);
b.append(array[i]);
}
return b.toString();
}
//generating nonce value
private static String nonce() {
Random r = new Random();
StringBuilder n = new StringBuilder();
for (int i = 0; i < r.nextInt(8) + 2; i++)
n.append(r.nextInt(26) + 'a');
return n.toString();
}
//timestamp
Long tsLong = System.currentTimeMillis() / 1000;
int ts = Integer.parseInt(tsLong.toString());
private static String[] generateOauthParams(int page) {
return new String[]{
"oauth_consumer_key=" + APP_KEY,
"oauth_signature_method=HMAC-SHA1",
"oauth_timestamp=" +
Long.valueOf(System.currentTimeMillis() * 2).toString(),
"oauth_nonce=" + nonce(),
"oauth_version=1.0",
"format=json"};
}
private static String signature(String[] params) {
String[] p = {RecipeActivity.APP_METHOD, Uri.encode(RecipeActivity.APP_URL), Uri.encode(paramify(params))};
String s = join(p, "&");
SecretKey sk = new SecretKeySpec(APP_SECRET.getBytes(), HMAC_SHA1_ALGORITHM);
try {
Mac m = Mac.getInstance(HMAC_SHA1_ALGORITHM);
m.init(sk);
haang = Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
return haang;
} catch (java.security.NoSuchAlgorithmException | java.security.InvalidKeyException e) {
Log.w("FatSecret_TEST FAIL", e.getMessage());
return null;
}
}
//signature method
//is is never used
public JSONObject searchRecipes(String searchRecipes, int page) {
List<String> params = new ArrayList<>(Arrays.asList(generateOauthParams(page)));
String[] template = new String[1];
params.add("method=recipes.search");
params.add("search_expression=" + Uri.encode(searchRecipes));
params.add("oauth_signature=" + signature(params.toArray(template)));
JSONObject foods = null;
try {
URL url = new URL(APP_URL + "?" + paramify(params.toArray(template)));
URLConnection api = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(api.getInputStream()));
while ((line = reader.readLine()) != null) builder.append(line);
JSONObject food = new JSONObject(builder.toString()); // { first
foods = food.getJSONObject("recipes"); // { second
} catch (Exception exception) {
Log.e("Json error", exception.toString());
exception.printStackTrace();
}
return foods;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
System.out.println("haang"+haang);
final RequestQueue requestQueue = Volley.newRequestQueue(RecipeActivity.this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, APP_URL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("success", response);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error",error.getMessage());
}
});
requestQueue.add(stringRequest);
}
}
But i am getting error. i am tring to get the data in Xml form.here is my logcat.I am new to this concept and have no idea what i am doing wrong.
<error xmlns="http://platform.fatsecret.com/api/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://platform.fatsecret.com/api/1.0/ http://platform.fatsecret.com/api/1.0/fatsecret.xsd">
<code>2</code>
<message>Missing required oauth parameter: oauth_signature_method</message>
</error>
why i am getting this error .please guide me.
Here's the JSON I'm parsing.
<item>{\"name\":{\"mainName\":\"Ham and cheese
sandwich\",\"alsoKnownAs\":[]},\"placeOfOrigin\":\"\",\"description\":\"A ham and cheese
sandwich is a common type of sandwich. It is made by putting cheese and sliced ham
between two slices of bread. The bread is sometimes buttered and/or toasted. Vegetables
like lettuce, tomato, onion or pickle slices can also be included. Various kinds of
mustard and mayonnaise are also
common.\",\"image\":\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Grilled_ham_and_cheese_014.JPG/800px-Grilled_ham_and_cheese_014.JPG\",\
"ingredients\":[\"Sliced
bread\",\"Cheese\",\"Ham\"]}
alsoKnownAs and ingredients arrays don't have keys. I need to convert them to lists and add them to the Sandwich object. Currently, it doesn't work. I thought the code inside the for loop would be enough. Can someone please take a look? Thank you in advance.
I based my code on the answers in this thread: Converting JSONarray to ArrayList
Also, one of the posters in the above thread suggested using a helper method from this link(line 45).
https://gist.github.com/codebutler/2339666
My code:
public static Sandwich parseSandwichJson(String json) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(json)) {
return null;
}
Sandwich sandwiches = null;
try {
// Create a JSONObject from the JSON file
JSONObject jsonObject = new JSONObject(json);
//fetch JSONObject named name
JSONObject objectName = jsonObject.getJSONObject("name");
// Extract the value for the key called "main_name"
String mainName = "";
if (objectName.has("mainName")) {
mainName = objectName.optString(KEY_MAIN_NAME);
}
JSONArray alsoKnownAsArray = objectName.optJSONArray(KEY_ALSO_KNOWN_AS);
List<String> alsoKnownData = new ArrayList();
for (int i = 0; i < alsoKnownAsArray.length(); i++) {
alsoKnownData.add(alsoKnownAsArray.getString(i));
}
String placeOfOrigin = "";
if (objectName.has("placeOfOrigin")) {
placeOfOrigin = objectName.optString(KEY_PLACE_OF_ORIGIN);
}
String description = "";
if (objectName.has("description")) {
description = objectName.optString(KEY_DESCRIPTION);
}
String image = "";
if (objectName.has("image")) {
image = objectName.optString(KEY_IMAGE);
}
JSONArray ingredientsArray = objectName.optJSONArray(KEY_INGREDIENTS);
List<String> ingredientsData = new ArrayList<String>();
if (ingredientsArray != null) {
for (int i = 0; i < ingredientsArray.length(); i++) {
ingredientsData.add(ingredientsArray.getString(i));
}
}
Sandwich sandwich = new Sandwich(mainName, alsoKnownAsArray, placeOfOrigin, description, image, ingredientsArray);
sandwiches.add(sandwich);
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing sandwich JSON results", e);
}
// Return the list of sandwiches
return sandwiches;
}
You can parse the JSON this way:
public class JsonUtils {
public static Sandwich parseSandwichJson(String json) {
try {
JSONObject mainJsonObject = new JSONObject(json);
JSONObject name = mainJsonObject.getJSONObject("name");
String mainName = name.getString("mainName");
JSONArray alsoKnownAsArray = name.getJSONArray("alsoKnownAs");
List<String> alsoKnownAs = new ArrayList<>(alsoKnownAsArray.length());
for ( int i = 0; i < alsoKnownAsArray.length(); i++ ) {
alsoKnownAs.add(alsoKnownAsArray.getString(i));
Log.i("alsoKnownAs", "I am here" + alsoKnownAs);
}
String placeOfOrigin = mainJsonObject.optString("placeOfOrigin");
String description = mainJsonObject.getString("description");
String image = mainJsonObject.getString("image");
JSONArray ingredientsArray = mainJsonObject.getJSONArray("ingredients");
List<String> ingredients = new ArrayList<>(ingredientsArray.length());
for ( int i = 0; i < ingredientsArray.length(); i++ ) {
Log.i("ingredients", "These are the ingredients" + ingredients);
ingredients.add(ingredientsArray.getString(i));
}
return new Sandwich(mainName, alsoKnownAs, placeOfOrigin, description, image, ingredients);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Use Gson for parsing (https://github.com/google/gson)
Add this 2 class for data handle
public class CustomData
{
private List<String> ingredients;
private String placeOfOrigin;
private String description;
private Name name;
private String image;
public List<String> getIngredients ()
{
return ingredients;
}
public void setIngredients (List<String> ingredients)
{
this.ingredients = ingredients;
}
public String getPlaceOfOrigin ()
{
return placeOfOrigin;
}
public void setPlaceOfOrigin (String placeOfOrigin)
{
this.placeOfOrigin = placeOfOrigin;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public Name getName ()
{
return name;
}
public void setName (Name name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
Class Name:
public class Name
{
private String[] alsoKnownAs;
private String mainName;
public String[] getAlsoKnownAs ()
{
return alsoKnownAs;
}
public void setAlsoKnownAs (String[] alsoKnownAs)
{
this.alsoKnownAs = alsoKnownAs;
}
public String getMainName ()
{
return mainName;
}
public void setMainName (String mainName)
{
this.mainName = mainName;
}
}
Function to parse JSON to Object
public CustomData parseJsonToData(String jsonString) {
CustomData data = new Gson().fromJson(jsonString, CustomData.class);
return data;
}
So you can get List by
CustomData data = parseJsonToData(jsonString)
List<String> ingredients = data.getIngredients()
I'm populating a ListView from DB. The recordset from the DB contains the Zipcode which is then transformed into City and State using google map api and then set to Listview Item.
I need to be able to set the value that is being returned from the background class in Listview. Any guidance would be very much appreciated. Thanks in advance.
for (int i = 0; i < zipcodes.getLength(); i++) {
GetCityStateInfoFromPostalCode getCityStateInfoFromPostalCode = new GetCityStateInfoFromPostalCode(getActivity(), "110001", "ta");
String mCityState = getCityStateInfoFromPostalCode.getCityState();
}
Here's Background Class that fetches the info from Google maps api
public class GetCityStateInfoFromPostalCode extends AsyncTaskLoader<String> {
private String URL;
private String mState = "";
private String mCity = "";
private Context mContext;
public String getCityState() {
return mCityState;
}
private String mCityState = "";
public GetCityStateInfoFromPostalCode(Context context, String postalCode, String language) {
super(context);
this.mContext = context;
URL = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:" + postalCode + "&language=" + language;
// Kick start the load process
forceLoad();
}
public String loadInBackground() {
JSONObject jsonObject;
JSONArray jsonRootArray;
JSONArray jsonAdressArray;
JSONObject addressComponentCityObject;
JSONObject addressComponentStateObject;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
httpGet.addHeader("content-type", "application/json");
try {
HttpResponse resp = client.execute(httpGet);
String json = EntityUtils.toString(resp.getEntity(), "UTF-8");
jsonObject = new JSONObject(json);
addressComponentCityObject = new JSONObject();
addressComponentStateObject = new JSONObject();
jsonRootArray = jsonObject.getJSONArray("results");
//This points to "0"
JSONObject rootJson = jsonRootArray.getJSONObject(0);
//This points to address components
jsonAdressArray = rootJson.getJSONArray("address_components");
//This points to Object 1 (Second object of the jsonAddressArray)
addressComponentCityObject = jsonAdressArray.getJSONObject(1);
mCity = addressComponentCityObject.getString("long_name");
addressComponentStateObject = jsonAdressArray.getJSONObject(3);
mState = addressComponentStateObject.getString("long_name");
} catch (Throwable t) {
// Handle error here
t.printStackTrace();
}
this.mCityState = mCity + ", " + mState;
return mCityState;
}
}
with AsyncTask you can generate and override the methods below :
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
I hope this will help you :)
Imagine I have an object - ChildObject. ChildObject has 3 properties. Id, Name, Age.
I also have another object - ParentObject. ParentObject also has 3 properties. Id, Date but the 3rd is ArrayList of ChildObjects Family.
How would I go about converting this into a JSONObject to be able to send it over to a RESTfull WebAPI service.
So far I have failed to find anything that works, and I'm struggling to wrap my head around the problem.
To make it more of a challenge I cant use 3rd party extentions (eg gson etc).
Thanks in advance for your help.
Adding Objects to see if they make it any clearer
ParentObject
public class JobMovementRequestDto {
public String Id_Employee;
public String ActionDate;
public String Id_Terminal;
public String Id_Device;
public ArrayList<JobActivityRequestDto> FromJobs;
public ArrayList<JobActivityRequestDto> ToJobs;
public JobMovementRequestDto(){
}
public JobMovementRequestDto(String idEmployee, String activityDate, String idTerminal, String idDevice, ArrayList<JobActivityRequestDto> fromItems, ArrayList<JobActivityRequestDto> toItems){
this.Id_Employee = idEmployee;
this.ActionDate = activityDate;
this.Id_Terminal = idTerminal;
this.Id_Device = idDevice;
this.FromJobs = fromItems;
this.ToJobs = toItems;
}
public String getIdEmployee() {return this.Id_Employee;}
public String getActivityDate() {return this.ActionDate;}
public String getIdTerminal() {return this.Id_Terminal;}
public String getIdDevice() {return this.Id_Device;}
public ArrayList<JobActivityRequestDto> getFromList() {return this.FromJobs;}
public ArrayList<JobActivityRequestDto> getToLIst() { return this.ToJobs;}
ChildObject
public class JobActivityRequestDto {
public String Id_Job;
public String Id_Batch;
public String Id_ActivityType;
public JobActivityRequestDto()
{
}
public JobActivityRequestDto(String idJob, String idBatch, String idActivityType)
{
this.Id_Job = idJob;
this.Id_Batch = idBatch;
this.Id_ActivityType = idActivityType;
}
public String getIdJob() { return this.Id_Job;}
public String getIdBatch() {return this.Id_Batch;}
public String getIdActivityType() {return this.Id_ActivityType;}
}
Here is your complete solution, Please check.
public void makeJsonObject()
{
try
{
JSONObject parentJsonObject = new JSONObject();
parentJsonObject.put("Id", parentObject.getId());
parentJsonObject.put("Id", parentObject.getDate());
JSONArray childListArr = new JSONArray();
for (int i = 0; i < parentObject.ChildObjectsList().size(); i++)
{
ChildObject childObject = parentObject.ChildObjectsList().get(i);
JSONObject childJsonObject = new JSONObject();
childJsonObject.put("id", childObject.getId());
childJsonObject.put("Name", childObject.getName());
childJsonObject.put("Age", childObject.getAge());
childListArr.put(childJsonObject);
}
parentJsonObject.put("childList", childListArr);
Log.e(TAG, "parentJsonObject=="+parentJsonObject.toString(4));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
JSONObject fromObject, toObject, parentObject;
JSONArray fromArray, toArray;
JobMovementRequestDto JMRD = new JobMovementRequestDto();
try {
parentObject = new JSONObject();
parentObject.put("Id_Employee", JMRD.getIdEmployee());
parentObject.put("ActionDate", JMRD.getActivityDate());
parentObject.put("Id_Terminal", JMRD.getIdTerminal());
parentObject.put("Id_Device", JMRD.getIdDevice());
fromArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getFromList()){
//Loop your multiple childObjects and add it childArray
fromObject = new JSONObject();
fromObject.put("Id_Job",JARD.getIdJob());
fromObject.put("Id_Batch",JARD.getIdBatch());
fromObject.put("Id_ActivityType",JARD.getIdActivityType());
fromArray.put(fromObject);
}
toArray = new JSONArray();
for(JobActivityRequestDto JARD : JMRD.getToLIst()){
//Loop your multiple childObjects and add it childArray
toObject = new JSONObject();
toObject.put("Id_Job",JARD.getIdJob());
toObject.put("Id_Batch",JARD.getIdBatch());
toObject.put("Id_ActivityType",JARD.getIdActivityType());
toArray.put(toObject);
}
//Finally, Add childArray to ParentObject.
parentObject.put("fromObjects",fromArray);
parentObject.put("toObjects",toArray);
} catch (JSONException e) {
e.printStackTrace();
}
Create a JSON like this and You Can Send This to Your Server. I Hope This Is What You Want Right?
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 )