Question

I am communicating with a database in php mysql travez to display results in a ListView, but I'm trying to implement a ExeptionConnection for when 3G or WIFI but the application can not connect, return to previous Activity and show a Toast. but not how to implement it in my code, I could only implement JsonExeption. This is my code:

protected String doInBackground(String... args) {



        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
                params);



        Log.d("All Products: ", json.toString());

        try {


            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
                for (int i = 0; i < list_rs.length(); i++) {
                    JSONObject c = list_rs.getJSONObject(i);

        //Process Code
                }
            } else { 

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

Where url_list_rs is the url of my php. Where I can Implement ExeptionConnection? Can anyone help? Thank Masters!

Was it helpful?

Solution

If you want to create you own exception, you can do:

//create a new Exception class    
public class ConnectionException extends Exception {
    public ConnectionException(String message){
         super(message);
    }
}

In your makeHttpRequest method

if(no connection) { //check connection
    throw new ConnectionException ("No connection!");
} else { ... }

Finally, and try-catch block

try {
    JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
            params);
catch(ConnectionException ex) {
    ex.printStackTrace();
}

Note: I am not sure if this is the best practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top