ProgressDialog not being displayed in Activity with custom View - java

I am developing an Android app which has 2 classes. Game, which extends Activity, and GameView, which extends View.
When the game is loaded, it sets the content view to GameView, which is just a drawing class that uses a canvas to display the game.
I am trying to create a ProgressDialog in the Game class which will show a spinner after a certain action has been done, as this takes a long time to complete. So far I have the following:
setContentView(R.layout.activity_game);
ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Calculating hint");
pd.show();
AsyncTask<String[][], Void, SudokuSquare> nextSquareThread = new GetNextSquare().execute(puzzleNumbers);
next = nextSquareThread.get();
pd.dismiss();
setContentView(gameView);
And my AsyncTask class looks like this:
private class GetNextSquare extends AsyncTask<String[][], Void, SudokuSquare> {
private ProgressDialog dialog = new ProgressDialog(Game.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Finding next number");
this.dialog.show();
}
#Override
protected SudokuSquare doInBackground(final String[][]... args) {
try {
SudokuAdvancedSolver solver = new SudokuSolver(args[0]);
return solver.getOneValue();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#Override
protected void onPostExecute(final SudokuSquare result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
At the moment I have two ProgressDialogs, one inside the AsyncTask and one outside. Which one is correct? Also, the spinner is not being displayed at all. What am I overlooking which is causing this to be the case?

only the one outside is correct. because you are trying the main thread (the UI thread of your activity) by another thread (your asychronic task). you should use a handler in place of this :
1/ you show the progress bar
2/ you load the game in a thread
3/ when the game is loaded you send a message to the handler which will stop the progress bar.
See this exemple . you should dismiss your dialog in the handler (when the handler receives the message from the thread) .

If you don't implement a listener on Asynctask, i could suggest you to dismiss your progress dialog onPostExecute
private ProgressDialog dialog;
public void setProgressDialog(ProgressDialog dialog){
this.dialog = dialog;
}
#Override
protected void onPostExecute(final SudokuSquare result) {
dialog.dismiss();
}
and before you executing Asynctask add this code
nextSquareThread.setProgressDialog(pd);

Related

Pause UI, while update data on postExecute in AsyncTask

I'm using sockets in my app. I created a class SocketClient with methods: onConnect, onSendData, onReadData. Method onReadData extends AsyncTask. It waits for a string message from the server inside doInBackground and then makes a new task to listen for the incoming message. Now I want to pause the UI in my MainActivity class while the message is loading and get it, but don't know how to do that. My Async Task looks like:
public void ReadMyData() {
mt = new ReadDataAsync();
mt.execute();
}
class ReadDataAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// a lot of work
return message;
}
#Override
protected void onPostExecute(String result) {
ReadMyData();
}
}
and MainActivity:
public SocketClient mySocketClient = new SocketClient();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySocketClient.onConnect();
//there I need wait message load and take it
setContentView(R.layout.activity_game);
WorkWithMessage(message);}
Create a progress DIALOG and start it when you know the message is loading, than take it off when the message is loaded.
You can create a progress DIALOG like this:
ProgressDialog pd = New ProgressDialog();
pd.setTitle(”title”);
pd.setMessage(”messgae”);
pd.setCancleable(false);
Than call
pd.show();
When you wish to load the message, and
pd.dismiss();
When you’r done.

Android: Progress Dialog shows a black screen

This is my code that am I using to implement a ProgressDialog when a camera fired and photo taken.
public void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ProgressDialog dialog = ProgressDialog.show(this, "Loading", "Please wait...", true);
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
On clicking on the save button of my android device, instead of displaying the Progress Dialog, it displays a black screen. Please what could be wrong.
You should remember when it comes to Progress dialog is that you should run it in a separate thread. If you run it in your UI thread you'll see no dialog.
If you are new to Android Threading then you should learn about AsyncTask. Which helps you to implement painless Threads.
Sample code:
private class CheckTypesTask extends AsyncTask<Void, Void, Void>{
ProgressDialog asyncDialog = new ProgressDialog(IncidentFormActivity.this);
String typeStatus;
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setMessage(getString(R.string.loadingtype));
//show dialog
asyncDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
Good luck.
EDIT
The method show() must be called from the User-Interface (UI) thread, while doInBackground() runs on different thread which is the main reason why AsyncTask was designed.
You have to call show() either in onProgressUpdate() or in onPostExecute
It is working for me just using your ProgressDialog line of code so the problem must be elsewhere but you can try:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Please wait...");
dialog.setTitle("Loading");
dialog.show();

Show DialogFragment on AsyncTask.onPostExecute when activity is in background;

I got a java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState when trying to show a dialog after the Activity goes to background, I need to show this message to the user, is there any methods to show the dialog when activity is resumed. My code is something like this:
public class MyTask extends AsyncTask<String,String,String>{
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage(getString(R.string.dialog_progress_message));
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// HTTP POST user action
// App goes to background (user press home button i.e.)
// Getting message from server
return message;
}
#Override
protected void onPostExecute(String message) {
progressDialog.dismiss();
DialogAlert dialogAlert = DialogAlert.newInstance(message);
dialogAlert.setCancelable(false);
//App crash here
dialogAlert.show(getSupportFragmentManager(), TAG);
}
}
I have tried with AsyncTaskLoader but the dialog doesn't show up when activity resumes. Any ideas.
Try with below code snippets,
Replace
dialogAlert.show(getSupportFragmentManager(), TAG);
with
getSupportFragmentManager().beginTransaction().add(dialogAlert, "tag")
.commitAllowingStateLoss();

Activity screen goes blank while loading soundpools

I am loading around 100 soundpools of small sound which I need them through out application in an activity.
When this activity starts, the screen goes blank and the background loads after loading all soundpools.
How do make it display the background I which have already added in xml through out while loading soundpools?
Use AsyncTask to handle this.
private class MyBackgroundTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
//initialize views like progress dialog.
}
#Override
protected Boolean doInBackground(String... params) {
//Add code which you want to run in background.
//In your case, code to load sound pools
}
#Override
public void onPostExecute(Boolean success) {
//update UI with the result
}
}
And in onCreate method,
new MyBackgroundTask().execute();

Show ProgressDialog, Retrieve Data, and WAIT FOR IT

I'm writing an app that at many points will attempt to retrieve account information from a website. I'd like to write a single function ("getAccount()") to do the following:
Show a ProgressDialog
Make the call to the website
Wait for a response
Clear the ProgressDialog
Return control to the calling function after the first four steps are done
I'm not having a problem with getting the data from the page; the problem I have is with the whole "show dialog / wait for completion / return control to the calling function" portion. Either the ProgressDialog doesn't show at all, or the function returns to the caller immediately after making the data request from the site, without giving it enough time to retrieve the data.
Any help would be most appreciated.
EDIT: I'm adding a bit of code below for what I have with AsyncTask. Notice that I have the line MsgBox("done") inside grabURL(); this is simply a Toast call. When I run this code, "done" pops up while the HTTP request is still being made. This MsgBox line only exists so I can see if grabURL is properly waiting for GrabURL to finish (which it isn't).
public void grabURL() {
new GrabURL().execute();
MsgBox("done");
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MyContext);
protected void onPreExecute() {
Dialog.setTitle("Retrieving Account");
Dialog.setMessage("We're retrieving your account information. Please wait...");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
// Get account info from the website
String resp = GetPage(ThePage); // I have this classed out elsewhere
// Some other code that massages the data
AccountRetrievalSuccess = true;
} catch (Exception e) {
AccountRetrievalSuccess = false;
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
}
}
The message box done appears because AsyncTask is using a separate thread(s) to run doInBackground. The call to execute does NOT block. You could move message box done to onPostExecute following the call to dismiss. Tip. You may want to call progress.cancel in onPause or you may get unwanted behaviour on orientation change. Finally, if you are retrieving info in doInBackground, consider returning the info in doInBackground. The info will be passed to onPostExecute. So if the info is object MyInfo consider:
private class GrabURL extends AsyncTask<String, Void, MyInfo> {
Can't say for sure without seeing some code but sounds like you are making a asynchronous call to the website when you want to make a synchronous call (which will block and wait for return data) to the website instead.
You want to use an AsyncTask, generate a non-user-cancellable ProgressDialog in the onPreExecute, do your work in doInBackground, and dismiss it in onPostExecute.
Something like this:
public class MyApp extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// blah blah blah
URL url;
try
{
url = new URL("http://example.com");
new MyTask().execute(url);
}
catch (MalformedURLException e)
{
}
}
protected void doSomeStuff()
{
// stuff to do after the asynctask is done
}
protected void throwAWobbly()
{
// stuff to do if you didn't get the data
}
// inner class to do the data getting off the UI thread,
// so android doesn't "not responding" kill you
private class MyTask extends AsyncTask<URL, Void, Boolean>
{
private ProgressDialog dialog;
private boolean gotData = false;
protected void onPreExecute()
{
// create a progress dialog
dialog = ProgressDialog.show(MyApp.this, "",
"Doing stuff. Please wait...", false, false);
}
protected Boolean doInBackground(URL... urls)
{
// get your data in here!
return gotData;
}
protected void onPostExecute(Boolean result)
{
// get rid of the progress dialog
dialog.dismiss();
if (true == result)
{
// got all data!
doSomeStuff();
}
else
{
// oops!
throwAWobbly();
}
}
}
}

Categories

Resources