Why does Gson library show null value when debugging? - java

I am parsing the Json and display on list view using gson library. When I insert my input stream I am getting null values. Can you please tell where I am wrong I will give you steps
I downloaded 2.3 Gson library. Then I make getter and setter
------------------
package com.firstgroup.webservice;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.firstgroup.dto.Holder;
import com.firstgroup.webservicecallback.WebserviceCallBack;
import com.google.gson.Gson;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class RequestTask extends AsyncTask<String, String, String>{
private WebserviceCallBack callBack;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog= new ProgressDialog((Context) callBack);
super.onPreExecute();
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Webservice Call...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
// I am getting correct result here ...
Reader reader = new InputStreamReader(response.getEntity().getContent());
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..\
progressDialog.hide();
} catch (IOException e) {
//TODO Handle problems..
progressDialog.hide();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
if(callBack!=null){
callBack.getWebserviceResponse(result);
}
progressDialog.hide();
}
public void setObserver(WebserviceCallBack callback){
callBack=callback;
}
}
callback on main activity:
#Override
public void getWebserviceResponse(String response) {
// TODO Auto-generated method stub
Log.d("response", response);
//can I used this code ?
// I want to used gson in main activity?
Reader reader = new InputStreamReader(response.getEntity().getContent());
Gson gson = new Gson();
Holder response1 = gson.fromJson(reader, Holder.class);
}
}

Add a class:
public class Holder {
List<deparaturedaseboarddto> data;
}
And change your below code:
deparaturedaseboarddto response1 = gson.fromJson(reader, deparaturedaseboarddto.class);
to:
Holder response1 = gson.fromJson(reader, Holder.class);
Reason: Your json text value has a root object named as data and it has a list of deparaturedaseboarddto. You are trying to deserialize this json value to a deparaturedaseboarddto instance but it is an object which has a list of deparaturedaseboarddto.
Also (not relevant to your error);
1) Class names starts with capital letters, and field names are camel case at Java.
2) You don't have to use #SerializedName if the java class's field name
is same with the json value's field name.
3) Below mapping is probably prevent an error because there are no fields at json value named as Result. #SerializedName("Result") may be removed or replaced with #SerializedName("alertsId")
#SerializedName("Result")
int alertsId;
4) Also may want to replace below code:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
with:
responseString = gson.toJson(response1);
Edit for the second question at the comment:
If you want to use retrieve Holder instance from AsyncTask, make below edits.
Change this:
public class RequestTask extends AsyncTask<String, String, String>
with this:
public class RequestTask extends AsyncTask<String, String, Holder>
and:
protected String doInBackground(String... uri)
with this:
protected Holder doInBackground(String... uri)
and this:
protected void onPostExecute(String result)
with this:
protected void onPostExecute(Holder result)

Related

How to get the returned value of AsyncTask in android studio

Helloo, I know there is a lot of posts abnout this but ITS SO confusing i'v read alot of them but i can't manage to solve a simple probleme. All i want is to get a Class from my main activity.kt when i do
val QuizzList = Network().execute(); (in main activity.kt)
I want QuizzList to be my class, not a Async task blabla.
What do i need to do in here to make this task returns a QuizCollection (its a custom class)?
package com.example.myapplication;
import android.os.AsyncTask;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Network extends AsyncTask<String, Integer, Object> {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public Network() {
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected QuizCollection doInBackground(String... params) {
try {
// On doit utiliser cet adresse URL, le 127.0.0.1 ne marche pas a cause du serveur qui
// Roule deja sur l'adresse.
//Get the content from the server
URL url = new URL("http://10.0.2.2:8080/api/quizz");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
Gson gson = new Gson();
JSONArray jsonArray = new JSONArray(content.toString());
System.out.println("Le content : "+content.toString());
QuizCollection quizz = new QuizCollection();
for (int i=0; i<jsonArray.length();i++){
System.out.println(jsonArray.get(0).toString());
Quiz quiz = gson.fromJson(jsonArray.getJSONObject(i).toString(), Quiz.class);
System.out.println("Titre "+quiz.Title);
quizz.addQuiz(quiz);
}
System.out.println("ca fonctionne?"+quizz.QuizArray.get(0).Title);
in.close();
return quizz;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Object page)
{
//onPostExecute
}
}
You should use callback
public interface OnTaskCompleted{
void onTaskCompleted(QuizCollection collection);
}
In your Activity:
//do whatever you want with collection which is the object returned from AsyncTask
Network(OnTaskCompleted { collection -> collection.toString() }).execute()
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,QuizCollection >{
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected QuizCollection doInBackground(String... params) {
return new QuizCollection();
}
protected void onPostExecute(QuizCollection collection){
// your stuff
listener.onTaskCompleted(collection);
}
}
I had to do this
protected void onPostExecute(QuizCollection result)
{
//onPostExecute
super.onPostExecute(result);
}
And do a .get() after calling execute

Extract json data from an api array or matrix java android studio

I can't extract data from this json. I believe it is because it is an array. I read about it but I didn't find anything specific for this case.
I just need to take the values ​​individually each time I close {}.
Eg: result [0] .getLoterias();
== INSTANTANEA
The connection is being made normally, I just can't extract the data.
httpservice2.java
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Gson().fromJson(resposta.toString(), CEP2.class);
}
}
Main3Activity.java:
package br.com.matheuscastiglioni.blog.requisicao_http;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutionException;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
import br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2;
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
final TextView resposta = findViewById(R.id.etMain_resposta2);
final TextView cep = findViewById(R.id.etMain_resposta3);
final TextView token = findViewById(R.id.etMain_resposta4);
Bundle extras = getIntent().getExtras();
String respostatoken = extras.getString("token");
String respostaid = extras.getString("id");
cep.setText(respostaid);
token.setText(respostatoken);
//alert(cep.getText().toString() + token.getText().toString());
try {
CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get();
String loteria = retorno.getIdloteria();
resposta.setText(loteria);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private void alert(String s) {
Toast.makeText(this,s,Toast.LENGTH_LONG).show();
}
}
CEP2.java:
package br.com.matheuscastiglioni.blog.requisicao_http.model;
public class CEP2 {
private String idloteria;
public String getIdloteria() {
return idloteria;
}
public void setIdloteria(String idloteria) {
this.idloteria = idloteria;
}
}
currently:
I changed
return new Gson().fromJson(resposta.toString(), CEP2.class);
per
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
httpservic2 new:
package br.com.matheuscastiglioni.blog.requisicao_http.service;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
public class HttpService2 extends AsyncTask<Void, Void, CEP2> {
private final String cep;
private final String token;
public HttpService2(String cep, String token) {
this.cep = token;
this.token = cep;
}
#Override
protected CEP2 doInBackground(Void... voids) {
StringBuilder resposta = new StringBuilder();
try {
URL url = new URL( "A" + this.cep + "&token=" + this.token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.connect();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
resposta.append(scanner.next());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
}
}
I need to change the return from doinbackground However, I'm lost
It seems you only want the idloteria from the response which should be fine. But as you say it's an array and it should be parsed as an array or a List.
The:
return new Gson().fromJson(resposta.toString(), CEP2.class);
Should be
Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;
If you want the response be parsed as a list.
Another possibility is to get the data parsed as an array:
CEP2[] cep2Array = new Gson().fromJson(resposta.toString(), CEP2[].class);
return cep2Array;
and you'll need to change the return of the doInBackground in accordance with the response type you choose.
Lets choose to return a list. In this case change AsyncTask<Void, Void, CEP2> to AsyncTask<Void, Void, List<CEP2>> and also protected CEP2 doInBackground to protected List<CEP2> doInBackground.
The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List). And in this onPostExecute you can save the list, print it or do whatever you want to do with the received data.
But keep in mind that AsyncTask are deprecated in API level R. It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.

Android: JSON parsing error nothing comes up

I am trying to parse JSON, I have done it there before but not quiet this way. I spent hours trying to solve the problem, but I dont know what is wrong with the code.I am attaching the entire code for the activity, Web Request class and the layout. Any help will be greatly appreciated.
I get this error
java.io.FileNotFoundException: /data/system/users/sdp_engine_list.xml: open failed: ENOENT (No such file or directory)
05-19 18:17:27.427 3450-3450/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
05-19 18:17:28.232 3450-3592/? W/DisplayManagerService: Failed to notify process 20004 that displays changed, assuming it died.
This is the activity Transactions class.
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import com.rectuca.iyzicodemo.Classes.Transaction;
import com.rectuca.iyzicodemo.Library.WebRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Transactions extends ListActivity {
// URL to get contacts JSON
private static String url = "http://www.mocky.io/v2/573dbd243700005f194dcdcc";
// JSON Node names
private static final String TAG_PAYMENTS= "payments";
private static final String TAG_PAYMENT_ID = "paymentId";
private static final String TAG_SENT_BY = "sentBy";
private static final String TAG_DATE_TIME = "dateTime";
private static final String TAG_SENT_TO = "sentTo";
private static final String TAG_BANK_NAME = "bankName";
private static final String TAG_INSTALLMENTS = "installments";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_3DS = "threeDs";
private static final String TAG_CANCELLED = "cancelled";
private static final String TAG_RETURNED = "returned";
private static final String TAG_TRANSACTION_STATUS = "transactionStatus";
private static final String TAG_BLOCKAGE_AMOUNT = "blockage_amount";
private static final String TAG_BLOCKAGE_RELEASE_DATE = "blockageReleaseDate";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
// Calling async task to get json
new GetInfo().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetInfo extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ArrayList<HashMap<String, String>> transactionInfoList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(Transactions.this);
proDialog.setMessage("Please Wait...");
proDialog.setCancelable(false);
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
WebRequest webReq = new WebRequest();
// Making a request to url and getting response
String jsonStr = webReq.makeWebServiceCall(url, WebRequest.GET);
Log.d("Response: ", "> " + jsonStr);
transactionInfoList = ParseJSON(jsonStr);
return null;
}
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
transactionInfoList=new ArrayList<HashMap<String, String>>();
ListAdapter adapter = new SimpleAdapter(
Transactions.this, transactionInfoList,
R.layout.row_layout, new String[]{TAG_SENT_TO,TAG_DATE_TIME
,TAG_BANK_NAME,TAG_AMOUNT,TAG_3DS, TAG_CANCELLED,
TAG_RETURNED},
new int[]{R.id.name,R.id.dateTime ,R.id.bankName,R.id.amount,
R.id.threeDS, R.id.cancelled, R.id.returned});
setListAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> paymentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray payments = jsonObj.getJSONArray(TAG_PAYMENTS);
// looping through All Payments
for (int i = 0; i < payments.length(); i++) {
JSONObject c = payments.getJSONObject(i);
String dateTime =c.getString(TAG_DATE_TIME);
String sentTo =c.getString(TAG_SENT_TO);
String bankName =c.getString(TAG_BANK_NAME)+" ( "+c.getString(TAG_INSTALLMENTS)+" ) " ;
String amount =c.getString(TAG_AMOUNT);
String threeDS =c.getString(TAG_3DS);
String cancelled =c.getString(TAG_CANCELLED);
String returned =c.getString(TAG_RETURNED);
// temporary hashmap for a single payment
HashMap<String, String> payment = new HashMap<String, String>();
// adding every child node to HashMap key => value
payment.put(TAG_DATE_TIME, dateTime);
payment.put(TAG_SENT_TO, sentTo);
payment.put(TAG_BANK_NAME, bankName);
payment.put(TAG_AMOUNT, amount);
payment.put(TAG_3DS, threeDS);
payment.put(TAG_CANCELLED, cancelled);
payment.put(TAG_RETURNED, returned);
// adding student to students list
paymentList.add(payment);
}
return paymentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
This is the WebRequest Class
package com.rectuca.iyzicodemo.Library;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class WebRequest {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* #url - url to make request
* #requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* #url - url to make request
* #requestmethod - http request method
* #params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
This is what I am trying to do
http://lh3.googleusercontent.com/JqcySZU2Pz067NutlDvPP5Zq_3n_WSAllIuEdjQjOjyeGkKguaMNCrltaKbjBCi16g=h900-rw
I would suggest you to use
VOLLEY networking library by google
You should try to use Volley JSONOBJECTREQUEST() and you won't have any issue after that parsing will be easier.
add this to dependency section of your app
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

get XML from server by URL in AsyncTask and return response to UI

I try to get xml from server in async task, but my doInBackground method returns me NULL. Where is my mistake? And how I can send result to UI?
Here is all classes
I have this code for getting xml from server:
package classes;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created by Mikhail on 28.03.2015.
*/
public class GetXMLFromServer {
InputStreamReader reader;
public GetXMLFromServer(){
//reader = null;
}
public InputStreamReader getReaderWithXML(String url){
GetXMlTask task = new GetXMlTask();
task.execute(url);
return reader;
}
public void setReader(InputStreamReader newReader){
this.reader = newReader;
}
class GetXMlTask extends AsyncTask<String, Integer, InputStreamReader>{
#Override
protected InputStreamReader doInBackground(String... params) {
InputStreamReader iStream = null;
try {
iStream = new InputStreamReader(getUrlData(params[0]));
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return iStream;
}
#Override
protected void onPostExecute(InputStreamReader inputStreamReader) {
super.onPostExecute(inputStreamReader);
setReader(inputStreamReader);
}
public InputStream getUrlData(String urlString) throws URISyntaxException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(String.valueOf(new URL(urlString)));
HttpResponse res = client.execute(method);
StatusLine status = res.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d("APP", "HTTP error.Invalid server status code: " + res.getStatusLine());
}
return res.getEntity().getContent();
}
}
}
You have a good example how to use async task here.
Please check it!
The returning is in onPostExecute method.
To send the result to UI use OnPostExecute do call a static method of your UI class.
protected void onPostExecute(Long result) {
YourUIFragmentORActivity.showResult(result);
showDialog("Downloaded " + result + " bytes");
}

android post and receive json Asyc

I am working on an android application that posts a JSON object to a server and gets one back in response. I am stuck in how to get the JSON that the server responds with back to the main thread. Below is the code that I have so far. Even after I run my background process, when I call getResponse it returns null.
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
public class AsyncHttpPost extends AsyncTask<String, String, HttpResponse> {
private JSONObject mData = null;// post data
private HttpResponse response = null;
/**
* constructor
*/
public AsyncHttpPost(JSONObject json) {
mData = json;
}
public HttpResponse getResponse() {
return response;
}
/**
* background
*/
#Override
protected HttpResponse doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
try {
post.setEntity(new StringEntity(mData.toString()));
response = client.execute(post);
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return response;
}
}
U need to get data first , have u create a an adapter for it ?
when u want to get something using json, for an example title
this is how it loooks like.. you would also need to write in your main activity(depending what java use to display) to display the data.
I help this will help you. C:
//Declare variables
String title;
// call out the variables
public (ClasName) (String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

Categories