views:

380

answers:

1

Hi, I have here a function that downloads data from a remote server to file. I am still not confident with my code. My question is, what if while reading the stream and saving the data to a file and suddenly I was disconnected in the internet, will these catch exceptions below can really catch that kind of incident? If not, can you suggest how to handle this kind of incident?

Note: I call this function in a thread so that the UI won't be blocked.

public static boolean getFromRemote(String link, String fileName, Context context){ 
        boolean dataReceived = false;
        ConnectivityManager connec =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connec.getNetworkInfo(0).isConnected() || connec.getNetworkInfo(1).isConnected()){
                try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpGet httpGet = new HttpGet(link);
                        HttpParams params = httpClient.getParams();
                        HttpConnectionParams.setConnectionTimeout(params, 30000);
                        HttpConnectionParams.setSoTimeout(params, 30000);
                        HttpResponse response;
                        response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200){
                            HttpEntity entity = response.getEntity();



                            InputStream in = null;
                            OutputStream output = null;

                            try{
                                in = entity.getContent();

                                String secondLevelCacheDir = context.getCacheDir() + fileName;

                                File imageFile = new File(secondLevelCacheDir);

                                output= new FileOutputStream(imageFile);
                                IOUtilities.copy(in, output);
                                output.flush();
                            } catch (IOException e) {
                                Log.e("SAVING", "Could not load xml", e);
                            } finally {
                                IOUtilities.closeStream(in);
                                IOUtilities.closeStream(output);
                                dataReceived = true;

                            }
                        }
                    }catch (SocketTimeoutException e){  
                        //Handle not connecting to client !!!!
                        Log.d("SocketTimeoutException Thrown", e.toString());
                        dataReceived = false;

                    } catch (ClientProtocolException e) {
                        //Handle not connecting to client !!!!
                        Log.d("ClientProtocolException Thrown", e.toString());
                        dataReceived = false;

                    }catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        dataReceived = false;
                        Log.d("MalformedURLException Thrown", e.toString());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        dataReceived = false;
                        Log.d("IOException Thrown", e.toString());
                    } 
                }
            return dataReceived;

        }
A: 

I use the following snippet to check if Network is Available before I start a network communication(Prevention better than cure?). Once the communication starts, I can only hope that the network remains available throughout. If not, I would catch Exception thrown and display a message to the user.

public boolean isNetworkAvailable() {
   Context context = getApplicationContext();
   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity == null) {
      boitealerte(this.getString(R.string.alert),"getSystemService rend null");
   } else {
      NetworkInfo[] info = connectivity.getAllNetworkInfo();
      if (info != null) {
         for (int i = 0; i < info.length; i++) {
            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
               return true;
            }
         }
      }
   }
   return false;
}

You can attach a DefaultThreadHandler with any thread which would be used if any exception go uncaught in the exception-raising code.

[EDIT: Adding sample code]

//attaching a Handler with a thread using the static function
Thread.setDefaultUncaughtExceptionHandler(handler);

//creating a Handler
private Thread.UncaughtExceptionHandler handler=
        new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(TAG, "Uncaught exception", ex);
            showDialog(ex);
        }
    };

void showDialog(Throwable t) {
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
            builder
                .setTitle("Exception")
                .setMessage(t.toString())
                .setPositiveButton("Okay", null)
                .show();
    }
Samuh
Can you give some example on how to create a DefaultThreadHandler? I haven't experience creating that. Thanks.
M.A. Cape
I haven't used them myself in code(know them only in theory) but I think using them is pretty straight forward. I have edited my answer above; take a look.
Samuh