App crashes when wifi is out of range

133 views Asked by At

I have an app that crashes when the wifi on phone goes out of range. It gets strings from an online txt mainly and I do disconnect the HTTPURLConnection after it gets done, so I was not expecting the crash. Below is the relevant code;

To check network availablity(all code that uses an internet connection gets checked by this first):

public boolean isNetworkAvailable() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            //if (netInfo != null && netInfo.isConnected()) {
            return true;
        }
        return false;
    }

My checkForPromptPassword asynctask that runs on onResume:

private class CheckForPromptPasswordAgain extends AsyncTask<Void, Void, Boolean>
    {
        //    ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            //  pdLoading.setMessage("\tFetching Database...");
            //     pdLoading.show();
        }
        @Override
        protected Boolean doInBackground(Void... params) {

            //this method will be running on background thread so don't update UI frome here
            //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
            //view GONE by default of update button



                    if (isNetworkAvailable()){
                        if (PromptForPasswordAgain()){
                            //TODO: //show update button or dialog
                            return true;
                        }else{
                            //TODO: //proceed as normal 
                            return false;
                        }
                    }


                    return false;

        }





        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);


            //this method will be running on UI thread


            if (result==true){
                promptForPassword();
            }else{

                //  showDialog("string", "string",0);
            }



            //  pdLoading.dismiss();
        }
    }

My checkForUpdate AsyncTask that runs on OnResume():

Private class CheckForUpdate extends AsyncTask<Void, Void, Boolean>
        {
            //    ProgressDialog pdLoading = new ProgressDialog(MainScreenActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            //  pdLoading.setMessage("\t string.");
            //     pdLoading.show();
        }
        @Override
        protected Boolean doInBackground(Void... params) {

            //this method will be running on background thread so don't update UI frome here
            //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
            //view GONE by default of update button


            if (fileExistance("data.txt")){
                try {
                    if (isNetworkAvailable()){
                        if (isDatabaseContentDifferent()){
                            //TODO: //show update button or dialog
                            return true;
                        }else{
                            //TODO: //proceed as normal 
                            return false;
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block

                    e.printStackTrace();
                }
            }else{
                Log.i("error","file data.txt does not exist in internal");
                return false;
            }

            return false;
        }


        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);


            //this method will be running on UI thread

            Button updateButton = (Button) findViewById(R.id.UpdateDatabase);
            updateButton.setVisibility(View.GONE);
            if (result==true){
                showDialog("Database Updated On Server", "The  Database App has detected a change in the database, press \"Update Database\" to account for the change(s).  ",0);
                updateButton.setVisibility(View.VISIBLE);
            }else{
                updateButton.setVisibility(View.GONE);
                //  showDialog("No Update Detected", "The Database App has detected a change in the database, press \"Update Database\" to account for the change(s).  ",0);
            }



            //  pdLoading.dismiss();
        }
    }

Example of the HTTPURLClient that I am using, many functions but this is the basic structure:

public boolean isDatabaseContentDifferent() throws IOException{
        String page = null;
        try{
            URL url = new URL(_data);
            HttpURLConnection.setFollowRedirects(true);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(false);
            con.setReadTimeout(20000);
            con.setRequestProperty("Connection", "keep-alive");
            //get etag for update check
            //String etag= "";

            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
            ((HttpURLConnection) con).setRequestMethod("GET");
            //System.out.println(con.getContentLength()) ;
            con.setConnectTimeout(5000);
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            //make seperate function for etag it doesn't work with GET
            //String etag = con.getHeaderField("etag");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println(responseCode);
            }
            StringBuffer buffer = new StringBuffer();
            int chars_read;
            //int total = 0;
            while ((chars_read = in.read()) != -1) 
            {
                char g = (char) chars_read;
                buffer.append(g);
            }
            page = buffer.toString();
            //create password.txt to internal
//TODO: checkkk
            con.disconnect();
        }catch(Exception e){
            showDialog("Database Fetch Failure","Unable to Fetch Password Database, check your internet" +
                    " connection and try again later.",0);
            Log.i("Page", "Error in isDatabaseContentDifferent()");
            return false;
        }

        if (fileExistance("data.txt")){
            if (isTextInFileDifferent(page,"data.txt")){

                return true;

            }else{
                return false;
            }

    }else{
        Log.i("Page","file data.txt does not exist IN isDatabaseContentDifferent()");
        return false;
        }
    }

Any help will be highly appreciated. Thanks.

0

There are 0 answers