如果服务器连接期间没有互联网,Android应用程序崩溃

时间:2015-06-25 11:13:13

标签: android android-json android-internet

我正在调用一个url来获取数据并插入我的数据库中。我提供了一个没有互联网检查。如果我在没有互联网连接的情况下打开应用程序,它会起作用,会弹出一个弹出窗口..但如果我连接到网址并且互联网进入中间过程,我的应用程序崩溃了,如何解决?

我的代码:

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();

    }

请帮忙

1 个答案:

答案 0 :(得分:0)

为什么你不去寻找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);
                }
}

在调用asynctask之前检查

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

                }
相关问题