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();
}
}));
}
Related
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);
I am trying to send some data to the server using the Volley library.
private void registerUser(final String email, final String username,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
// String status = jObj.getString("status");
// User successfully stored in MySQL
// Now store the user in sqlite
String name = jObj.getString("username");
String email = jObj.getString("email");
String password = jObj.getString("password");
// String created_at = user
//.getString("created_at");
// Inserting row in users table
// db.addUser(name, email);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("username", username);
params.put("password", password);
return params;
}
Unfortunately no json is sent and I get nothing back. Here is a sample of my logcat output. After sending a request successfully to the server, I want to get response with success/fail.
Register Response: ---- YOUR DATA ----
username=xxx&email=xxx%40gmail.com&password=xxxx&-------------------
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ org.json.JSONException: Value ---- of type java.lang.String
cannot be converted to JSONObject
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
05-05 14:56:55.002 2558-2558/app.victory.walking.thewalkingviktory
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
Any help please? Thanx.
private void postUsingVolley() {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
final String mVendorId = DeviceDetails.getInstance(mContext).getVendor_id();
String mUserId = UserModel.getInstance(mContext).getUser_id();
final HashMap<String, String> postParams = new HashMap<String, String>();
sendFeedbackParams.put("key1", value1);
sendFeedbackParams.put("key2", value2);
sendFeedbackParams.put("key3", value3);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
ApplicationData.POST_URL, new JSONObject(postParams),
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("TAG", response.toString());
try {
//Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "Thank you for your post", Toast.LENGTH_LONG).show();
if (response.getBoolean("status")) {
pDialog.dismiss();
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
pDialog.dismiss();
if (isNetworkProblem(error)) {
Toast.makeText(mContext, "Internet Problem", Toast.LENGTH_SHORT).show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getRequestHeaders();
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(8000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Use Volley like this,... It is working for me.
First of all you are not sending json to your server. You are sending parametrized url with post method and getting json text as response.
I think the problem is the response from the server which is supposedly json. But from your log, this text "---- YOUR DATA ----" which you get from Log.d(TAG, "Register Response: " + response.toString()); is not at all json formatted . So you need to modify your server to respond in correct json format.
This is the solution. I had to use the JsonObjectRequest class and not the StringRequest on. What JsonRequest does is that it converts your HashMap key-value pairs into a JSON Format.
private void registerUser(String email_address,String username, String
password) {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
final String mVendorId =
DeviceDetails.getInstance(mContext).getVendor_id();
String mUserId = UserModel.getInstance(mContext).getUser_id();
String location = getResources().getConfiguration().locale.getCountry();
final HashMap<String, String> postParams = new HashMap<String, String>
();
postParams.put("username", username);
postParams.put("email", email_address);
postParams.put("password", password);
postParams.put("location", location);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(AppConfig.URL_REGISTER, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("TAG", response.toString());
try {
Toast.makeText(getApplicationContext(),
response.getString("message"), Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Thank
you for your post", Toast.LENGTH_LONG).show();
if (response.getString("status").equals("success")){
session.setLogin(true);
pDialog.dismiss();
Intent i = new
Intent(RegisterActivity.this,Welcome.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
JSon post
public void makePostUsingVolley()
{
session = new SessionManager(getActivity().getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
final String token = user.get(SessionManager.KEY_NAME);
//Toast.makeText(getActivity().getApplicationContext(),name, Toast.LENGTH_SHORT).show();
final Map<String, String> params = new HashMap<String, String>();
//params.put("Employees",name);
String tag_json_obj = "json_obj_req";
String url = "enter your url";
final ProgressDialog pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest req = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
// final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
//"http://emservices.azurewebsites.net/Employee.asmx/CheckUserGet", new Response.Listener<JSONObject>() {
#Override
public void onResponse(String response) {
JSONObject json;
// Toast.makeText(getActivity().getApplicationContext(),"dfgghfhfgjhgjghjuhj", Toast.LENGTH_SHORT).show();
//Toast.makeText(getActivity().getApplicationContext(),obb.length(), Toast.LENGTH_SHORT).show();
// JSONObject data=obj.getJSONObject("Employee_Name");
ObjectOutput out = null;
try {
json = new JSONObject(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.hide();
// Toast.makeText(getApplicationContext(),"hi", Toast.LENGTH_SHORT).show();
Log.d("", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
pDialog.hide();
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username",name);
params.put("password",password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_obj);
}
requestQueue= Volley.newRequestQueue(MainActivity.this);
StringRequest request=new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
Log.d("response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name.getText().toString().trim());
jsonObject.put("email", email.getText().toString().trim());
jsonObject.put("phone", phone.getText().toString().trim());
} catch (JSONException e) {
e.printStackTrace();
}
Map<String, String> params = new HashMap<String, String>();
params.put("message", jsonObject.toString());
return params;
}
};
requestQueue.add(request);
[["deep","dee#gmail.com","8888999999"]]
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"}]
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.
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?