Dismiss Progress Dialog and handle exception in AsyncTask - android

I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?

Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}

You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}

#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}

You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}

first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions

private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}

Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}

Related

Showing percentage progress dialog while parsing JSON response android

I am getting a JSON response from a URL and convert it into a string. I want to parse this string to get some values from the response. But when the parsing takes place the application shows a blank screen(black screen) until the response is parsed. I wanted to show a ProgressDialog which shows how much data is to be downloaded so that the app does not show that blank screen. I tried showing a ProgressDialog but it is shown before the parsing and after it is done. The in between time still shows the blank screen.
Here is my code:-
String registerContet = "myUrl";
String items;
try
{
items = new FetchItems().execute(registerContet).get();
pDialog = new ProgressDialog(this).show(Home.this, "Fetching news items", "Please wait..");
JSONArray jObject = new JSONArray(items);
for (int i = 0; i < jObject.length(); i++)
{
JSONObject menuObject = jObject.getJSONObject(i);
String title= menuObject.getString("Title");
String description= menuObject.getString("BodyText");
String thumbnail= menuObject.getString("ThumbnailPath");
String newsUrl = menuObject.getString("Url");
String body = menuObject.getString("Body");
String newsBigImage = menuObject.getString("ImageBlobUrls");
map = new HashMap<String,String>();
map.put(SOURCETITLE, title);
map.put(TITLE, description);
map.put(THUMBNAILPATH, thumbnail);
map.put(BODY, body);
map.put(URL, newsUrl);
map.put(IMAGEBLOBURLS,newsBImage);
myNList.add(map);
}
itemsAdapter = new LazyAdapter(Home.this, myNList);
if(pDialog!=null && pDialog.isShowing())
{
pDialog.dismiss();
}
nList.setAdapter(itemsAdapter);
nList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
myDialog = new ProgressDialog(Home.this).show(Home.this, "Fetching news..", "Just a moment");
HashMap<String, String> myMap = myNList.get(position);
Intent nIntent = new Intent(Home.this,NDetails.class);
newsIntent.putExtra("NItems", myMap);
startActivity(nIntent);
}
});
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FetchItems.java is
private class FetchItems extends AsyncTask<String, String, String> {
// TODO Auto-generated method stub
ProgressDialog myDialog;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpResponse response = null;
String resultString = "";
String myResponseBody = "";
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpGet request = new HttpGet(params[0]);
try {
response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
myResponseBody = convertToString(inputStream);
}
}
} catch (Exception e) {
}
return myResponseBody;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/*
* if(myDialog.isShowing()) { myDialog.dismiss(); }
*/
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*
* myDialog = new ProgressDialog(Home.this);
* myDialog.setMessage("Loading"); myDialog.show();
*/
}
}
Can anyone tell me how can I resolve this.
Thanks
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
Creating dialog in activity:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Converting..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Show dialog in onPreExecute()
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Dismiss dialog in onPostExecute()
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Use this code with in onPreExecute method,
private ProgressDialog dialog;
dialog = new ProgressDialog(this);
dialog.setMessage("Please Wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
easy and simple code for percentage in dialog of progress dialog
> protected void onPreExecute() {
dialog = new ProgressDialog(UploadActivity.this);
dialog.setMessage("Loading, please wait.. ");
dialog.show();
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setMessage("Loading, please wait.. "+String.valueOf(progress[0])+"%");
}

when process dialog is being displayed, doInBackground() is not being executed

I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}

ProgressDialog is not displayed

I have an Async Task getting me some data from the web. Async Task works fine and I want a Progress Dialog Spinner to be displayed while the data is being procured from the web.The Progress Dialog Spinner never shows up. Here is my code:
public class JsonHttpParsingActivity extends ListActivity{
private String jsonResult;
private ArrayList nameArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpConnection task = new HttpConnection(this);
AsyncTask<String,Void,String> taskResult = task.execute("Some URL...");
try {
jsonResult = taskResult.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
.
More Code.....
}
}
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
setActivity(activity);
}
public void setActivity(Activity activity) {
m_activity = activity;
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress((int) ((values[0] / (float) values[1]) * 100));
};
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Thanks!
Instead of write a separate method setActivity(activity) (Non UI Thread scope)
for starting ProgressDialog put the code in onPreExecute() (UI Thread) of AsyncTask, Because you are trying to show it in non UI thread.
Try this,
protected HttpConnection(Activity activity) {
m_activity = activity;
}
Override
protected void onPreExecute(String result){
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
Call progress bar from onPreExecute() function
The following code is working fine and tested:
public class HttpConnection extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Activity m_activity;
protected HttpConnection(Activity activity) {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(m_activity);
progressDialog.setMessage("Wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader in = null;
String inputLine= "", finalMessage = "";
HttpURLConnection urlConnection = null;
try {
String urladdress = params[0];
URL url = new URL(urladdress);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((inputLine = in.readLine()) != null){
finalMessage = finalMessage + inputLine;
}
in.close();
Log.v("finalmessage", ""+finalMessage);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return finalMessage;
}
#Override
protected void onPostExecute(String result){
progressDialog.hide();
}
}
Try calling the AsyncTask from another method in the activity. My guess is that right now, you call it in the onCreate method of the activity. Since the activity is still building, this can give you exceptions. A thing I once tried when I had this issue, is starting the asynchronous task from the onPostCreate method of the activity.

How to start and finish progressBar dynamically in android

When I skip second activity class from first activity class, I will start imageprocessing on certain image in second activity and then until new image comes to screen I wnt to start progress bar and then finish when the new image comes to screen. How can I do this ?
Use ProgreaaDialog and AsyncTask. you wil get your soultion
Use AsyncTask in doBackInGroundProcess do image processing. and in doPostExecute() exit or cancel the progress dialog
have a look on the sample code.
To start AsyncTsk use new ProgressTask().execute(null); from the activity where you want to do image processing.
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Have a look here
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Here is a method which when called starts a progressbar
private void downloadText(String urlStr) {
final String url = urlStr;
progressDialog = ProgressDialog.show(this, "", "Trying to register...");
Log.i("First string", urlStr);
try{
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
try{
msg = Message.obtain();
msg.what=1;
}catch(Exception e)
{
}
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (Exception e) {
//////////////////////////////////////
e.printStackTrace();
}
try{
messageHandler.sendMessage(msg);
}catch(Exception e)
{
}
}
}.start();
}catch(Exception e)
{
}
}
and here is the handler code
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
try{
super.handleMessage(msg);
switch (msg.what) {
case 1:
{
break;
}
}
progressDialog.dismiss();
}catch(Exception e)
{
}
}
};
Try this way
first Intialize your ProgressDialog
progressDialog = ProgressDialog.show(this, "", "Trying to ...");
then start a new thread in which you can write your code which needs to be executed
and finally in the handler handle the code and end the progessDialog

How to implement ASyncTask in Android

Can anybody tell me how to update the UI using ASyncTask and give an example?
I am getting the value from two webservices. From two webservices I am getting value in two arraylist on post method will not return value it will rounding in loop. How do I return from onPostExecuteMethod?
This is my async class:
public class HomeTask extends AsyncTask<Void,Void,Bundle>
{
private Context ctx;
public HomeTask(Context context) {
ctx = context;
}
#Override
protected void onPreExecute() {
//super.onPreExecute();
//setContentView(R.layout.splash);
dlg = new ProgressDialog(getDialogContext());
dlg.setMessage("Loading....");
dlg.show();
//setContentView(R.layout.splash);
}
#Override
protected Bundle doInBackground(Void... params) {
Bundle b=new Bundle();
// TODO Auto-generated method stub
try
{
WebService tableservice=new WebService();
tableservicevalue=tableservice.callTableServer(SOAP_ACTION,"",strUsername,strPassWord,questGroupId,URL);
tableservicevalue=decodeXMLData(tableservicevalue);
DomTableParser parser=new DomTableParser();
parser.setTableservicevalue(tableservicevalue);
parsedValue=parser.parseXmlFile(tableservicevalue);
Log.d("1234%%%%$$$$$$$parsed value$$$$$", parsedValue.toString());
WebService service=new WebService();
webservicevalue=service.callHomeServer(SOAP_ACTION,"",strUsername,strPassWord,questGroupId,URL);
webservicevalue=decodeXMLData(webservicevalue);
ArticleParser articleParser=new ArticleParser();
articleParsedValue=articleParser.parseXmlArticle(webservicevalue);
//b.putStringArrayList("articleParsedValue", articleParsedValue);
Log.d("(((((((parsed value is",parsedValue.toString());
b.putStringArrayList("parsedValue", parsedValue);
b.putStringArrayList("articleParsedValue", articleParsedValue);
Log.d("(((((((parsed value is",articleParsedValue.toString());
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return b;
}
#Override
protected void onPostExecute(Bundle b) {
Log.d("vijay checking","checking&&&&");
Log.d("****","*********");
Log.d("calling","handler");
Log.d("****","*********");
parsedValue1=b.getStringArrayList("parsedValue");
articleParsedValue1=b.getStringArrayList("articleParsedValue");
}
onupdating user interface
new HomeTask(HomeActivity2.this).execute(null);
for(int i=0;i<parsedValue1.size();i++)
{
DomParserTableDataSet dataSet=(DomParserTableDataSet)parsedValue1.get(i);
if(i==0)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex0.setText(dataSet.getIndexName());
txtlast0.setText(dataSet.getLastValue());
txtchange0.setText(dataSet.getChangePercentage());
}
if(i==1)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex1.setText(dataSet.getIndexName());
txtlast1.setText(dataSet.getLastValue());
txtchange1.setText(dataSet.getChangePercentage());
}
if(i==2)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex2.setText(dataSet.getIndexName());
txtlast2.setText(dataSet.getLastValue());
txtchange2.setText(dataSet.getChangePercentage());
}
if(i==3)
{
Log.d("&&&&&&index name is", dataSet.getIndexName());
Log.d("&&&&&&index name is", dataSet.getLastValue());
Log.d("&&&&&&index name is",dataSet.getChangePercentage() );
txtindex3.setText(dataSet.getIndexName());
txtlast3.setText(dataSet.getLastValue());
txtchange3.setText(dataSet.getChangePercentage());
}
}
//
for(int i=0;i<articleParsedValue1.size();i++)
{
System.out.println("for loop checking i is"+i);
ArticleDataSet articleDataset=(ArticleDataSet)articleParsedValue1.get(i);
System.out.println("articleDataset.getArticle_title()"+articleDataset.getArticle_title());
HashMap<String, String> mapValue=new HashMap<String, String>();
WebView webviewcontent=new WebView(HomeActivity2.this);
if(articleDataset.getArticle_summary().length()>75)
{
summary=articleDataset.getArticle_summary().substring(0,75)+"...";
}
else
{
summary=articleDataset.getArticle_summary();
}
String html ="<html><body><div><label> <font face=\"verdana\" color=\"#C1002B\" size=\"4\"><b>"+articleDataset.getArticle_title()+"</b> </font> </label>"+ "<label> <font color=\"#000000\" size=\"2\" face=\"verdana\">"+"|"+"</font></label> "+"<label> <font color=\"#AAAAAA\" face=\"verdana\" size=\"2\">"+articleDataset.getArticle_date()+" </font></label></div>";
html=html+"<div><label> <font color=\"#000000\" face=\"verdana\" size=\"2\">"+summary+" </font></label></div></body></html>" ;
webviewcontent.getSettings().setJavaScriptEnabled(true);
webviewcontent.clearCache(true);
final Activity activity = HomeActivity2.this;
webviewcontent.loadData(html, "text/html", "utf-8");
if(i==articleParsedValue1.size()-1)
{
webviewcontent.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url)
{
// setContentView(R.layout.home);
if (dlg.isShowing())
{
dlg.dismiss();
dlg = null;
}
splash.setVisibility(View.GONE);
// setContentView(repl);
}
});
}
mainlinear4.addView(webviewcontent);
//webviewcontent.setOnTouchListener(HomeActivity2.this);
}
}
List<String> data; // declare here so that we can use it in onPostExecute().
public class YourActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
starttask();
}
private void starttask() {
new FileAsync().execute("start");
Toast toast = Toast.makeText(yourActivity.this," start:" , 7);toast.show();
}
class FileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressDialog = ProgressDialog.show(yourActivity.this,
"", "Loading ...", true);
}
#Override
protected String doInBackground(String... aurl) {
// These methods are calling data from web service made
// in sperate class but you can do this here as well.
TempDAO tempDAO = new TempDAOImpl();
data = tempDAO.getDataList(arg1,arg2);
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
TextView textData= new TextView(YourActivity.this);
textData.setText(data.get(1));
textData.setTextColor(Color.WHITE);
textData.setGravity(Gravity.CENTER);
setContentView(textData);
m_ProgressDialog.dismiss();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
AlertDialog.Builder builder;
protected void onPreExecute() {
super.onPreExecute();
builder = new AlertDialog.Builder(TabGroup2ProductsActivity.this);
}
#Override
protected String doInBackground(String... urls) {
if (urls.length == 1) {
return POST(urls[0]);
} else {
if ("pdf".equalsIgnoreCase(urls[1])) {
downloadPDF(urls[0]);
return "";
} else {
downloadImage(urls[0]);
return "";
}
}
}
#Override
protected void onPostExecute(String result) {
}
}
public String POST(String url) {
System.out.println("I am in post data./..............................");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
System.out.println("Status is : " + status);
ParseProductJson parseJson = new ParseProductJson();
if (status == 200) {
result = EntityUtils.toString(response.getEntity());
System.out
.println("################result1###############################"
+ result);
FileOutputStream fos = openFileOutput("productsJson.json",
Context.MODE_PRIVATE);
fos.write(result.getBytes());
fos.close();
System.out.println("Done");
HashMap<String, List<Product>> hashmap = parseJson
.parseProductJson(readProductsJSON("productsJson.json"));
arrGroupelements = parseJson.getHeadingArray(hashmap);
arrChildelements = parseJson.get2dArray(hashmap);
statusClass = status;
} else {
statusClass = 400;
result = "Did not work!";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
and from Activity onCreate(){
int statusClass = 2;
new HttpAsyncTask()
.execute("http://104.130.240.26:8080/bhn/service/products/");
do {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (statusClass == 2);
}
Sample Async task to request webservice
Following is the way how to make AsyncTask :
private class AsyncTaskGetPlaces extends AsyncTask<Void, Void, AsyncTaskResult<Object>>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected AsyncTaskResult<Object> doInBackground(Void... params)
{
try
{
LibHttp libHttp = new LibHttp();
String res = libHttp.listBusiness("21","test#ns.com");
return new AsyncTaskResult<Object>(res);
}
catch (Exception e)
{
e.printStackTrace();
return new AsyncTaskResult<Object>(e);
}
}
#Override
protected void onPostExecute(AsyncTaskResult<Object> result)
{
if(result.getError()!= null)
{
showOKAlertMsg("App",getResources().getString(R.string.txt_data_not_found), false);
}
else
{
String res = result.getResult().toString();
try {
JSONObject resObj = new JSONObject(res);
if(resObj.getString("status_code").equals("1")){
//parse
// Do your task here
}
} catch (JSONException e) {
e.printStackTrace();
showOKAlertMsg("",getResources().getString(R.string.txt_internal_server_error), false);
}
}
}
}
Where AsyncTaskResult is
public class AsyncTaskResult<T>
{
private T result;
private Exception error;
public T getResult()
{
return result;
}
public Exception getError()
{
return error;
}
public AsyncTaskResult(T result)
{
this.result = result;
}
public AsyncTaskResult(Exception error)
{
this.error = error;
}
}

Categories

Resources