Android Show Loading dialog into AsyncTask



i want to show loading dialog before Json data get loaded into JsonObject using AsyncTask.


The problem im using AsyncTask and calling it from another class (a fragment) ..


so i have created : public static ProgressDialog dialog ; in the fragment activity (using it as a global var)


then calling the Async task :



JSONParser jsonParser = new JSONParser();

jsonParser.execute(url,this);

jObj = jsonParser.get();


Here is the JSONParser (Asynch task)



public class JSONParser extends AsyncTask<Object, Integer, JSONObject> {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
private MovieListBoxOffice act; // The fragment Activity
// constructor
public JSONParser() {
super();
}
ProgressDialog dialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = act.dialog;
dialog.setMessage("Loading...");

dialog.setCancelable(true);
dialog.show();
}


@Override
protected JSONObject doInBackground(Object... params) {


// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpGet httpGet = new HttpGet((String)params[0]);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(line);
}
is.close();
json = sb.toString();

} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
System.out.println("error on parse data in jsonparser.java");
}


return jObj;
}


protected void onPostExecute(String result) {

dialog.dismiss();
}


The result is the loading dialogue don't show until the data are loaded (after the async task finish) !!!


i have doubt that jsonParser.get(); is causing the problem and how can i manage that without changing my code from The fragment class to the postexecute ,


No comments:

Post a Comment