I can't stop ProgressDialog with method dismiss(); - android

I don't know why my code not working. I read a lot of same problems, but this is in most cases right solution, but for me is not working. My AsyncTask looks like this:
public class SavingAsync extends AsyncTask<String, String, String> {
private static final String TAG = "DrawView";
private ProgressDialog pd;
private Context context;
private File saveFile;
private Bitmap bitmap;
public SavingAsync(Context c, File sF, Bitmap b) {
context = c;
saveFile = sF;
bitmap = b;
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
ProgressDialog.show(context, "", "Saving...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
OutputStream stream;
try {
stream = new FileOutputStream(saveFile);
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Bitmap is saved sucessfully, but ProgressDialog run forever :/

You are showing ProgressDiaog with
ProgressDialog.show(context, "", "Saving...");
and show method returns a PreogressDialog object.
The dialog you are dismissing using pd reference variable using pd.dismiss() in your code does to have reference to dialog you are showing. You should assign it to pd. Like this
pd = ProgressDialog.show(context, "", "Saving...");
And then calling pd.dismiss() will dismiss the currently showing Dialog.

Related

Progress Dialogue Not Showing On AsyncTask

I am using an AsyncTask To show progress dialogue, the code is running as expected but the progress dialogue is still not showing up. Everything inside doInBackground is executing perfectly. I'm unable to understand what is causing this.
Async Task ->
class MyAsyncTask extends AsyncTask<String,String,String>{
ProgressDialog pd;
Context context;
PyObject object;
String str;
MyAsyncTask(Context contexted) {
this.context = contexted;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setMessage("This May Take Some Time");
pd.setTitle("Loading Tweet Engine");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String og = strings[0];
if(!Python.isStarted()){
Python.start(new AndroidPlatform(context));
Python py = Python.getInstance();
PyObject pyf = py.getModule("myscript");
object = pyf.callAttr("get_tweets",og);
}
else {
Python py = Python.getInstance();
PyObject pyf = py.getModule("myscript");
object = pyf.callAttr("get_tweets",og);
}
return object.toString();
}
#Override
protected void onPostExecute(String s) {
pd.dismiss();
super.onPostExecute(s);
}
}
And it is called by ->
String returnlist = new MyAsyncTask(this).execute(tempvalued).get();

Start activity is slow

I'm write a music application online.But i'm meet a problem... A new activity starts slowly when I select an item in listview...
I don't know resolve, please help me ! :(
Sorry. I'm speak English very bad :(
This is my code:
public class startNewActivity extends AsyncTask<String, Void, String> {
private Activity activity;
private String selectDoc = "div.gen img";
private String attr = "title";
private String result;
public String Quality;
public startNewActivity(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... arg0) {
nameSong = (String) lvSong.getItemAtPosition(positionId);
link = linkSong.get(Integer.valueOf(obj.toString()));
Quality = Utils.getQuality(link, selectDoc, attr, result);
Log.i("Quality", Quality);
changeLink = link.replace(".html", "_download.html").substring(15)
.replaceFirst("", "http://download")
.replace("nhac-hot", "mp3".concat("/vietnam/v-pop"));
Log.i("Change link", changeLink);
try {
//Connect internet
linkIntent = Utils.getLinkPlay(selectLinkPlay, changeLink,
afterChangeLink);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Server has problem... Please while for minutes",
Toast.LENGTH_SHORT).show();
}
return linkIntent;
}
#Override
protected void onPostExecute(String result) {
//i'm want help here
Intent i = new Intent(SongActivity.this, PlayMusicActivity.class);
i.putExtra("song", linkIntent);
i.putExtra("namesong", nameSong);
i.putExtra("Quality", Quality);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
pDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(SongActivity.this, "",
"Please wait...");
}
}
You're starting the new activity inside onPostExecute() which executes only after you've completed doInBackground(). Hence, the time delay.
Ideally, you should start the activity just after you execute your AsyncTask. The AsyncTask will continue in the background while your activity changes.

Need to use a variable which used in for loop

I have an AsyncTask class and I have to use the variable to show pictures in an ImageView. I use jsoup library to parse html page and the problem is that I can't take my variable "bitmap" from doInBackground to onPostExecute method. How can I resolve my problem?
Here is the code :
private class ParseHTML extends AsyncTask<Void, Void, Void>{
String resultTextFmt;
Bitmap bm;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("WebMD");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params){
try{
Document document = Jsoup.connect(mURL).get();
Elements description2 = document.select("h2[class=et_pt_title]");
Log.v("Data3", description2.toString());
resultTextFmt = description2.toString();
Elements divs = document.select("img");
Log.w("DIVS_PICS", divs.toString());
Bitmap bitmap;
for (Element div : divs) {
Log.d("web Stuff",div.text());
// Element myImage = div;
String iurl;
iurl = div.absUrl("src");
Log.w("ABSurl:",iurl.toString());
URL url = new URL(iurl);
bitmap = BitmapFactory.decodeStream(url.openStream()); // I need to get this var
}
bm = bitmap;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
imgView.setImageBitmap(bm); // and put it here to show
textView.setText(Html.fromHtml(resultTextFmt));
mProgressDialog.dismiss();
}
}
You need to declare your AsyncTask like this:
private class ParseHTML extends AsyncTask<Void, Void, Bitmap>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(Void... params){
Bitmap returnValue = new Bitmap();
return returnValue;
}
#Override
protected void onPostExecute(Bitmap result){
imgView.setImageBitmap(result);
}
}
As you can see, you can parametrize result value as a Bitmap for doInBackground() at the Class definition. This way, you will also receive this value in onPostExecute() callback and handle the Bitmap there after composing it.
If you want to make it more sophisticated by also handling input args, or, for example, learn how to monitor the process, you have official documentation about AsyncTask here.

Progress Dialog only shows up when the job is already done

I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});

Return result from AsyncTask

public int postToTwitter(String msg) {
String url = null;
new ImageSender().execute();
// Twitlink I have to pass in next line but it showing null
twitter.updateStatus(msg+" "+twitlink);
return 1;
}
AsyncTask Class:
private class ImageSender extends AsyncTask<URL, Integer, Long> {
private String url;
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(OutgoingHome.this, "", "Sending image...", true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
protected Long doInBackground(URL... urls) {
long result = 0;
ImageUpload upload = ImageUpload.getTwitpicUploader ("8b8f5db5ca383798509af8459f968dbc",auth);
try {
twitlink = upload.upload(new File(path));
result = 1;
} catch (Exception e) {
}
return result;
}
protected void onPostExecute(Long result) {
mProgressDialog.cancel();
}
}
The simplest method is to use the get() method of the AsyncTask. The other way is to implement an OnResultListener and call its onResult() method inside the AsyncTask onPostExecute(). However, the first solution should be enough. Hope this helps.

Categories

Resources