简体   繁体   中英

Android App Crashes if no internet during server connection

I am calling a url to fetch data and insert in my database. I have provided a no internet check. If I open the app without internet connection, it works fins, a pop up comes.. But if I connect to the url when I have internet and the internet goes in middle the process, my app crashes, How to fix it?

My code:

public class DoPOSTPen extends AsyncTask<String, Void, Boolean> implements OnCancelListener {
    @SuppressWarnings("deprecation")
    @Override
    protected Boolean doInBackground(String... arg0) {

        try {

            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://testapi.pharmeazy.in/api/MediEazy/GetAllInvoices");

            request.addHeader("Authorization", " basic NDlyaWNva2pvaWQwM2ptZGlraWRES09qZGZpamRmNzY0dDA4NWp6MzcyOHdzMkpJS1M4MTA0c2NvcTJ1OTRkazphd0VEMzI3MkA4WWFzZEU3MjI3IUBeIypVSFMq");
            request.setHeader(HTTP.CONTENT_TYPE, "application/json");
            System.out.println("PRIINTING");

            HttpResponse response = null;
            try {
                response = client.execute(request);

                Log.d("Response of GET request", response.toString());
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            InputStream inputStream = response.getEntity().getContent();
            String result = Utils.convertInputStreamToString(inputStream);


            System.out.println("server response is :" + result + "\n" + inputStream);


            try {

                ja=new JSONArray(result);




            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
        }
        catch (Exception e) {
            Log.e("ClientServerDemo", "Error:", e);

            toastText2 = "Connection Error !";
        }

        return true;
    }

    protected void onPreExecute() {

        //display the progress dialog

        mProgressHUD2 = ProgressHUD.show(Med.this,"Getting Rejected Orders", true,false,this);

    }

    @Override
    protected void onPostExecute(Boolean valid) {
        mProgressHUD2.dismiss();
        // if server response is successful

       for(int i=0;i<ja.length();i++){

           try {
            jo=ja.getJSONObject(i);


             db.insertLabel(jo.get("Id").toString(), jo.get("CustomerId").toString(), jo.get("PharmacyId").toString(),
                     jo.get("DeliveryAddress").toString(), jo.get("DeliveryName").toString(), 
                      jo.get("OrderStatus").toString(),jo.get("PrescriptionAttached").toString(),jo.get("Discount").toString());




             }


         catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

       }
       new DoPOST3().execute();

    }

Please help

why you don't go for httpurlconection

  @Override
        protected String doInBackground(String... params) {


            String finalResult = null;
            URL url = null;
            HttpsURLConnection urlConnection = null;
            try {           



                url=new URL(URL);
                urlConnection = (HttpsURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);  
                urlConnection.setDoInput(true);   

                urlConnection.setRequestMethod("POST");  
                urlConnection.setUseCaches(false);  
                urlConnection.setConnectTimeout(5000);  
                urlConnection.setReadTimeout(5000);  
                urlConnection.setRequestProperty("Content-Type","application/json"); 
                urlConnection.connect();  


                OutputStreamWriter out = new   OutputStreamWriter(urlConnection.getOutputStream());
                out.write(jsonObjSend.toString());
                out.close(); 
                starttime = System.currentTimeMillis();

                try {
                    mResponseCode = urlConnection.getResponseCode();
                    totaltime = System.currentTimeMillis() - starttime;
                    Log.e("HTTP POST Response Code:", ""
                            + mResponseCode);
                } catch (SSLPeerUnverifiedException e) {

                    Log.e("Exception", Log.getStackTraceString(e));
                } catch (IOException e) {

                    Log.e("Exception", Log.getStackTraceString(e));
                    Log.e("HTTP POST Response Code(2):", ""
                            + mResponseCode);
                }
}

check before calling asynctask

 if(Util.haveNetworkConnection(this))
        {
  HttpPostData req=new HttpPostData(URL, createJsonObject(),this) ;
     req.execute();

                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM