1

I am trying to retrieve a JSONObject from database but I found out that the request don't even make it to the Server. I checked the Apache Access Log to confirm this. The URL is valid and when I access it via a web browser, it return the expect JSONObject. The exception error show null by the Volley library.

 private void GetSchInfo(){

    showDialog();

    // making fresh volley request and getting json
    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
            URL_SchInfo, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {


            try{

                spinnerClass.setVisibility(View.VISIBLE);
                spinnerSch.setVisibility(View.VISIBLE);
                spinnerDept.setVisibility(View.VISIBLE);
                btnRegClass.setVisibility(View.VISIBLE);
                txtClassMsg.setVisibility(View.VISIBLE);
                btnRefresh.setVisibility(View.GONE);

                JSONArray schools = response.getJSONArray("sch_info");
                JSONArray departments = response.getJSONArray("dept_info");

                for (int i = 0; i < schools.length(); i++){
                    JSONObject schObj = (JSONObject)schools.get(i);
                    SchInfo sch = new SchInfo(schObj.getString("school_id"), schObj.getString("school_name"));
                    schoolList.add(sch);
                }

                for (int j = 0; j < departments.length(); j++){
                    JSONObject deptObj = (JSONObject)departments.get(j);
                    DeptItem dept = new DeptItem(deptObj.getString("department_id"), deptObj.getString("department_name"));
                    deptList.add(dept);
                }


                //populate
                //populateInfo();

            }catch(JSONException e){
               Log.e(TAG, "JSON Error: " + e.getMessage());
                e.printStackTrace();
                spinnerClass.setVisibility(View.GONE);
                txtClassMsg.setVisibility(View.GONE);
                spinnerSch.setVisibility(View.GONE);
                spinnerDept.setVisibility(View.GONE);
                btnRegClass.setVisibility(View.GONE);
                btnRefresh.setVisibility(View.VISIBLE);

             }

            hideDialog();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            String body;

                if (error.networkResponse.data !=null){
                try {
                    body = new String(error.networkResponse.data, "UTF-8");
                }catch (UnsupportedEncodingException e){
                    e.printStackTrace();
                }
            }

          Log.e("Error: ",   error.getCause()  +">>" + error.getMessage());
            Log.e(TAG, "JSON Error: " + error.getMessage() );
            hideDialog();
            spinnerClass.setVisibility(View.GONE);
            spinnerSch.setVisibility(View.GONE);
            spinnerDept.setVisibility(View.GONE);
            btnRegClass.setVisibility(View.GONE);
            txtClassMsg.setVisibility(View.GONE);
            btnRefresh.setVisibility(View.VISIBLE);
        }
    });

    // Adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);
}

How do I solve this?

Note The server is on my local machine, I connect via hotspot with something like http://192.164.***.***.

BlackPearl
  • 2,532
  • 3
  • 33
  • 49

5 Answers5

7

This may be due to unsecured URL so you can add this line in AndroidManifest.xml

android:usesCleartextTraffic="true"

 <application
    android:name=".ExampleApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher_new"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_circle"
    android:largeHeap="true"
    android:resizeableActivity="false"
    android:usesCleartextTraffic="true"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme.NoActionBar">

and if in case it gives this [java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion] error then add this line as application tag child.

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

For more details visit this link --

https://developer.android.com/about/versions/pie/android-9.0-changes-28#apache-p

rizwan
  • 164
  • 2
  • 5
2

Try to do a request from android mobile's browser if that works perfectly fine then must be of volley issue. if it did not work then that means you can not connect to the server just by typing 192.168.... Also check this link and run application inside emulator: How to connect to my http://localhost web server from Android Emulator in Eclipse

so by all means if you want to use like that put your server to online. and use your global ip to ping the server. read how to put local server online as per your own server documentation.

Community
  • 1
  • 1
Parth Dave
  • 2,096
  • 13
  • 20
  • Thanks, for the clue of testing with android browser, it gave me idea about where the problem was coming from. – BlackPearl May 11 '16 at 06:22
  • I had the same problem when i was developing my project and i turned my wamp server as online mode. twikked with his http doc inorder to give full access for every incomming request and added exception to firewall. and then used global ip. also check that your server accepts the request from other then local ip. – Parth Dave May 11 '16 at 06:31
2

My strategy is, make Volley singleton and use it from anywhere. Here is steps: add this gradle in build.gradle file

compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Create Application class like this

public class YourApplication extends Application {

    public static final String TAG = YourApplication.class.getSimpleName();
    private RequestQueue requestQueue;
    private com.android.volley.toolbox.ImageLoader imageLoader;
    private static YourApplication instace;

    @Override
    public void onCreate() {
        super.onCreate();
        instace = this;
    }

    public static synchronized YourApplication getInstance() {
        return instace;
    }

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return requestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (requestQueue != null) {
            requestQueue.cancelAll(tag);
        }
    }
}

Add bellow code in your menifest.xml

<application
        android:name=".package_path.YourApplication">

Add internet permission in menifest

<uses-permission android:name="android.permission.INTERNET" />

Now your volley is configured. You just use it this way:

final ProgressDialog progressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        progressDialog.setMessage("Please wait...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                URL_HERE,
                null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject object) {
                        progressDialog.dismiss();
            // Your Data is here
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
        //Error Occured


            }
        });
        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        YourApplication.getInstance().addToRequestQueue(jsonObjectRequest, "YOUR_TAG");

Edit use compile 'com.android.volley:volley:1.0.0'' in build.gradle file.

compile 'com.mcxiaoke.volley:library-aar:1.0.0' is just deprecated.

That's it :)

Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
1

getMessage() doesn't work sometimes. try this code to get the full error message that the server returned.

    if (volleyError != null && volleyError.networkResponse != null) {
        int statusCode = volleyError.networkResponse.statusCode;
        Log.w(tagToUse, TAG + " response code:" + statusCode + "");
        byte[] data = volleyError.networkResponse.data;
        int length = data.length;
        StringBuilder stringBuilder = new StringBuilder(length);
        for (int x = 0; x < length; x++) {
            stringBuilder.append(((char) data[x]));
        }
        String errorMessage = stringBuilder.toString();
        Log.d(tagToUse, TAG + " Server error data: " + errorMessage);
    }
Shawn Vega
  • 11
  • 3
-1

Bro first check the API (Application Programming Interface) that your response is getting in Json or not then next step is using volley. I think you API is not correct

Capt Wilco
  • 11
  • 1