user3834185
user3834185

Reputation:

Internet not available causes my android app to crash

When the internet is not available, my android app crashes. I use Exception handling but it is not working. logcat shows ondoingbackground() error. How do I solve it? I also tried timeout handling but it is also not working.

public String readJSONFeed(String URL) throws ClientProtocolException,
        IOException {

    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL);

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();

            get = stringBuilder.toString();
            return get;
        } else {

            // Log.d("JSON", "Failed to download file");
            Toast.makeText(getBaseContext(), "failed json",
                    Toast.LENGTH_SHORT).show();
            pbar.setVisibility(View.VISIBLE);
            return null;
        }
    }  catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), "failed json",
                Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Toast.makeText(getBaseContext(), "failed json",
                Toast.LENGTH_SHORT).show();

    }


}

class ReadJSONResult extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        // TODO Auto-generated method stub

        try {
            json = readJSONFeed(urls[0]);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), "failed json",
                    Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), "failed json",
                    Toast.LENGTH_SHORT).show();

        }
        return json;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        login.setVisibility(View.INVISIBLE);
        pbar.setVisibility(View.VISIBLE);

    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        try {
            pbar.setVisibility(View.GONE);

            JSONObject jsonObject = new JSONObject(result);

            if ("1".equals(jsonObject.getString("success"))) {
                logdata = getSharedPreferences(log, 0);
                SharedPreferences.Editor getlog = logdata.edit();
                getlog.putString("setid", "1");
                getlog.commit();

                String lnid = jsonObject.getString("lnId");
                JSONObject lineman = jsonObject.getJSONObject("lineman");
                String lnName = lineman.getString("lineName");
                SharedPreferences.Editor editor = op_data.edit();
                editor.putString("savelnid", lnid);
                editor.putString("linemanName", lnName);
                editor.commit();
                Bundle basket = new Bundle();
                basket.putString("lnId", lnid);
                Intent i = new Intent("com.example.online.LINEMAN");
                i.putExtras(basket);
                startActivity(i);

                pbar.setVisibility(View.GONE);
                login.setVisibility(View.VISIBLE);
            } else {
                Toast.makeText(getBaseContext(),
                        "Account Not Found \n Please try again.",
                        Toast.LENGTH_LONG).show();
                pbar.setVisibility(View.GONE);
                login.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            Log.d("Ex", e.getLocalizedMessage());
            Toast.makeText(getBaseContext(), "onPost == " + e.toString(),
                    Toast.LENGTH_LONG).show();
            pbar.setVisibility(View.GONE);
            login.setVisibility(View.VISIBLE);
        }

    }

}

Upvotes: 0

Views: 90

Answers (3)

Charaf Eddine Mechalikh
Charaf Eddine Mechalikh

Reputation: 1248

first remove these Toasts :

    Toast.makeText(getBaseContext(), "failed json",
            Toast.LENGTH_SHORT).show();

after that before using a jsonObject you must check if it is valid or not

       JSONObject jsonObject = new JSONObject(result);

            if (jsonObject!=null && !jsonObject.isNull("success"))//this avoid crash when json is null which means when there is no internet
            {if ("1".equals(jsonObject.getString("success"))) {
//do something
    }}

Upvotes: 0

Rajat Mehra
Rajat Mehra

Reputation: 1482

Cannot use Toast in doInBackGround().

Upvotes: 1

Amsheer
Amsheer

Reputation: 7141

Because of this

  Toast.makeText(getBaseContext(), "failed json",
                    Toast.LENGTH_SHORT).show();

You can't call Toast Inside of doInBackGround

Remove Toast .....

If you want to notify user add Toast in onPostExecute() method.

Upvotes: 5

Related Questions