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);
Related
I wanna add a custom header in Retrofit. But I don't know how to set it. any one can help me?
This is my code
#SuppressLint("StaticFieldLeak")
private void save_config(final String ip_server_txt, final String port_server_txt, final String user_sql_txt, final String pass_sql_txt, final String token_txt) {
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
HashMap<String, String> map = new HashMap<>();
map.put("ip_server", ip_server_txt);
map.put("user_sql", user_sql_txt);
map.put("pass_sql", pass_sql_txt);
map.put("port_sql", port_server_txt);
map.put("token", token_txt);
try {
httprequest req = new httprequest(appconfig.URL_CONFIG_SQL);
response = req.prepare(httprequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response = e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss",result);
onTaskCompleted1(result, jsoncode);
hideDialog();
}
}.execute();
}
I am trying to parse the user data using JSON. but my app keeps crashing .
This is the data that I display are
[Title, First Name, Last Name, location {street, city, state, and postcode} and email ]
this is the urls
"http://randomuser.me/api/?results=5&format=json"
This is my code
user class
public class User {
private String pic;
private String gender;
private String title;
private String first;
private String last ;
private String city;
private String street;
private String postcode;
private String email;}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private OkHttpClient httpClient;
private Request request;
TextView tv;
private String[] urls = {
"http://randomuser.me/api/?results=5&format=json"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.data_l);
httpClient = new OkHttpClient();
request = new Request.Builder()
.url(urls[0])
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful())
{
final String dataa = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<User> users = parseDataJSON(dataa) ;
tv.setText(dataa);
}
});
}
}
});
}
public ArrayList<User> parseDataJSON(String data) {
ArrayList<User> users = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(data);
JSONArray usersArray = jsonObject.getJSONArray("results");
for (int i = 0; i < usersArray.length(); i++) {
User user = new User();
JSONObject userObject = usersArray.getJSONObject(i);
String gender = userObject.getString("gender");
user.setGender(gender);
JSONObject nameObject = userObject.getJSONObject("name");
user.setTitle(nameObject.getString("title"));
user.setFirst(nameObject.getString("first"));
user.setLast(nameObject.getString("last"));
JSONObject locationObject = userObject.getJSONObject("location");
user.setCity(locationObject.getString("city"));
user.setStreet(locationObject.getString("street"));
user.setStreet(locationObject.getString("state"));
String email = userObject.getString("email");
user.setEmail(email);
JSONObject pictureObject = userObject.getJSONObject("picture");
user.setPic(pictureObject.getString("large"));
users.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
}
return users;
}
I already did the implementation.
As your Pojo has private properties (pic, gender, title, etc) then you need to include (in your POJO) public setters to set the data? (You'll also need getters too - in order to access the data)
e.g.
public void setPic(String pic) {
this.pic = pic;
}
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 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;
}
}
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: