Set minimal time for ProgressDialog , maximum not need - android

I need to display user info while app processing some data. I use ProgressDialog like
pd = ProgressDialog.show(MainActivity.this,
"", "Processing",
true, false);
Processing takes while connect to network and download data, but when network is not available it returns immediately and my progress dialog just flash very quick. Is there maybe more elegant solution then to put in catch Thread to sleep for some time :
try{
//connecting and calculating
}
catch(Exception exc){
Thread.sleep(400);
handler.sendEmptyMessage(0);
}
I need to set minimal time for my ProgressDialog regardless of success or failure ? Does anybody know how to achieve that ?

This will help you
Write the following code immediately after the dialog initialization
new Thread(){
public void run(){
try{
Thread.sleep(5000);
}
catch(Exception ex){}
try{
Message msg=actHandler.obtainMessage();
actHandler.sendMessage(msg);
}
catch(NullPointerException ex){
Log.e("Handler Exception :",ex.toString());
dialog.dismiss();
}
}
}.start();
actHandler=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
doSomthing();
}
};
public void doSomething(){
dialog.dismiss();
}

I would do this the other way around: only show your progressDialog if you can establish the connexion. I feel that making the user wait 0.4 second for a result you already know just for the bling is pointless ;)

Related

Android socket programming with ProgressDialog in a method

I would like to have a method that sends a udp broadcast and returns the responses in a list. In addition, a progress dialog is displayed during the broadcast and cancels when the method returns.
I have successfully accomplished the same thing with AsyncTask, but when I do that the class becomes very difficult to reuse because I have to do different things in the onPostExecute depending on where I start the AsyncTask. This is why I would much rather do it with a Thread, below is my method so far:
public static ArrayList<Device> broadcastForDevices(final String broadcastMessage,Context context){
final ProgressDialog p=ProgressDialog.show(context, null,"Broadcasting...",false);
final Handler handler= new Handler() {
#Override
public void handleMessage(Message message) {
Log.i(TAG,"Dismissing");
p.dismiss();
}
};
Thread broadcastForDevices=new Thread(new Runnable(){
#Override
public void run(){
DatagramSocket udpBroadcastSocket=null;
try{
udpBroadcastSocket= new DatagramSocket();
Log.i(TAG, "Created datagram socket");
}
catch(Exception e){
Log.i(TAG,"Exception "+e.getMessage());
}
detectedDevices=processDeviceResponses(sendBroadcastPackets(udpBroadcastSocket,broadcastMessage));
handler.sendEmptyMessage(0);
}
});
//Start then join normally defeats purpose of thread, but socket programming must be done off the UI thread
broadcastForDevices.start();
try {
broadcastForDevices.join();
} catch (InterruptedException e) {
Log.i(TAG, "Interrupted exception");
}
return detectedDevices;
}
The problem with above code is that the progress dialog never shows up. If I make the progress dialog a member variable of the class instead of final, the progress dialog shows up but is never cancelled. In both cases, the "Dismissing" gets logged somehow. Any ideas on how to make this work?
Using Thread:join() will not solve anything. The things you first did in onPostExecute you could now do in your Handler.

Android exit with toast

I have a quit() method that I am using. I use a toast to print out "thank you for using this app". On the next line I do a system.exit(0); and when I run the app, the toast doesn't show before the system exits the app. Is there a way to fix this?
The way you should do it, in your activity:
Toast.makeText(this,"Thanks for using the app",Toast.LENGTH_SHORT).show();
finish();
Forget System.exit
You could run a thread that waits for the duration of your Toast.-
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(WAIT_TIME_IN_MILLIS);
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();

Android let Toast come before Thread.sleep // Systemclock.sleep

I want to make a Toast appear and THEN let a sleep operate.
If i do that, the Toast appears AFTER the sleep, but i want it the other way around. Anyone has a suggestion? Here my code for this
switch (checkedRadioButton) {
case R.id.radio0 : radioButtonSelected = "radiobutton1";
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG).show();
vd.vibrate(100);
android.os.SystemClock.sleep(1000);
vd.vibrate(100);
thanks so far
The display of toast is an asynchronous (i.e not a blocking call) operation, means once the toast request is executed, the operating system jumps to the next operation and meanwhile the toast is prepared and displayed.
To acquire your default behavior, you should execute the thread-sleep call after few seconds of delay. Use a Handler and its postDelay method for this.
Delay time should be like:
LONG_DELAY = 3500; // 3.5 seconds
SHORT_DELAY = 2000; // 2 seconds
Try to use AsyncTask class.Write this code as it is. no need to take the name of variable of class AsyncTask.
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPostExecute(Void result) {
Toast toast2 = Toast.makeText(context, "Task completed",
Toast.LENGTH_SHORT);
toast2.show();
}
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "here is your text before Sleep", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(1000); // time in milisec 1000ms= 1sec
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}.execute();

ProgressDialog crashing application

I'm trying to get a ProgressDialog to load my listview before displaying it but i'm getting a crash. Would there be a better way to implement this?
EDIT: Updated with the logcat error, forgotten about it.
List<String> internetArray = new ArrayList<String>();
private ProgressDialog p;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView internetList = (ListView)findViewById(R.id.list);
p = ProgressDialog.show(this, "Please wait..", "Loading list..", true);
new Thread(){
public void run(){
//do some extreme work before creating list
try {
sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
internetArray.clear();
//p.dismiss();
}
}.start();
getPermissions(this);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, internetArray);
arrayAdapter.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
internetList.setAdapter(arrayAdapter);
}
Without a logcat from a first glance this is the problem: p.dismiss();.
You are trying to dismiss a UI element, in your case the progress dialog from a background thread.
Although I am certain that this is the cause, you should post your logcat for more details.
EDIT: The above error should be taken under consideration, although the error appears in creating the dialog: MainActivity.this this can't be instatiated. You can try passing the actual context by this and not class context MainActivity.this.
p = ProgressDialog.show(this, "Please wait..", "Loading list..", true);
UPDATE: Perhaps in your line of code is working but you have to know that when you are trying to access a UI element from a background thread would cause memory leaks (you are not even trying to access it through runOnUIThread() method, this is serious according to my opinion).
I didn't say that you should not add it at all, but you should add it in the ui thread. To our problem now, did the this work? Because I don't see any new logcat or something... :)

android problem with progress dialog

In my app i m trying to fetch data from server and storing in database.
When it is doing all these work i want at that time progressdialog should show, if successfully data fetches then dialog should close and some alertDialog should show for msg "successfully data fetched". and if any n/w problem there, then it should show different msg that "problem with n/w".
for that i am doing like below,
public void onClick(View arg0) {
myProgressDialog = ProgressDialog.show(
getParent(), "Please wait...",
"Doing upgrade...", true);
new Thread() {
public void run() {
try {
upgradeAll();//function where data fetched from server
sleep(5000);
} catch (Exception e) {
}
// Dismiss the Dialog
myProgressDialog.dismiss();
Toast.makeText(UpgradeAllTableData.this, "Due to some internal problem \n" +
"it couldnot update..", Toast.LENGTH_LONG).show();
}
}.start();
}
AsyncTask code,
private class UpgradeTask extends AsyncTask<Context, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(UpgradeAllTableData.this);
#Override
protected void onPreExecute() {
System.out.println("In onPreExecute ");
Dialog.setTitle("Loading");
Dialog.setMessage("Please wait for few seconds...");
Dialog.show();
}
#Override
protected Void doInBackground(Context... params) {
System.out.println("In doInBackground ");
upgradeAll();
System.out.println("In doInBackground after fetching");
return null;
}
#Override
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
Dialog.dismiss();
Toast.makeText(UpgradeAllTableData.this, "Problem with internet" , Toast.LENGTH_SHORT).show();
alertboxNeutral("Warning", "Problem with Internet Connection", "Okay","Try again");
}
}
Problem is Toast is not showing. why?
My question is which condition and where to give so that if any problem with n/w then it show some msg and success then show another msg.
Where i should write code for that?
Give me some suggestion.
Thank you
Not exactly an answer to your particular question, but have you considered AsyncTask? It's pretty much designed to handle situations like yours, where a task is performed async while showing some progress (and eventual result) on the UI thread. Alternativelly, you could broadcast an intent and have your activity catch it to show the toast, since your Toast should be show from your UI thread as well.
update:
AsyncTask reference - http://developer.android.com/reference/android/os/AsyncTask.html
What you are doing is totally wrong. UI thread handles all UI changes, but here you are creating ProgressDialog in UI thread and dismissing it in some Other Thread.. A solution is make use of AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources