Volley- fetching json array with POST request - android

I am using volley.jar to fetch JSON array from remote server. Am able to fetch via GET request.Please help me with POST request
I am following a tutorial from androidhive.
Here is my working code.
public class fbuk extends Activity {
// Movies json url
private static final String url = "http://example.com/xyz.php?q=ram";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
listView = (ListView) findViewById(R.id.listview);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("ttl"));
movie.setThumbnailUrl(obj.getString("img"));
movie.setRating(obj.getString("stts"));
movie.setYear(obj.getString("relz"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
How to send params

public void Post(String url, final Map<String, String> map) {
showProgress();
RequestQueue queue = Volley.newRequestQueue(_serverctx);
StringRequest request = new StringRequest(Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response!=null && response.length()>0) {
try {
_response.result(new JSONObject(response)); // Pass data to your parsing method(in my case i made a interface)
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("error");
hideProgres();
}
}){
#Override
protected Map<String, String> getParams() {
return map;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
request.setShouldCache(false);
request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
queue.add(request);
}
Call from Activity or fragment
Put the above method in a seprate class and give a call like
Map<String,String> params = new HashMap<String, String>();
params.put("email",email);
params.put("password",password);
_req = new NetworkRequests(this, ctx);
_req.Post(ShoqahContants.Login_URL, params);
and your are Done :)

This worked for me.
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
url="http://www.example.com/xyz.php";
Volley.newRequestQueue(your_activity.this).add(
new CustomJsonRequest(Request.Method.POST, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
GC gc = new GC();
gc.setTitl(obj.getString("ttl"));
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
hidePDialog();
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(
NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser
.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser
.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public class CustomJsonRequest extends Request {
Map<String, String> params;
private Response.Listener listener;
public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
Response.Listener responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
params=new HashMap<String, String>();
params.put("key", value);
this.params = params;
this.listener = responseListener;
}
#Override
protected void deliverResponse(Object response) {
listener.onResponse(response);
}
#Override
public Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
p.s:the json must be in the below format
[{"titl":"The Great gatsby"},{"titl":"Wolf Of Wall Street"}]

Related

android volley post json ID and get result back from PHP server

i am struggling to make this work, basically i get an id from previous activity using intent, now i want to send this id to server so it returns all the data associated with this id.
javacode
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
PHP server
if (!empty($_POST)) {
$query = " SELECT * FROM table WHERE ID = :ID " ;
$query_params = array(
':ID' => $_POST['ID'],);
try {
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$result = $statement->fetchAll();
if($result){
$data =array();
foreach($result as $rows){
$json = array();
$json["Name"] = $rows["Name"];
array_push ($data,$json);
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
i used this example of http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put and coverted the string response to string array, worked for me
url = "http://httpbin.org/post";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Alif");
params.put("domain", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
I would modify the request like this:
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,URL,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
return params;
}
};
ApplicationController.getInstance().addToRequestQueue(req);
and also would modify the PHP code like this:
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
try {
$statement = $db->prepare(SELECT * FROM table WHERE ID = ?);
$statement->bindValue(1, $id);
$result = $statement->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$records = array();
$records = $statement->fetchAll(PDO::FETCH_ASSOC);
$data = array();
foreach($records as $record){
$data["Name"] = $record["Name"];
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
}
Hope it helps!!!
the issue is that you send json but you expect params in you php.
there 2 solutions:
1) update php to accept json not just post params
2) update volley request to send post params but expect JSONObject
for example you can use this request:
public class JsonObjReq extends Request<JSONObject> {
private final Response.Listener<JSONObject> mListener;
private final Map<String, String> params;
public JsonObjReq(int method, String url, Map<String, String> params, Response
.Listener<JSONObject> mListener,
Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = mListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
and apply to your code like that:
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjReq req = new JsonObjReq(Method.POST, URL, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

Android Volley POST JsonObject and get JsonArray or JsonObject or Other response

in volley we have some ability to retrieve data from server such as jsonObject,jsonArray and String. in this below sample we can get simply jsonObject or jsonArray response from server,
public static void POST(HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
JsonObjectRequest req1 = new JsonObjectRequest(ApplicationController.URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response:", response.toString());
if (listener != null)
listener.onResultJsonObject(response);
else
Log.e(TAG,"Error: SetServerResponse interface not set");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req1);
}
my problem is i want to send jsonObject from this method and get jsonArray or jsonObject from server, and i can not get simply array from server with this method. for example i must be filter server response with this jsonObject:
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
params.put("search_count", "10");
params.put("order_by", "id");
server return jsonArray and i can not get that with Volley response
Looking at the source code of JsonArrayRequest. There is a constructor which takes in a JSONObject. You should check it out
public class RetreiveData {
public static final String TAG = RetreiveData.class.getSimpleName();
public static void POST(String localhost, final HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
StringRequest post = new StringRequest(Request.Method.POST, localhost, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (listener != null)
listener.onResponse(response.toString());
else
Log.e(TAG, "Error: SetServerResponse interface not set");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = params;
return map;
}
#Override
public RetryPolicy getRetryPolicy() {
setRetryPolicy(new DefaultRetryPolicy(
5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return super.getRetryPolicy();
}
};
ApplicationController.getInstance().addToRequestQueue(post);
}
}

Volley - Make a jsonarray post request

I am having this class where am fetching json array with POST method after referring several google searches and stackoverflow question but my code gives an weird error Cannot Resolve Symbol POST
here is my activity
public class fbuk extends Activity {
// Movies json url
private static final String url = "http://example.com/xyz.php";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
listView = (ListView) findViewById(R.id.listview);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
// Creating volley request obj
JsonArrayRequest movieReq = new PostJsonArrayRequest(Method.POST, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("ttl"));
movie.setThumbnailUrl(obj.getString("img"));
movie.setRating(obj.getString("stts"));
movie.setYear(obj.getString("rel"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("q", "ram");
return params;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
I am following a tutorial from androidhive
Please suggest where am making the mistake
I have done like this (see sample code), make sure that import com.android.volley.Request; must be imported in your activity class otherwise Request.Method.POST will not work and Unable to Resolve will appear
String url = "http://example.com/xyz.php";
ErrorListener errorListener = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError errorResponce)
{
}
};
Listener<JSONArray > jsonArrayListener = new Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// TODO Auto-generated method stub
}
};
PostJsonArrayRequest req = new PostJsonArrayRequest(Request.Method.POST, url , null, jsonArrayListener, errorListener);
And use this class for
public class PostJsonArrayRequest extends JsonRequest<JSONArray>
{
public PostJsonArrayRequest(int method, String url, String requestBody,
Listener<JSONArray> listener, ErrorListener errorListener)
{
super(method, url, requestBody, listener, errorListener);
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response)
{
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Check your import for Method. It should be
import com.android.volley.Request.Method
May be you have imported as a
import java.lang.reflect.Method;
Use
JsonArrayRequest movieReq = new PostJsonArrayRequest(Request.Method.POST,url,
new Response.Listener<JSONArray>() {
and make sure to import,
import com.android.volley.Request.Method;
hope it will work.

best way to send params in json array volley

I am using volley library to fetch json array via POST request. when I use get method am able to fetch the desired values but when I use POST method am unable to fetch any value instead am getting this error
value of type org.json.jsonobject cannot be converted to jsonarray
Here is my code
public class xyz extends Activity {
private static final String url = "http://example.com/q.php";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
listView = (ListView) findViewById(R.id.listview);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError errorResponce)
{
VolleyLog.d( "Error: " + errorResponce.getMessage());
hidePDialog();
}
};
Response.Listener<JSONArray > jsonArrayListener = new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// TODO Auto-generated method stub
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("ttl"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
};
Map<String, String> mParam = new HashMap<String, String>();
mParam.put("q", "ram");
PostJsonArrayRequest req = new PostJsonArrayRequest(Request.Method.POST, url , null, jsonArrayListener, errorListener,mParam);
// Creating volley request obj
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
// Adding request to request queue
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
private Map<String,String> mParam;
private Response.Listener<JSONArray> mListener;
public PostJsonArrayRequest(int method, String url, String requestBody,
Response.Listener<JSONArray> listener, Response.ErrorListener errorListener,Map param) {
super(method, url, requestBody, listener, errorListener);
mListener=listener;
mParam=param;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParam;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONArray response) {
mListener.onResponse(response);
}
}
}
please guide me where am making the mistake. am i passing the params correctly?

JSONArray custom request stops working

In my android app I have a request which until yesterday was working, now it seems ignored by the onCreate. Even if I pass a url to an empty php file, I have no errors, just an empty listview.
Here's my code:
public class CustomJsonRequest extends Request<JSONArray> {
Map<String, String> params;
customListener listener;
public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
customListener listener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
this.params = params;
this.listener = listener;
}
#Override
protected void deliverResponse(JSONArray response) {
listener.onResponse(response);
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new
String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
In my activity I have the interface and the listeners
My request in the activity is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
PDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
PDialog.setMessage("..wait..");
PDialog.show();
SharedPreferences prefs = getSharedPreferences(MainActivity.SharedPrefName, 0);
nome= (prefs.getString("Name", ""));
genere= (prefs.getString("Sesso",""));
id= (prefs.getString("ID", ""));
gps = new GPSTracker(MapActivity.this);
link= (prefs.getString("LINK", ""));
age= (prefs.getString("AGE", ""));
foto= (prefs.getString("FOTO", ""));
// Get listview
lv = (ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, productsList);
lv.setAdapter(adapter);
CustomJsonRequest requi= new CustomJsonRequest(Request.Method.POST,
url_all_products_post, null, listener, error)
{protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id",id);
params.put("name", nome);
params.put("gender", genere);
params.put("lt", lt);
params.put("ln", ln);
params.put("age", age);
params.put("foto", foto);
params.put("link", link);
return params;
};
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(requi);
}
public interface customListener{
public void onResponse(JSONArray response);
}
ErrorListener error = new ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}};
customListener listener= new customListener(){
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
...
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// notifying list adapter about data changes
adapter.notifyDataSetChanged();
hidepDialog();
}
};
Why the onCreate "skips" my request?
I can't see any reason why the below wouldn't work as you would expect.
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
PDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
PDialog.setMessage("..wait..");
PDialog.show();
SharedPreferences prefs = getSharedPreferences(MainActivity.SharedPrefName, 0);
nome = (prefs.getString("Name", ""));
genere = (prefs.getString("Sesso", ""));
id = (prefs.getString("ID", ""));
gps = new GPSTracker(MapActivity.this);
link = (prefs.getString("LINK", ""));
age = (prefs.getString("AGE", ""));
foto = (prefs.getString("FOTO", ""));
// Get listview
lv = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, productsList);
lv.setAdapter(adapter);
Map<String, String> params = new HashMap<>();
params.put("id", id);
params.put("name", nome);
params.put("gender", genere);
params.put("lt", lt);
params.put("ln", ln);
params.put("age", age);
params.put("foto", foto);
params.put("link", link);
AppController.getInstance().addToRequestQueue(new CustomJsonRequest(Request.Method.POST,
url_all_products_post, params, new customListener() {
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// notifying list adapter about data changes
adapter.notifyDataSetChanged();
hidepDialog();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
error.printStackTrace();
}
}));
}

Categories

Resources