I have this really crazy problem which I cant seem to tackle. I tried many variations to my approach but it doesnt seem to work like I intended.
What I want is when the user clicks a button on my MainActivity, it should spawn a new thread made available by AsyncTask. The MainActivity should display a ProgressDialog in the meanwhile. The newly created thread is incharge of using a HTTP connection to fetch xml through a url, parse it and store the data in a local database.
What I want is the AsyncTask thread to throw a timed out exception, or any exception in case there is no data connection or if the xml is not available at the url. It must dismiss the ProgressDialog at that time.
This is what I did, sometimes it works but at times it just shows the ProgressDialog for a long time
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(MainActivity.this, "Working..",
"Fetching Values", false,true);
}
protected String doInBackground(String... params) {
String xml = null;
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
false);
HttpGet method = new HttpGet(
new URI(
"http://www.blahblahblah.xml"));
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams
.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse res = client.execute(method);
InputStream is = res.getEntity().getContent();
parser.setInput(is, null);
int eventType = parser.getEventType();
parser.nextTag();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getAttributeCount() == 2) {
myDbHelper.update(parser.getAttributeValue(0),
parser.getAttributeValue(1));
}
}
eventType = parser.next();
}
System.out.println("End document");
xml = "Done, Database updated :)";
}
catch (Exception e) {
xml = "Error: Unable to fetch data";
e.printStackTrace();
}
return xml;
}
@Override
protected void onPostExecute(String xml) {
pd.dismiss();
Toast.makeText(MainActivity.this, xml, Toast.LENGTH_SHORT).show();
}
}
best way is
you can check data connectivity before starting async task
like
boolean isInternetConnectd;
if(isInternetConnectd)
{
// do network related task….
}
else
{
// show dialog “internet connection not available”
}