Android: Progress dialog and toast - android

Can anyone help me how to put a progress dialog that loads for 5 seconds and shows a fast after? Here's the code:
btnSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String phoneNo = editTextRecipient.getText().toString();
String message = editTextNewMessage.getText().toString();
setResult(RESULT_OK);
saveState(phoneNo, message);
final Toast toast = Toast.makeText(getBaseContext(),
"Your message " + "\"" + message + "\"" + " is sent to " +"\""+ phoneNo+"\"",
Toast.LENGTH_SHORT);
toast.show();
Intent setIntent = new Intent(Edit_Message.this, Main.class);
startActivity(setIntent);
}
});
}
I want to put a 5 second progress dialog and a tots that prompts that the message has been sent. Can anyone help me?

Please try this
showProgress ();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dialog.cancel();
Intent i=new Intent(getApplicationContext(),Main.class);
startActivity(i);
finish();
}
}, 5000);
private ProgressDialog dialog;
public void showProgress () {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Please wait");
dialog.show();
}

if you really need to make progess bar for 5 second then Progress Dialog & Java thread is use ** Progress dialog**but if you need it to dynamic then AsyncTask is best practice to use.
as per your description you need to raise Toast after complete load then you can make it in after complete thread or in asynctask , onPostExecute() will use.

Related

Android Thread Issues

I'm having some problems running a thread in my android application, It should show a dialog asking the user something and if the user clicks yes, a loading dialog should appear while it's doing something in the background, I created a thread but when I click the yes button, the UI still locks up until the process is done.
Code:
Dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("LOGO.bin Was Not Found, Would You Like To Extract It?")
.setTitle("LOGO Not Found!");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getAndExtract();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
System.exit(0);
}
});
AlertDialog dialog = builder.create();
dialog.show();
getAndExtract:
public void getAndExtract()
{
new Thread(new Runnable() {
#Override
public void run() {
try {
showLoad("Grabbing Logo...");
getLogo();
Thread.sleep(2000);
progressDialog.cancel();
showLoad("Extracting Images...");
extractImages();
Thread.sleep(2000);
progressDialog.cancel();
}catch (InterruptedException iE)
{
iE.printStackTrace();
}
}
}).run();
}
showLoad:
progressDialog.setMessage(msg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
basics of extractImages:
Command cmd = new Command(0, "LogoInjector -i " + getFilesDir() + "/LOGO.bin -d -g " + getFilesDir() + "/");
RootTools.getShell(true).add(cmd);
basics of getLogo:
Command cmd = new Command(0, "dd if=/dev/block/mmcblk0p" + partitionIndex + " of=" + getFilesDir() + "/LOGO.bin");
RootTools.getShell(true).add(cmd);
I also tried putting showLoad in runOnUiThread but there was no change... if I remove progressDialog.cancel(); it does show the loading dialog but after the extract is already complete. I press Yes and it just hangs until getLogo() and extractImages() both completed
Can anyone help me find out why this isn't working?
Thanks!
Try using AsyncTask:
final AsyncTask<Void,Void,Void> asyncTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// do whatever you need to do in background
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute( aVoid);
// do after finished
}
};
asyncTask.execute();
Hope that helps =]

Why the dialog don't works in parallel with a thread?

Why the dialog don't works in parallel with a thread?
Using this code, the activity freeze and the progress dialog don't show...
I need to show the progress dialog during the download of files...
in the onCreate:
pDialog = new ProgressDialog(this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setTitle(null);
pDialog.setMessage(getString(R.string.loading));
in the download method:
startReader = true;
pDialog.show();
new Thread(new Runnable(){
public void run(){
for(int i = 1; i <= Integer.parseInt(pages); i++){
try{
if(!isCached(code,i)){
try{
CODE TO DOWNLOAD THE FILE;
Log.d(TAG, "File downloaded: /"+ code + "/" + "pg" + i + ".rsc");
}catch(IOException e){
runOnUiThread(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(), getString(R.string.reader_errinternetcon), Toast.LENGTH_SHORT).show();
}
});
}
}
}catch(Exception e){
runOnUiThread(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_SHORT).show();
}
});
startReader = false;
break;
}
}
if(startReader){
runOnUiThread(new Runnable(){
public void run(){
Intent intent = new Intent(MainActivity.this, ReaderActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Pages", pages);
intent.putExtra("Code", code);
getApplicationContext().startActivity(intent);
}
});
}
}
}).start();
pDialog.dismiss();
Thread.start() starts the thread but does not wait for it to finish. You dismiss your dialog immediately afterwards. That's why you don't see the progress dialog.
I suggest you make your background thread an AsyncTask. Set up your progress dialog in onPreExecute(), do your background thread processing in doInBackground() and do UI thread post-processing such as dismissing progress dialogs in onPostExecute().

ProgressDialog does not always show up

My application works as a BluetoothServer, almost the same as the BluetoothChat example. I'm facing a strange problem. Inside my run-method where I start reading input from the bluetoothSocket, I want to post a message to a handler. This handler is in a seperate class, to avoid possible memory leaks.
public void run() {
Log.i("", "BEGIN ReadInputThread");
final byte[] buffer = new byte[1024];
int bytesread;
Message msg = handler.obtainMessage();
msg.obj = "0";
handler.sendMessage(msg);
...... snip .....
When I receive the String "0", in my handler, I want to show a progressDialog that informing the user that the application has an incoming file. In my handler, this is how I deal with it:
public class MessageHandler extends Handler {
#Override
public void handleMessage(Message m) {
Vibrator v = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE);
String message = (String) m.obj;
//Getting files
if (message.equals("0")) {
folder.appendToLogFile(new Date().toString(), "Incoming File From: " + deviceName);
v.vibrate(1500);
pd = new ProgressDialog(c);
pd.setTitle("Please Wait..");
pd.setMessage("Retrieving file from " + deviceName);
pd.setCancelable(false);
pd.show();
}
}
The first time, when I have my Activity open, which will start this Thread, the progressDialog will show. After the transfer has finished, I navigate to a new Activity, and then returning to the previous Activity. When I now try to transfer a file, it will succeed, but no ProgressDialog is shown on the screen.
I did some checks just to figure out if the ProgressDialog is "visible" by adding these two lines under the pd.show() statement
if(pd.isShowing())
Log.w("Handler: ", "inside the handler, and the progressdialog is showing");
And this also appears in LogCat, even if the ProgressDialog is not showing!
Can anybody give me a hint, or a solution to this frustration issue?
Thanks in advance!
Just to clarify a bit
My ProgressDialog is created in a class which not extends Activity, it doesn't extend any classes.
The first thing I do, is to post a 0 to my handler, in the start of my run() method. When I know that I have received the last byte-packet from the socket, I send another message to the handler:
if(lastPacket) {
msg = handler.obtainMessage();
msg.obj = "1";
handler.sendMessage(msg);
}
And in my Handler:
#Override
public void handleMessage(Message m) {
Vibrator v = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE);
String message = (String) m.obj;
//Getting files
if (message.equals("0")) {
folder.appendToLogFile(new Date().toString(), "Incoming File From: " + deviceName);
v.vibrate(1500);
pd = new ProgressDialog(c);
pd.setTitle("Please Wait..");
pd.setMessage("Retrieving file from " + deviceName);
pd.setCancelable(false);
pd.show();
if(pd.isShowing())
Log.w("Handler: ", "inside the handler, and the progressdialog is showing");
}
//File complete
if(message.equals("1")) {
Toast.makeText(c, "File Received from: " + deviceName, Toast.LENGTH_LONG).show();
folder.appendToLogFile(new Date().toString(), "File Received");
pd.setMessage(c.getResources().getString(R.string.createCase));
GenerateCase caseGenerator = new GenerateCase(c, pd, lastCases, nextPCN);
caseGenerator.execute("");
}
}
as you can see, I pass the ProgressDialog into the AsyncTask. In my onPostExecute method, I dismiss this ProgressDialog
Solution
If someone is curious. I got confused with the threads. When I left my Activity, I forgot to kill my running thread, which would cause the ProgressDialog to start in a different thread when I resumed my activity.
Close your progress dialog via broadcast Intent;
onPostExecute(){
sendBroadcastIntent(new Intent("ACTION_CLOSE_DIALOG"):
}
BroadCastReceiver receiver = new BroadCastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if(pd.isShowing()){
pd.dismiss();
}else{
pd.show()
}
}
}
call Broadcast here:
pd.show();// call broadcast instead pd.show() use sendBroadcastIntent(new Intent("ACTION_CLOSE_DIALOG")

Android Handler - not working properly

I want to create a dialogBuilder with a text field and a button on it. The idea is to make the program wait for any further actions until the text in the field is entered and the OK button is clicked. Below is the code:
private static final Object wait = new int[0];
private static String result = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler h = new Handler();
final Context context = MainActivity.this;
h.post(new Runnable() {
public void run() {
final Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(R.string.app_name);
final LinearLayout panel = new LinearLayout(context);
panel.setOrientation(LinearLayout.VERTICAL);
final TextView label = new TextView(context);
label.setId(1);
label.setText(R.string.app_name);
panel.addView(label);
final EditText input = new EditText(context);
input.setId(2);
input.setSingleLine();
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_URI
| InputType.TYPE_TEXT_VARIATION_PHONETIC);
final ScrollView view = new ScrollView(context);
panel.addView(input);
view.addView(panel);
dialogBuilder
.setCancelable(true)
.setPositiveButton(R.string.app_name,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
result = input.getText().toString();
synchronized (wait) {
wait.notifyAll();
}
dialog.dismiss();
}
}).setView(view);
dialogBuilder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
result = null;
synchronized (wait) {
wait.notifyAll();
}
}
});
dialogBuilder.create().show();
}
});
String localResult = null;
try {
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
throw new RuntimeException("Cancelled by user");
}
Log.d("RESULT ", "RESULT " + localResult);
} catch (InterruptedException e) {
localResult = result;
result = null;
if (localResult == null) {
// user is requesting cancel
Log.d("CANCELED ", "CANCELED " + localResult);
throw new RuntimeException("Cancelled by user");
}
}
Log.d("RESULT AFTER THE DIALOG", "RESULT AFTER THE DIALOG " + result);
}
The program is going to Log.d("Waiting", "Waiting " + localResult); and after that just waiting. NO DIALOG BUILDER IS SHOWN on the activity window. I used the debug mode and saw that the program flow is not entering the run() method, but the value of the Handler.post() is true. And for this reason the dialog is not shown, and the program is waiting.
I have tried to remove the moment with waiting (remove the Handler.post()), just to see if the dialog will show, and it showed and all moved well, but the result was not I am needing - I want the program to wait the input from the dialog ... I am really out of ideas.
Would you please give me some suggestions as I am really out of ideas.
Thanks a lot!
Handlers don't run in a separate thread. So when you call wait() :
synchronized (wait) {
Log.d("Waiting", "Waiting " + localResult);
wait.wait();
}
It waits indefinitely since the handler runs on the same thread as the current thread. Your Runnable can only be executed after the onCreate() method finishes but this will never happen because you just called wait().
You should reconsider your idea and find a workaround (for example, show the dialog the usual way and disable the "OK" button as long as the user does not enter a valid text). But calling wait() on the UI thread cannot go well.
You should be running the display of the Dialog in the UI Thread, not a seperate thread.
An example would be something like this:
In the onCreate()
runOnUiThread(new Runnable() {
#Override
public void run() {
// Display progress dialog when loading contacts
dialog = new ProgressDialog(this);
// continue with config of Dialog
}
});
// Execute the Asynchronus Task
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// code to execute in background
return null;
}
#Override
protected void onPostExecute(Void result) {
// Dismiss the dialog after inBackground is done
if (dialog != null)
dialog.dismiss();
super.onPostExecute(result);
}
}.execute((Void[]) null);
Specifically what is happening here is the Dialog is being displayed on the UI thread and then the AsyncTask is executing in the background while the Dialog is running. Then at the end of the execution we dismiss the dialog.

ProgressDialog dismissal in android

I want to open a ProgressDialog when I click on the List Item that opens the data of the clicked Item form the Web Service.
The ProgressDialog needs to be appeared till the WebContent of the clicked Item gets opened.
I know the code of using the Progress Dialog but I don't know how to dismiss it particularly.
I have heard that Handler is to be used for dismissing the Progress Dialog but I didn't found any worth example for using the Handler ultimately.
Can anybody please tell me how can I use the Handler to dismiss the Progress Dialog?
Thanks,
david
Hi this is what you want
public void onClick(View v)
{
mDialog = new ProgressDialog(Home.this);
mDialog.setMessage("Please wait...");
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable()
{
#Override
public void run()
{
statusInquiry();
}
}).start();
}
here is the web webservice that is called
void statusInquiry()
{
try
{
//calling webservice
// after then of whole web part you will send handler a msg
mHandler.sendEmptyMessage(10);
}
catch (Exception e)
{
mHandler.sendEmptyMessage(1);
}
}
and here goes handler code
Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 10:
mDialog.dismiss();
break;
}
}
}
};
A solutiion could be this:
ProgressDialog progressDialog = null;
// ...
progressDialog = ProgressDialog.show(this, "Please wait...", true);
new Thread() {
public void run() {
try{
// Grab your data
} catch (Exception e) { }
// When grabbing data is finish: Dismiss your Dialog
progressDialog.dismiss();
}
}.start();

Categories

Resources