I have used an asyncTask to make an http request and hence i have used progress bar to indicate the progress of ongoings in that thread. Everything works fine till the onPostexecute() method is called, i have displayed the response string in the Logcat but my progress bar doesn't quit.
There was similar questions asked but i didn't get the required solution for the problem.
Please help.
Here is my code:
class RequestTask extends AsyncTask<String, Integer, String> {
#SuppressWarnings("static-access")
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
prgDialog=new ProgressDialog(getActivity());
prgDialog.setCancelable(true);
prgDialog.show(getActivity(), null, "Loading...");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("result", result);
prgDialog.dismiss();
// Do anything with response..
}
}
You're not calling dismiss() on the ProgressDialog instance you think(or want)you do. You create a ProgressDialog and assign it to the prgDialog reference only to call:
prgDialog.show(getActivity(), null, "Loading...");
which will create a new instance of ProgressDialog which you don't dismiss because prgDialog points to another not showing ProgressDialog. Try:
protected void onPreExecute() {
super.onPreExecute();
prgDialog = ProgressDialog.show(getActivity(), null, "Loading...");
}
This is why you should call static methods on the class and not some instance of that class.
Related
I have a method that need to update its status periodically to the server.
I am using AsyncTask to run the HTTP call in background.
PROBLEM: In onPostExecute method upon checking AsyncTask.getStatus, It show the previous task still running which is causing the error.
ERROR: java.lang.IllegalStateException: Cannot execute task: the task is already running.
DIFFERENT STRATEGIES USED TO SOLVE THE PROBLEM BUT NONE IS WORKING
1. Before Relaunching AsyncTask, checked the status, it is showing the thread is RUNNING.
2. Called the AsyncTask.cancel(true), immediately before calling the AsyncTask.execute if it is still running. It turns out AsyncTask still RUNNING and taking more than 3 mins to get cancel.
NOTE: I have checked many similar questions here, but haven't found helpful.
I would really appredicae if any one of you guys give me an example to solve this issue, Thanks a Million in advance......
public class MainActivity extends Activity implements AsyncResponse{
ConnectServer asyncTask =new ConnectServer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
//Start updating server using below method
loop();
}
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
//Log.v(TAG, output);
if(output != null){
//not using this at this point
}
}
//Method that will call Async method to reach server
public void loop(){
TextView b = (TextView) findViewById(R.id.mField);
String str;
try {
str = asyncTask.execute(true).get();
b.setText(str);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// START SERVER CONNECTION
class ConnectServer extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
public int i = 0;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.0.21:8080");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("GPSApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
TextView mField = (TextView) findViewById(R.id.mField);
mField.setText(result+i);
try {
Thread.sleep(10000);
//asyncTask =new ConnectServer();
i++;
String str = asyncTask.execute(true).get();
mField.setText(str+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onPreExecute() {}
}
}
Call getStatus() to get the status of AsyncTask. If the status is AsyncTask.Status.RUNNING, cancel it.
can you please tell me how to call json web service using how to call json webservice using asynctask android .I call like that and got the response.But I need to do like that before calling i need to show "please wait " do some async task in background.and remove that pop up when response come.
public static String getMethod(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
WebServiceRequestManager wb=new WebServiceRequestManager();
String ss= wb.getMethod("htoard?crsCode=add");
System.out.println("String"+ss);
My suggestion would to use AndroidAsyncHttp(LoopJ) for the following reasons.
1) Code structure will be small and elegant.
2) Easy to use.
3) Performance ,it is really fast
DO this way
This is your WebServiceRequestManager.java
public class WebServiceRequestManager {
public String getMethod(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
}
How to call it from Activity from asynctask?
public class MainActivity extends Activity {
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Please Wait...");
}
#Override
protected String doInBackground(Void... params) {
WebServiceRequestManager manager = new WebServiceRequestManager();
return manager.getMethod("http://50.57.145.165:8080/FirstGroupRailApps/jservices/rest/a/destinationdashboard?crsCode=add");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Respose : " + result);
hideProgressDialog();
}
}.execute();
}
public void showProgressDialog(final String msg) {
runOnUiThread(new Runnable() {
public void run() {
if (progress == null || !progress.isShowing()) {
progress = ProgressDialog.show(MainActivity.this, "", msg);
}
}
});
}
public void hideProgressDialog() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (progress.isShowing())
progress.dismiss();
} catch (Throwable e) {
}
}
});
}
}
I have the following piece of code and I would want to add a feature in here such that I know when the JSON content is uploaded. I am uploading a JSON content.
#Override
protected String doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
String state = "";
HttpPost httpPost = new HttpPost(commentURL);
StringEntity se = null;
HttpResponse response = null;
HttpEntity entity = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
InputStream is = null;
try {
se = new StringEntity(params[0].toString());
Log.i("SE", params[0].toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
try {
response = httpClient.execute(httpPost);
Log.i("HTTP POST", httpPost.toString());
Log.i("RESPONSE", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
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");
}
is.close();
state = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return state;
}
I tried researching myself, which is where I stumbled upon the MultipartEntity, but since I am to upload a simple JSON content through POST I didn't find this necessary to use. So how do I show how much progress is made in the upload process and also what is the total size of the JSON content ?? I sort of figured that I would have had to use the StringEntity ? Am I right ?
Initiate your progress bar as
private ProgressDialog pDialog;
On onPreExecute()
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
On onPostExecute()
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
}
For showing progress bar with percentage try ..
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "your_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
I need to download a file from internet to update some resources files in the path
"/data/data/" + context.getPackageName() + "/databases/"
the method
public static void updateDB(){
removeOldCopies();
//how to download a file in a specific directory without open browser????
}
should perform this action without user intervention, showing only a progress dialog
How could I do this?
You can use AsyncTask to show a Progress Dialog on the PreExecute() method and hide/dismiss it in the PostExecute() method.
ProgressDialog prog = new ProgressDialog(this); // Create Progress Dialog
private class DownloadFile extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Display progressDialog before download starts
prog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prog.hide(); //Hide Progress Dialog else use dismiss() to dismiss the dialog
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
InternetManager in = new InternetManager("http://url-to-download");
in.fileRequest();
return null;
}
}
in.fileRequest() will give you the file that you intent to download, Then use FileOutputStream.write(bytes[]) to write it into a file.
And finally call the AsyncTask through,
DownloadFile dd = new DownloadFile();
dd.execute();
InternetManager class which performing internet releted task.
public class InternetManager {
HttpClient httpclient;
HttpGet httpget;
HttpResponse httpresponse;
HttpEntity httpentity;
String url;
String response = null;
byte[] data = null;
public InternetManager(String url) {
this.url = url;
}
public byte[] fileRequest() {
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
try {
httpresponse = httpclient.execute(httpget);
httpentity = httpresponse.getEntity();
data = EntityUtils.toByteArray(httpentity);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("", "File downloaded URL: " + url);
return data;
}
}
I have a simple program that aks questions then call a php file saying if the answer was a yes or a no.
Right now it works but there is a slight pause when the information is being send. I would like some kind message or indicator to come up showing the computer is busy.
Now when I chnage the text of a textvue, before I send the data, the textView does not change, I allso tried to call it's update methed
code
case R.id.butYes:
mSend .setText("Sending your vote to server");
mSend.invalidate();
TalkToServer( mYes[mPes-1] );
UpdateScreen();
mSend .setText("");
break;
String TalkToServer( String addr)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(addr);
HttpResponse response;
String responseBody=new String("");
try {
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseBody;
}
use AsyncTask to avoid hanging of UI when sending data to server just change your code as:
case R.id.butYes:
new SendTextOperation().execute("");
break;
private class SendTextOperation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
//Update UI here
mSend.setText("Sending your vote to server");
mSend.invalidate();
}
#Override
protected String doInBackground(String... params) {
// Talk to server here to avoid Ui hanging
TalkToServer( mYes[mPes-1] );
return null;
}
#Override
protected void onPostExecute(String result) {
// Update screen here after talk to server end
UpdateScreen();
mSend .setText("");
}
}