rahman
rahman

Reputation: 31

How to get Json response

Im very new for android.. I want to get response from restful webservice. Webservice works fine. But, how get response from android.. If i run the application please wait progress only came... Please anyone help

Here my code

 public void invokeWS(RequestParams params){
            // Show Progress Dialog
            prgDialog.show();
            // Make RESTful webservice call using AsyncHttpClient object
            AsyncHttpClient client = new AsyncHttpClient();
            client.get("http://192.168.2.2:9999/useraccount/login/dologin", params, new JsonHttpResponseHandler() {
                // When the response returned by REST has Http response code '200'
                @Override
                public void onSuccess(int statusCode, Header[] headers, String response) {
                    // Hide Progress Dialog
                    prgDialog.hide();
                    try {
                        // JSON Object
                        JSONObject obj = new JSONObject(response);
                        // When the JSON response has status boolean value assigned with true
                        if (obj.getBoolean("status")) {
                            Toast.makeText(getActivity().getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
                            // Navigate to Home screen
                            //navigatetoHomeActivity();
                        }
                        // Else display error message
                        else {
                            errorMsg.setText(obj.getString("error_msg"));
                            Toast.makeText(getActivity().getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }
                }

                // When the response returned by REST has Http response code other than '200'
                @Override
                public void onFailure(int statusCode, Header[] headers, String content, Throwable error) {
                    // Hide Progress Dialog
                    prgDialog.hide();
                    // When Http response code is '404'
                    if (statusCode == 404) {
                        Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code is '500'
                    else if (statusCode == 500) {
                        Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code other than 404, 500
                    else {
                        Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
                    }

                }
            });
        }

In above code, Header[] automatically strike out in onSuccess method. How to fix it. Please anyone help me!!

Upvotes: 2

Views: 804

Answers (3)

Ram Mandal
Ram Mandal

Reputation: 1959

In order to fetch data from server please follow the steps here

first add this dependency in your build.gradle file and sync it compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Now create a class named Appcontroller which extends Application and add this and import those api which is showing red line

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();


private RequestQueue mRequestQueue;

private static AppController mInstance;

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


}

public static synchronized AppController getInstance() {
    return mInstance;
}

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


    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    int socketTimeOut = 60000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    req.setRetryPolicy(policy);
    getRequestQueue().add(req);
}

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

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

public static String getDate() {
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = new Date();
    String formatedDate = dateFormat.format(date);
    return formatedDate;
}
}

now add these two to your Activity

 Response.Listener<String> jsonResponse;
    Response.ErrorListener errorListener;

and initialize those in oncreate like this

    jsonResponse = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d("Response", response);

        //parseData(response); and store it


    }
};

    errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(getApplicationContext(), "Unable to fetch Data from server", Toast.LENGTH_SHORT).show();
        finish();
    }
};


    if (ServerConfig.isNetworkOnline(SplashScreen.this)) {
        StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
        };
        AppController.getInstance().getRequestQueue().add(strReq);
    } else {
        Toast.makeText(getApplicationContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
        finish();
    }

if problem let me know and dont forget to add Appcontroller to your manifest

<application
android:name=".AppController"..../>

Upvotes: 0

Chris
Chris

Reputation: 4593

I presume you are using LoopJ library, which is fine, stick with it if you do.

You are using JsonHttpResponseHandler, rather use AsyncHttpResponseHandler. The response will come back as byte array, so you will need to parse it to json. I have created it here as seperate function for easy reusing. For example:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.2.2:9999/useraccount/login/dologin", params, new AsyncHttpResponseHandler() { //here is where you should use AsyncHttpResponseHandler instead

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            Log.d("*** LOG login: " + this.getClass().getName(), "SUCCESS");

            JSONObject responseParsed = parseResult(response);

            //your code continue here, example hide the progress bar
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            Log.d("*** LOG error: " + this.getClass().getName(), e.toString());
        }

    });

Then here is the example code to parse the reponse byte array. The function is called from inside the previous onSuccess():

 /**
 * Parse the byte[] that is returned from the server first into a string then cast the results string into a json object. 
 * This is wrapped inside a seperate function so it can be used by multiple calls.
 * @param response
 * @return
 */
JSONObject parseResult(byte[] response) {
    String str = null;
    try {
        str = new String(response, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    JSONObject responseToJson = null;
    try {
        responseToJson = new JSONObject(str);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return responseToJson;
}

Upvotes: 0

KaHeL
KaHeL

Reputation: 4371

first of all make sure you have the permission on your manifest:

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

Now second is that I suggest you to use Volley for request. It's easy to use and in case you're using Android studio it's much easier to plugin the library. Just add this line to your app.gradle dependencies and you're good to go.

compile 'com.mcxiaoke.volley:library:1.0.17'

For more information about the mirror library click here

now for sample implementation:

public void SendRequest(View view){
        progressDialog.setMessage("Please wait");
        progressDialog.show();

        String url ="YOUR_URL";

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("Message", "Response is: " + response);
                        progressDialog.dismiss();

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Message", "Error");
                error.printStackTrace();
                progressDialog.dismiss();
            }
        });

        stringRequest.setTag("YOUR_TAG");
        // Add the request to the RequestQueue.
        queue.add(stringRequest);
    }

and to cancel your request

public void CancelRequest(View view){
        queue.cancelAll("YOUR_TAG");
        Log.e("Message", "Request cancelled");
    }

For easier handling in case you need to change fragments to be displayed just add this on pause or on stop. Goodluck!

Upvotes: 2

Related Questions