This is my Main Class.Can any one tell me why it s returning null in System.print().I have used Gson external libs.What i am doing wrong here.How can i display all contains
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
#Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.TITLE, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
Post po = gson.fromJson(reader, Post.class);
List<Post> posts = Arrays.asList(po);
System.out.println("ID:"+po);
content.close();
handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
//Post.java
public class Post {
#SerializedName("id")
public long ID;
public String TITLE;
public String AUTHOR;
public String URL;
#SerializedName("date")
public Date dateCreated;
public String body;
public List<Tag> tags;
public Post() {
}
public String toString() {
return "Student [id=" + ID + ", title="
+ TITLE + ", thumb_url=" + URL
+ ", dt=" + AUTHOR + "]";
}
}
There are a few things you need to consider. First of all, your fields need have proper #SerializedName("") annotation. It indicates that the property name (like thumb_url, dt) does not match the field name in your JSON. If both names do match, there is no need for the annotation.
Secondly, you need to "parse" the response that you get from the server to JsonObject and then read the JsonElement.
Here's the code you need:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yy-d-M hh:mm");
//2014-06-14 02:39:24
//yy-d-M hh:mm
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
JsonParser jsonParser = new JsonParser();
JsonObject details = jsonParser.parse(reader).getAsJsonObject();
JsonArray array = details.getAsJsonArray("veg_food");
for ( JsonElement element : array ){
Post post = gson.fromJson(element, Post.class);
posts.add(post);
}
System.out.println("ID:"+ posts);
Also, make sure you change your Post.java class to this:
#SerializedName("id")
public long ID;
#SerializedName("title")
public String TITLE;
#SerializedName("thumb_url")
public String URL;
#SerializedName("dt")
public Date dateCreated;
Hope it helps.
[EDIT]
Output:
Related
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;
}
}
I have a method name Request() in the onCreate method of the activity.
private void Request() {
new PostDataAsyncTask(textEmail, tValue).execute();
}
Iam passing two strings in it and the async class is as follows:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
public PostDataAsyncTask(String textEmail, String hello) {
data = textEmail;
data1= hello;
}
long date = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = simpleDateFormat.format(Long.valueOf(date));
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
}
private void postText(){
try{
String postReceiverUrl = "http://techcube.pk/game/game.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", data));
nameValuePairs.add(new BasicNameValuePair("score", data1));
nameValuePairs.add(new BasicNameValuePair("datetime", dateString));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("SuccesS", "Response: " + responseStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now what i want is that i want to get the value of responseStr in my MainActivity that is generated when posttext method called.
How to show this responseStr value in the MainActivity?
Remember there is a new class that i made named as PostDataAsyncTask so how to access responseStr from this class and show it in my mainActivity as a Toast or Textview?
Please Help
You can create an interface that you pass into the method in question. For example
public interface INetworkResponse {
void onResponse(String response);
void onError(Exception e);
}
You would then need to create a concrete implementation of the interface. perhaps as a child class inside the activity that calls the AsyncTask.
public class MyActivity extends Activity {
private void Request() {
NetworkResponse response = new NetworkResponse();
new PostDataAsyncTask(textEmail, tValue, response).execute();
}
public class NetworkResponse implements INetworkResponse {
public void onResponse(String response) {
// here is where you would process the response.
}
public void onError(Exception e) {
}
}
}
Then change the async task constructor to include the new interface.
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
private INetworkResponse myResponse;
public PostDataAsyncTask(String textEmail, String hello, INetworkResponse response) {
data = textEmail;
data1 = hello;
myResponse = response
}
private void postText() {
// do some work
myResponse.onResponse(myResultString);
}
}
You can create a Handler as an Inner class inside your Activity to send data between your thread and UIthread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
String data = (String)msg.obj;
//Manage the data
}
}
Pass this object in the header of PostDataAsyncTask
public PostDataAsyncTask(String textEmail, String hello, YourHandler mYourHandler) {
data = textEmail;
data1= hello;
this.mYourHandler = mYourHandler;
}
and send the data in postText() to the Activity:
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
msg = Message.obtain();
msg.obj = responseStr;
mYourHandler.sendMessage(msg);
Log.v("SuccesS", "Response: " + responseStr);
}
I am trying to parse huge json using gson library and my main idea is to get one value from each object and save it as String. This the json file i am using. And this is the code i am using to parse the json:
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
public TextView textss;
public int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
textss = (TextView)findViewById(R.id.texts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.posts, menu);
return true;
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
#Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.title + " " + i, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat. bls bls bls " , Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://kylewbanks.com/rest/posts";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
for ( i = 0; i < 4; i++) {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();
handlePostsList(posts);
}
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
I am still learning and what i understand is that all values are saved in one big list and later these values are displayed as in Toast. What i am trying to do is save a value in String like i would to it with json like this:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
How can i achieve this by using Gson library?
Here's what I've tried as you want.
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
//List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
JsonArray posts = new JsonParser().parse(reader).getAsJsonArray();
// Get first element at index 0
Post post1 = gson.fromJson(posts.get(0).getAsJsonObject(), Post.class);
Log.d(TAG, "post1 .. " + post1.getTitle());
content.close();
//handlePostsList(posts);
First of all, I create a Gson JsonArray. And assign it by creating a new JsonParser which parses the reader as a JsonArray.
And then you can extract the first element of the posts by getting the element at index 0, and deserializes with respective Object.
I've used set/get for Post object so I get the title as post1.getTitle().
The log says
post1 .. Disabling Google Analytics in Development Using Only
JavaScript
I am attempting to write an Android app which casts JSON input. This is my sample input.
I have the following class to serve as the data container:
public class DATA {
public Long id;
public String title;
public String author;
public String url;
public String date;
public String body;
public DATA() {
// TODO Auto-generated constructor stub
}
#Override
public String toString(){
return "DATA-Oblect: ID=> " + id + "/nTITLE=> " + title;
}
}
Using the following code:
protected void doInBackground(String... url) {
try{
//create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://kylewbanks.com/rest/posts");//url[0]);
//perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
content = entity.getContent();
try{
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<DATA> Data = new ArrayList<DATA>();
Data = Arrays.asList(gson.fromJson(reader, DATA[].class));
content.close();
}catch(Exception ex){
Log.e(TAG, "JSON parse failed due to: " + ex);
}
}else{
Log.e(TAG, "Server response code: " + statusLine.getStatusCode());
}
}catch(Exception ex){
Log.e(TAG, "HTTP-Post failed due to: " + ex);
}
}
I get the following exception error:
JSON parse failed due to: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What am I doing wrong?
Update
The following the the my main activity code:
public class MainActivity extends Activity {
private List<DATA> Data;
public static final String jsonSource = "http://kylewbanks.com/rest/posts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// DataRetriever("http://kylewbanks.com/rest/posts");
new DataRetriever(this.getApplicationContext()).execute(jsonSource);
}
/**
* Callback function for handling retrieved data from the
* DATARetrieve class
* #param Data
*/
public void DataListDrop(List<DATA> Data){
this.Data = Data;
Toast.makeText(MainActivity.this, "Testing ... testing!", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(DATA data : MainActivity.this.Data){
Toast.makeText(MainActivity.this, data.title, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Callback function for responding no-data return from the
* DATARetrieve class
*/
private void NoData(){
runOnUiThread(new Runnable() {
#Override
public void run(){
Toast.makeText(MainActivity.this, "No data to process! Checkout LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
}
I have a ProgressDialog that retrieves in background data from database by executing php script.
I'm using gson Google library. php script is working well when executed from browser:
{"surveys":[{"id_survey":"1","question_survey":"Are you happy with the actual government?","answer_yes":"50","answer_no":"20"}],"success":1}
However, ProgressDialog background treatment is not working well:
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.4/tn_surveys/get_all_surveys.php";
HttpGet getRequest = new HttpGet(url);
Log.d("GETREQUEST",getRequest.toString());
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d("URL1",url);
HttpResponse getResponse = httpClient.execute(getRequest);
Log.d("GETRESPONSE",getResponse.toString());
final int statusCode = getResponse.getStatusLine().getStatusCode();
Log.d("STATUSCODE",Integer.toString(statusCode));
Log.d("HTTPSTATUSOK",Integer.toString(HttpStatus.SC_OK));
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d("RESPONSEENTITY",getResponseEntity.toString());
InputStream httpResponseStream = getResponseEntity.getContent();
Log.d("HTTPRESPONSESTREAM",httpResponseStream.toString());
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("HELLO","HELLO");
StringBuilder builder = new StringBuilder();
Log.d("STRINGBUILDER","STRINGBUILDER");
for (Survey survey : this.response.data) {
String x= survey.getQuestion_survey();
Log.d("QUESTION",x);
builder.append(String.format("<br>ID Survey: <b>%s</b><br> <br>Question: <b>%s</b><br> <br>Answer YES: <b>%s</b><br> <br>Answer NO: <b>%s</b><br><br><br>", survey.getId_survey(), survey.getQuestion_survey(),survey.getAnswer_yes(),survey.getAnswer_no()));
}
Log.d("OUT FOR","OUT");
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
HELLO Log is displayed.
STRINGBUILDER Log is displayed.
QUESTION Log is NOT displayed.
OUT FOR Log is displayed.
Survey Class:
public class Survey {
int id_survey;
String question_survey;
int answer_yes;
int answer_no;
public Survey() {
this.id_survey = 0;
this.question_survey = "";
this.answer_yes=0;
this.answer_no=0;
}
public int getId_survey() {
return id_survey;
}
public String getQuestion_survey() {
return question_survey;
}
public int getAnswer_yes() {
return answer_yes;
}
public int getAnswer_no() {
return answer_no;
}
}
Response Class:
public class Response {
ArrayList<Survey> data;
public Response() {
data = new ArrayList<Survey>();
}
}
Any help please concerning WHY the FOR loop is not executed.
Thank you for helping.
Any help please concerning WHY the FOR loop is not executed.
Simply put: data is empty. (So there is nothing for the loop to iterate over...)
Try something like this, from GSON's documentation:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
I haven't used GSON myself, but there are other examples of how to read lists:
Android gson deserialization into list
GSON : custom object deserialization
Your onPostExecute takes in a parameter called result. Your for loop iterates over the elements in an instance variable called response. Are they supposed to be the same?