Wednesday, July 24, 2013

Android: downloading text data from network url

reference: http://developer.android.com/training/basics/network-ops/connecting.html

1) create method to download string from url

String downloadURL(String strurl) throws IOException{
InputStream is = null;
   // Only display the first 500 characters of the retrieved
   // web page content.
   int len = 500;
   
   try{
    URL url = new URL(strurl);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setReadTimeout(10000); // 10 sec
    conn.setConnectTimeout(15000); // 15 sec
    conn.setRequestMethod("GET");
    conn.setDoInput(true); // allows receiving data.
    // starts query
    conn.connect();
    int response = conn.getResponseCode();
    Log.d("connection", "response is " + response);
    is = conn.getInputStream();
   
    InputStreamReader reader = new InputStreamReader(is);
   
    char[] buff = new char[len];
    reader.read(buff);
   
    String result =  new String(buff);
    Log.d("connection", "message is " + result);
    return result;
   }
   finally{
    if(is!=null){
    is.close();
    }
   }
}

2) create class to handle download in background process
// class to handle download
// http://developer.android.com/reference/android/os/AsyncTask.html
// < Params, Progress, Result>
// Params - the type of the parameters sent to the task upon execution.
// Progress - the type of the progress units published during the background computation.
// Result - the type of the result of the background computation.
// so in this case, String is the data type of parameter sent to task, void for type of progress units, string for data type of result
class MyTask extends AsyncTask<String, Void, String>{

@Override
  // "String..." = optional parameter. can be nullable 
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
return downloadURL(params[0]);
}
catch (Exception ex){
Log.d("download", "Error is " + ex.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("post-execute", result);
et2.setText(result); // display in EditText
}
}

3) Get connection state and execute the background process

// need to have android.permission.ACCESS_NETWORK_STATE
ConnectivityManager mgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected()){
new MyTask().execute(url);
}

No comments: