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;
}
}
Related
Hey guys i am new to Android networking concepts.I want to send username,password,imei number and location to the php server from android app.I am done my sending part.now my question is how to receive the response.i want to get the status (1 or 0) according to that i want to move to the next page.so anyone will know how to do this you are welcome.
private static final String REGISTER_URL="http://vPC70.com/App/login.php";
username = editTextUserName.getText().toString().toLowerCase();
userpassword=editTextPassword.getText().toString().toLowerCase();
loc="11.295756,77.001890";
imeino = "12312312456";
register(username, userpassword, imeino, loc);
private void register(final String username, final String userpassword,
String imeino, String loc) {
String urlSuffix = "?
username="+username+"&userpassword="+userpassword+"&imeino="+imeino
+"&location="+loc;
class RegisterUser extends AsyncTask<String,String , String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this, "Please
Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL+s);
HttpURLConnection con = (HttpURLConnection)
url.openConnection();
bufferedReader = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
}catch(Exception e){
return null;
}
}
}
RegisterUser ru = new RegisterUser();
ru.execute(urlSuffix);
this is the response
{"Login":[{"status":"1","message":"Login Successfully !!!"}]}
{"Login":[{"status":"0","message":"Invalid Password !!!"}]}
if the response is 1 toast the message login sucessfully
if the response is 0 toast the message invalid password in post execute
After getting the response from server,based on status display the message in toast
try {
JSONObject jobj = new JSONObject(response);
String status = jobj.getString("status");
String msg = jobj.getString("message");
if (status.equals("1")) {
//move to next page
Toast.makeText(LoginActivity.this, msg,Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, msg,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Create the POJO / Model class to convert your Response.
Like this
public class LoginResponse{
#SerializedName("Login")
#Expose
private List<Login> login = null;
public List<Login> getLogin() {
return login;
}
public void setLogin(List<Login> login) {
this.login = login;
}
}
public class Login {
#SerializedName("status")
#Expose
private String status;
#SerializedName("message")
#Expose
private String message;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
in PostExcecute convert the response to POJO object like this by using GSON
Gson gson = new Gson();
LoginResponse response = gson.toJson(result, LoginResponse.class);
Here you can check the conditions:;
if(response !=null && response.getLogin() !=null)
{
if(response.getLogin().getStatus().equalIgnoreCase("1"))
{
// show toast Login Successfully !!! and move to next screen
}
else if(response.getLogin().getStatus().equalIgnoreCase("0"))
{
// Invalid Password !!! your logic here
}
}
Here is the parser according to your response string
private void parseResponseJson(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response).getJSONArray("Login").getJSONObject(0);
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
}
In onPostExecute(String s) you can convert result into json and check status value like
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JsonObject object = new JsonObject(s);
if(object.optString("status").equals("1"))
{
// Your Logic here
}
}
Simple and Efficient solution. Use google's Gson library . You can easily create a hashmap from json string like this.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JSONString, type);
My scenario is i have 5 threads parallel call to happen in splash activity but i need to wait for one specific thread( which is DashBoardCallable) exectuion so that i can load dashboard data, show the splash screen untill dashboard data gets loaded and once dashboard data get loaded change the activity meanwhile in parallel i load some more data related to that user in background(which is thread util class will do ).
or you can understand this way i have a ExecutorService of 5 threads for parallel calls and Splashscreen is based on one thread execution out of 5. Once this thread execution is done change the activity leaving rest other thread execution in background.
below is splash activity code :
ExecutorService executor = Executors.newFixedThreadPool(5);
SharedPreferences sharedpreferences = getSharedPreferences(getResources().getString(R.string.mypreference_key), Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedpreferences.edit();
ThreadUtil datatype1 = new ThreadUtil(editor,3504,"URL","DATATYPE1","DATATYPE1");
ThreadUtil datatype2 = new ThreadUtil(editor,3504,"URL","DATATYPE2","DATATYPE2");
ThreadUtil datatype3 = new ThreadUtil(editor,3504,"URL","DATATYPE3","DATATYPE3");
ThreadUtil datatype4 = new ThreadUtil(editor,3504,"Different URL","DATATYPE1","DATATYPE1");
DashBoardCallable dashBoardCallable = new DashBoardCallable(SplashScreenActivity.this,3504);
FutureTask<String> dashboardFuture = new FutureTask<String>(dashBoardCallable);
executor.execute(datatype1);
executor.execute(datatype2);
executor.execute(datatype3);
executor.execute(datatype4);
executor.execute(dashboardFuture);
String response =dashboardFuture.get();
This is dashboaord callable :
public class DashBoardCallable implements Callable<String> {
private Context context;
private int user_id;
public DashBoardCallable(Context context,int user_id){
this.context = context;
this.user_id = user_id;
}
#Override
public String call() throws Exception {
HttpUtil httpUtil = new HttpUtil();
httpUtil.setUrl("URL");
httpUtil.setType("GET");
return httpUtil.getStringResponse();
}
}
this is threadUtil class:
public class ThreadUtil implements Runnable {
private int user_id;
private String url,type,stored_name;
private SharedPreferences.Editor editor;
public ThreadUtil( SharedPreferences.Editor editor, int user_id, String url, String type,String stored_name){
this.editor = editor;
this.user_id = user_id;
this.url = url;
this.type = type;
this.stored_name = stored_name;
}
#Override
public void run() {
HttpUtil httpUtil = new HttpUtil();
httpUtil.setUrl(url);
httpUtil.setType("GET");
String jsonresponse =httpUtil.getStringResponse();
Gson gson = new Gson();
switch (type){
case "DATATYPE1":
saveDATATYPE1(jsonresponse,gson,editor);
break;
case "DATATYPE2":
saveDATATYPE2(jsonresponse,gson,editor);
break;
case "DATATYPE3":
saveDATATYPE3(jsonresponse,gson,editor);
break;
}
}
private void saveDATATYPE1(String jsonresponse, Gson gson,SharedPreferences.Editor editor) {
if(!jsonresponse.equalsIgnoreCase("null")){
editor.putString(stored_name, jsonresponse);
editor.apply();
editor.commit();
}
}
private void saveDATATYPE2(String jsonresponse, Gson gson, SharedPreferences.Editor editor) {
try {
Type listType = new TypeToken<List<AssessmentPOJO>>() {}.getType();
ArrayList<AssessmentPOJO> dashboardCards = (ArrayList<AssessmentPOJO>) gson.fromJson(jsonresponse, listType);
for(AssessmentPOJO assessmentPOJO:dashboardCards){
System.out.println("XXBBXBXBXBXB -> "+assessmentPOJO.getName());
if(assessmentPOJO != null){
editor.putString(stored_name+assessmentPOJO.getId(), gson.toJson(assessmentPOJO));
editor.apply();
editor.commit();
}
}
}catch (JsonSyntaxException jse){
jse.printStackTrace();
}catch (Exception e){
}
}
private void saveDATATYPE3(String jsonresponse, Gson gson,SharedPreferences.Editor editor) {
if(!jsonresponse.equalsIgnoreCase("null")) {
Type listType = new TypeToken<List<CoursePOJO>>() {}.getType();
ArrayList<CoursePOJO> coursePOJOs = (ArrayList<CoursePOJO>)gson.fromJson(jsonresponse, listType);
for(CoursePOJO coursePOJO:coursePOJOs){
if(coursePOJO != null){
editor.putString(stored_name+coursePOJO.getId(), gson.toJson(coursePOJO));
editor.apply();
editor.commit();
}
}
}
}
}
this is HttpUtil class:
public class HttpUtil {
private String url;
private String type;
private HashMap<String,String> param;
private String postrequest;
public HttpUtil(){}
private int socketTimeOut=0, connectionTimeOut=0;
public HttpUtil(String url, String type, HashMap<String, String> param,String postrequest) {
this.url = url;
this.type = type;
this.param = param;
this.postrequest = postrequest;
}
public String getStringResponse(){
String jsonresponse="";
try {
System.out.println("url "+url);
System.out.println("type "+type);
HttpResponse httpResponse = getHttpResponse();
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
if(jsonresponse.equalsIgnoreCase("[]")){
jsonresponse="";
}
System.out.println("HttpUtil Response is .... " + jsonresponse);
} else {
return "null";
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonresponse;
}
public void getVoidResponse(){
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public HashMap<String, String> getParam() {
return param;
}
public void setParam(HashMap<String, String> param) {
this.param = param;
}
private HttpResponse getHttpResponse(){
HttpResponse httpResponse = null;
HttpClient httpclient = new DefaultHttpClient();
try{
switch(type){
case "GET":
if(socketTimeOut != 0 && connectionTimeOut != 0){
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
httpclient = new DefaultHttpClient(httpParameters);
}
httpResponse = httpclient.execute(new HttpGet(url));
break;
case "POST":
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(param != null) {
for (String key : param.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, param.get(key)));
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httpPost);
break;
case "PUT":
HttpPut httpPut = new HttpPut(url);
if(postrequest != null){
StringEntity se = new StringEntity(postrequest);
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
}
httpResponse = httpclient.execute(httpPut);
break;
default:
httpResponse = httpclient.execute(new HttpGet(url));
break;
} }catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}catch (JsonSyntaxException jse) {
jse.printStackTrace();
return null;
}catch (Exception e){
e.printStackTrace();
return null;
}
return httpResponse;
}
public String getPostrequest() {
return postrequest;
}
public void setPostrequest(String postrequest) {
this.postrequest = postrequest;
}
public int getSocketTimeOut() {
return socketTimeOut;
}
public void setSocketTimeOut(int socketTimeOut) {
this.socketTimeOut = socketTimeOut;
}
public int getConnectionTimeOut() {
return connectionTimeOut;
}
public void setConnectionTimeOut(int connectionTimeOut) {
this.connectionTimeOut = connectionTimeOut;
}
}
Based on the use of your threads I can tell you should be better to use AsyncTask.
Every AsyncTask must have a Callback and the Activity implement them so, after the task was completed, the Activity can keep control of the operations and take decisions.
For the tasks:
public class SplashScreenTask extends AsyncTask<Void, Void, Void> {
private Context context;
private SplashScreenTaskCallback listener = null;
public SplashScreenTask (Context context) {
this.context = context;
}
#Override
protected Void doInBackground (Void... params) {
// Do your tasks
return null;
}
#Override
public void onPreExecute () {
}
#Override
public void onPostExecute (Void v) {
if (listener != null) {
listener.OnSplashScreenTaskCompleted ();
}
}
public void setListener (SplashScreenTaskCallback listener) {
this.listener = listener;
}
public interface SplashScreenTaskCallback {
void OnSplashScreenTaskCompleted ();
}
}
And your activity:
public class SplashScreenActivity extends Activity implements SplashScreenTask.SplashScreenTaskCallback {
protected Runnable postDelayedAction;
private final Handler handler = new Handler();
#Override
public void onCreate (Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
handler.postDelayed(startBackgroundTasks, splashScreenDelay);
}
private Runnable startBackgroundTasks = new Runnable() {
#Override
public void run () {
// Do initial background tasks like sounds load
SplashScreenTask task = new SplashScreenTask (SplashScreenActivity.this);
task.setListener (SplashScreenActivity.this);
task.execute ();
}
};
#Override
public void OnSplashScreenTaskCompleted () {
// Here you take decisions
}
}
I would use the Rx zip operator to determine when all of your backgrounds tasks have completed. Determining the completion of multiple parallel jobs is a huge headache with the Android framework.
There is a best practice for showing a splash screen with no initial delay wherein you set the background drawable using themes. In order to do that and transition into your Activity (not your splash screen) where you can actually fire off all of this logic, simply duplicate the visuals of your splash screen in your Activity, and transition out of showing those visuals once your jobs have completed.
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 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 )
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
}
}