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.
Related
While I was testing the "volley" library, a doubt arose me regarding the method "post".
The thing is that I have been working with JsonObject until now, for that I used the following code and it works. In this method I send and JsonObject and receive another JsonObjet, I had no problem with it.
Now my doubt is, How can I do to send a JsonObject and receive an ArrayObject?
I am really lost with this, I will really appreciate your help, thanks in advance
public void testPost(String url, final String tag, JSONObject obj) {
//final ProgressDialog pDialog = new ProgressDialog(context);
//pDialog.setMessage("Loading...");
//pDialog.show();
JsonObjectRequest jsonObjReqpost = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//test
Log.d("SendRequestJsonPost", response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.data != null) {
error = new VolleyError(new String(error.networkResponse.data));
}
String fail = handlingErrors.resolverErrors(error.toString());
//Log.d("SendRequestJsonPost", fail);
//pDialog.hide();
}
}) {
//header
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("charset", "utf-8");
return headers;
}
};
jsonObjReqpost.setTag(tag);
Singleton.getInstance(context).addToRequestQueue(jsonObjReqpost);
}
You can use the following method to get JsonArray as response.
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener)
{
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
Please refer this answer for more details.
public class nameOfClass extends AsyncTask {
String response;
//This process is work in Background
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token;
//Tocken name that is send to server
token = "TockenName|" + "|";
try {
response = connection.EstablishConnection(token);
String message = "Sorry Fail to connect";
if (response.equals(message)) {
onPostExecute(message);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// In this method you can open loading msg
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
//Json object
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
//Hear traverse the loop and get the data
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.
The new request should be executed before the first ends. (Last in, first out)
How can I execute the new request succesfully ?
private void makeJsonObjectRequest() {
ac = new AppController();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", response.toString());
try {
// Parsing json object response
// response will be a json object
JSONArray name = response.getJSONArray("data");
for (int i = 0; i < name.length(); i++) {
JSONObject post = (JSONObject) name.getJSONObject(i);
try {
objectid = post.getString("object_id");
newRequest(objectid);
}
catch (Exception e) {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("test", "Error: " + error.getMessage());
}
});
// Adding request to request queue
ac.getInstance().addToRequestQueue(jsonObjReq);
}
Try it Work 100%
public class Utility {
String result = "";
String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
this.context = context;
}
public String getString(String url, final VolleyCallback callback) {
showpDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = response;
hideDialog();
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onRequestError(error);
hideDialog();
/*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
((Activity) context).setContentView(layout);*/
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
stringRequest.setRetryPolicy(
new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
return result;
}
public interface VolleyCallback {
void onSuccess(String result);
void onRequestError(VolleyError errorMessage);
//void onJsonInvoke(String url, final VolleyCallback callback);
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private void showpDialog() {
onProgress();
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onProgress() {
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
Call Fragment
Utility utility = new Utility(getContext());
utility.getString(urls, new Utility.VolleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject toplinks = new JSONObject(result);
JSONObject data = toplinks.getJSONObject("toplinks");
M.i("============LS", "" + data);
} catch (JSONException e) {
e.printStackTrace();
}
finally {
}
}
#Override
public void onRequestError(VolleyError errorMessage) {
errorJson.setVisibility(View.VISIBLE);
String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
errorJson.setText(msg);
}
});
all this about
Request Prioritization
Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.
So all you need change priority (set Priority.HIGH) to request you want process first.
here is a piece of code
public class CustomPriorityRequest extends JsonObjectRequest {
// default value
Priority mPriority = Priority.HIGH;
public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority p){
mPriority = p;
}
}
As others mentioned one way is to put a high priority on the request.
Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();
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 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?
protected JSONObject executeGet(String URL) throws CloudAppException {
JSONObject response = new JSONObject();
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject serverResponse) {
try {
response = serverResponse;
VolleyLog.v("Response:%n %s", serverResponse.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
RequestHandler.addToRequestQueue(req);
return response;
}
Ideally, I want to parse the response on my own, but I'm blanking on as to how to get the executeGet method to return the server response.
You need to extend the request class and in your custom request class override the parseNetworkResponse method and do your own parsing.
Here is a sample :
public class CustomRequest extends Request {
// the response listener
private Response.Listener listener;
public CustomRequest(int requestMethod, String url, Response.Listener responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener); // Call parent constructor
this.listener = responseListener;
}
// Same as JsonObjectRequest#parseNetworkResponse
#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));
}
}
#Override
public int compareTo(Request other) {
return 0;
}
#Override
protected void deliverResponse(Object response) {
if (listener!=null)
listener.onResponse(response);
}
}