Asked  6 Months ago    Answers:  5   Viewed   309 times

I am using android Volley for making a request. So I use this code. I don't understand one thing. I check in my server that params is always null. I consider that getParams() not working. What should I do to solve this issue.

 RequestQueue queue = MyVolley.getRequestQueue();
        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println(response);
                        hideProgressDialog();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                      hideProgressDialog();
                    }
                }) {
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("id","1");
                params.put("name", "myname");
                return params;
            };
        };
        queue.add(jsObjRequest);

 Answers

14

try to use this helper class

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> 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
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

In activity/fragment do use this

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);
Tuesday, June 1, 2021
 
hnkk
answered 6 Months ago
13

I ended up using Volley's StringRequest instead, because I was using too much valuable time trying to make JsonObjectRequest work.

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";

StringRequest strRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "test");
                return params;
            }
        };

queue.add(strRequest);

This worked for me. Its just as simple as JsonObjectRequest, but uses a String instead.

Wednesday, June 2, 2021
 
Giovanni
answered 6 Months ago
94

They're probably going to add it later, but in the meanwhile you can add the wanted constructor yourself:

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), 
        listener, errorListener);
}

This isn't tested, though I see no reason this shouldn't work since the implementation details are in the super class: JsonRequest.

Try it and see if it works.

EDIT:

I called it! It took them almost two years after I answered this but the Volley team added this constructor on March 19, 2015 to the repo. Guess what? This is the EXACT syntax.

Wednesday, June 2, 2021
 
insomiac
answered 6 Months ago
37

This is because starting with Android P, any network traffic between your app and insecure destinations must be explicitly whitelisted. See Protecting users with TLS by default in Android P.

In your code, you're making a request to:

http://hellapunk.com/listallshows.php?id=2018

The http:// shows that the site is not secure. If you dig deeper into your LogCat you'll likely find a message such as:

com.android.volley.NoConnectionError: java.io.IOException: Cleartext HTTP traffic to hellapunk.com not permitted
    at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:177)
    at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
    at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
 Caused by: java.io.IOException: Cleartext HTTP traffic to hellapunk.com not permitted
    at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
    at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:99)
    at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
    at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120) 
    at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87) 

Attempting it myself, it doesn't appear that the site supports https connections, so in order to reach this particular server from your application, you would need to whitelist the hellapunk.com domain manually.

In your resources directory, define an XML document for your network security configuration (e.g. res/xml/network_security_config.xml):

network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">hellapunk.com</domain>
    </domain-config>
</network-security-config>

Then, in your AndroidManifest.xml for your application, in the <application> tag, add the attribute:

<application
    android:networkSecurityConfig="@xml/network_security_config"

You should then be allowed to make insecure requests to any domain specified within that file.

Thursday, July 29, 2021
 
ajaybc
answered 4 Months ago
24

The volley request is an asynchronous call. It doesn't block the code till the response is received. So what is happening is your check for if(status==1) is happening before the volley response is received. Hence it is 0.

What you should do:

1) Make your function return type void.

2) In onResponse, put the code

if (status == 1) { // ** STATUS IS 0 HERE **
        statusBoolean = true;
    } else {
        statusBoolean = false;
}
Saturday, August 28, 2021
 
ielyamani
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share