i have the following code to load a file from my website
class DownloadTT4FileTask extends AsyncTask<String, String, String> {
private Context mContext;
private String mFilename;
private ProgressDialog progressDialog;
String retString="";
public DownloadTT4FileTask(Context context, String filename) {
mContext=context;
mFilename=filename;
}
@Override
protected void onPreExecute() {
Log.d("DownloadTT4FileTask", "onPreExecute");
progressDialog = ProgressDialog.show(mContext, mFilename, "Loading. Please wait...");
}
protected String doInBackground(String... args) {
URL url;
try {
url = new URL(args[0]);
java.net.URLConnection con = url.openConnection();
con.connect();
//Log.d("DownloadTT4FileTask", "con.connect ok ");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
String line;
for (; (line = in.readLine()) != null; ) {
// just read the line and save it
retString += line+"\n";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retString;
}
protected void onPostExecute(String result) {
Log.d("DownloadTT4FileTask", "onPreExecute");
progressDialog.dismiss();
}
};
// loading from website
filename = "http://2112design.com/tabs/"+band+"/"+song+".tt4";
String fileContents = new DownloadTT4FileTask(context, filename).execute(filename).get(15L, TimeUnit.SECONDS);
br = new BufferedReader(new StringReader(fileContents));
it loads fine (about 5 secs to load) but the progress dialog is a bit off. it doesn’t show up on the screen at the start of the download. it briefly flashes on screen at the end of the task.
i’ve seen many examples of how to use this and it looks like this is pretty normal code.
maybe the context is the issue? i get that from an onChildClick that running in a fragment which isn’t the main activity. i tried using the main activity context but that just crashed.
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Globals.mDoc.OpenTT4Document(parent.getContext(), band, song, mRemoteFilesThis==null ? Doc.SDCARD : Doc.WEBSITE);
return false;
}
any ideas? thanks
as Doc says about AsyncTask.get() :
currently you are calling AsyncTask.get() on main UI thread and progress dialog not appeared . you will need to start AsyncTask without calling get() method as :
and update UI after doInBackground completed inside onPostExecute as :
EDIT :
if you want to call get method of AsyncTask then use a Thread to get result back and avoid freezing of UI as :