When added JSONObject method, Limited Json in Android - android

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 )

Related

How to convert Json array to List<string>?

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()

how to retrieve below json data from server in android?

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'

How to form json array in android to send to server?

I have created an Api which is used to add multiple invitations in the database called as sendMultipleInvites.
Now I want to implement this API in android. I am trying to create an AsyncTask to call the api. I have helper class to connect to http server.
I am testing this in postman: my input should be like this:
{
"invitations": [
{
"date" : "12/08/2016",
"invitee_no" : "196756456",
"status" : "1",
"user_name" : "user10"
},
{
"date" : "12/08/2016",
"invitee_no" : "13633469",
"status" : "1",
"user_id" : "user9"
}
]
}
My serverRequest class:
public class ServerRequest {
String api;
JSONObject jsonParams;
public ServerRequest(String api, JSONObject jsonParams) {
this.api = api;
this.jsonParams = jsonParams;
}
public JSONObject sendRequest() {
try {
URL url = new URL(api);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(jsonParams.toString());
writer.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while ( (line = reader.readLine()) != null ){
sb.append(line);
}
reader.close();
Log.d("ServerResponse", new String(sb));
return new JSONObject(new String(sb));
} else {
throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode);
}
} catch (MalformedURLException me) {
me.printStackTrace();
return Excpetion2JSON.getJSON(me);
} catch(IOException ioe) {
ioe.printStackTrace();
return Excpetion2JSON.getJSON(ioe);
} catch(UnexpectedServerException ue) {
ue.printStackTrace();
return Excpetion2JSON.getJSON(ue);
} catch (JSONException je) {
je.printStackTrace();
return Excpetion2JSON.getJSON(je);
}
}
public ServerRequest(String api) {
this.api = api;
}
}
This is my asyncTask :
public class SendMultipleInvitesAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject> {
private Context context;
public SendInviteAsyncTask(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
}
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("status");
String message = jsonObject.getString("message");
if (result == 1) {
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
} catch (JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Edit:
Trying like this it is giving an error when I try to pass an arraylist to the execute method of async task.
AsyncTask:
public class SendInviteAsyncTask extends AsyncTask<ArrayList<Invitation>, Void, JSONObject> {
private ProgressDialog progressDialog;
private Context context;
public SendInviteAsyncTask(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
}
#Override
protected JSONObject doInBackground(ArrayList<Invitation>... arrayLists) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
Activity:
public class SendMultipleInvites extends AppCompatActivity {
private ArrayList<Invitation> invitationArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_multiple_invites);
invitationArrayList = new ArrayList<>();
Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");
invitationArrayList.add(invitation);
invitation = new Invitation("3","17/02/2016","282751221","1","user10");
invitationArrayList.add(invitation);
new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(invitationArrayList);
}
}
I was using hash map to send key and values. How can I do to send a json array?
How to modify my async Task? How can I send array to an async task? Can anyone help please.. Thank you..
To pass Array to your async Task do this:
SendInviteAsyncTask extends AsyncTask<ArrayList<Sring>, Void, JSONObject>
To make a Json object you can use Gson library
try this
JSONObject obj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject()
reqObj.put( "ctrlId", "txt1" );
req.put( reqObj );
reqObj = new JSONObject();
reqObj.put( "ctrlId", "txt2" );
req.put( reqObj );
obj.put( "req", req );
You can really simplify your code by using a few libraries for building json and sending http requests. Here is sample code using Gson for building the json string and Volley for the http request.
I also used this fantastic project for generating the json pojo objects below. It makes really quick work of it.
Invite ivt = new Invite();
ivt.getInvitations().add( new Invitation("3","17/02/2016","55165122","1","user10"));
ivt.getInvitations().add( new Invitation("3","17/02/2016","282751221","1","user10"));
Gson gson = new Gson();
String jsonString = gson.toJson(ivt);
String url = appContext.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
RequestQueue queue = Volley.newRequestQueue(appContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("TAG", "success: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
Invite.java
public class Invite {
#SerializedName("invitations")
#Expose
private List<Invitation> invitations = new ArrayList<Invitation>();
public List<Invitation> getInvitations() {
return invitations;
}
public void setInvitations(List<Invitation> invitations) {
this.invitations = invitations;
}
}
Invitation.java
public class Invitation {
#SerializedName("date")
#Expose
private String date;
#SerializedName("invitee_no")
#Expose
private String inviteeNo;
#SerializedName("status")
#Expose
private String status;
#SerializedName("user_name")
#Expose
private String userName;
#SerializedName("user_id")
#Expose
private String userId;
public Invitation(String d, String one, String two, String three, String four) {
date = d;
inviteeNo = one;
status = two;
userName = three;
userId = four;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInviteeNo() {
return inviteeNo;
}
public void setInviteeNo(String inviteeNo) {
this.inviteeNo = inviteeNo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}

How to show other objects from json in Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
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);
//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 set images from medium ? thanks all <3
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.getJSONArray("posts");
for (int i= 0; i < postsArray.length(); i++){
JSONObject postObject = postsArray.getJSONObject(i);
int id = postObject.getInt("id");
String title = postObject.getString("title");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.getJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "id: " + id);
Log.d("Data", "title: " + title);
//log other data
Log.d("Data", "the mediumObj url: " + mediumImage);
}
} catch (JSONException e) {
e.printStackTrace();
}

How to show other Json objects in RecylerView on Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts.
I can show title, description and thumbnail. but i want show medium from thumbnail_images instance of thumbnail. I don't know how to read images from medium ?!
My Json Link : Link
AsyncTaskCodes:
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");
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(
postObject.getInt("id"),
postObject.getString("title"),
postObject.getString("content"),
postObject.getString(mediumImage)));
}
} 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);
}
}
}
}
for fetch medium image i use this code :
//get other data
JSONObject imageObj = postObject.getJSONObject("thumbnail_images");
JSONObject mediumObj = imageObj.optJSONObject("medium");
String mediumImage = mediumObj.getString("url");
but when set mediumImage for infoModels.add(new MainDataModel() not show me any posts!
How can set images from medium ? thanks all <3
private void setImageWithPicaso(String imageUrl) {
if (!(imageUrl == null)) {
Picasso.with(getActivity()).load(imageUrl).placeholder(R.drawable.placeholder_background).into(imageView, new Callback() {
#Override
public void onSuccess() {
//On Success
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
//On Error
}
});
} else {
spinner.setVisibility(View.GONE);
//On Error
}
}

Categories

Resources