I am currently trying to make an AsyncTask that downloads a file in android. It's at a preliminary state but my code gets drowned in try catch statementes that I autocomple using eclipse's suggestions.
Here is the code from a single function that creates and writes to a file:
public void CreateFolder(View view) throws Exception{
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Dit+/Files");
folder.mkdirs();
folder.toString();
File file = new File(folder, "test.txt");
String url="http://cgi.di.uoa.gr/~std10108/a.txt";
FileWriter fw = new FileWriter(url);
fw.write(a);
fw.close();
}
while when I transfer this block to the async task it turns to this:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params){
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Dit+/Files");
folder.mkdirs();
folder.toString();
String a=params[0];
File file = new File(folder, "test.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fw.write(a);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I know that for the time using the async task is useless but I want to familiarize first with the concept of async tasks rather than using it as it should. Actually the url string is the source of the file I want to to download but I just want to make an example for now.
So my question is: Is there any way to write the async task without these try-catch statements because it makes the code unreadable and ugly.
Calling the function CreateFolder() in the doInBackground() function of the async task would be a good implementation?