display progressdialog in non-activity class - android

I am trying to display a dialog in a non-Activity class. Basically, I detect an object in my app, I would like to display a dialog and then switch activities. I'm getting a "java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()" in my logcat.
Here is some of my code:
public ImageTargetsRenderer(Context context) {
this.context = context;
mDialog = new ProgressDialog(context);
}
public void onDrawFrame(GL10 gl) {
testFlag = 0;
// DO NOT RENDER IF THERE IS NO TRACKABLE
if (!mIsActive)
return;
// Call our native function to render content
// RENDER IF THERE IS A TRACKABLE
testFlag = renderFrame();
System.err.println("ImageTargetsRenderer reports: " + testFlag);
if(testFlag > 0 && frameCount > 5)
{
frameCount = 0;
System.err.println("Starting to switch activities.");
mDialog.setTitle("Please wait");
mDialog.setMessage("Please wait");
mDialog.show();
new Thread() {
public void run() {
try{
sleep(5000);
} catch (Exception e) { }
// Dismiss the Dialog
mDialog.dismiss();
}
}.start();
Intent myIntent = new Intent(context, FlashActivity.class);
myIntent.putExtra("com.qualcomm.QCARSamples.ImageTargets.flagTest", testFlag);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(myIntent);
testFlag = 0;
return;
}
frameCount++;
}

Your Dialog should be called from the UIthread so try to use this,
context.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.show();
}
});
Hope this works.

You do this
context.runOnUIThread( new Runnable() {
public void run() {
// show the Dialog
mDialog.setTitle("Please wait");
mDialog.setMessage("Please wait");
mDialog.show();
}
});
}
Thread.sleep(5000);
context.runOnUIThread( new Runnable() {
public void run() {
// Dismiss the Dialog
mDialog.dismiss();
}
});

This is the exception you will get if you are performing any UI operation on any thread or from any background task. Also context.runOnUiThread won't work.
Instead use:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.dismiss();
}
});
You can use the same for showing where activity is the object of activity.

Related

How to change the activity when the progress bar ends in Android?

I want to change the activity after the progress bar ends. Means progress Bar thread ends. I am adding the activity2 after the thread. But the activity2 starts as the application runs. Why is it so?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Intent myIntent = new Intent(getApplicationContext(), activity2.class);
myIntent.putExtra("key", "......"); //Optional parameters
startActivity(myIntent);
You have created a new thread which is responsible for progress bar while on main thread your new activity code is executed. You need to place start activity code within the same thread.
What you can do is :
new Thread(new Runnable() {
public void run() {
while (progressStatus <= 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Intent myIntent = new Intent(getApplicationContext(), activity2.class);
myIntent.putExtra("key", "......"); //Optional parameters
startActivity(myIntent);
}
}).start();
This is because you start the progress bar in a new thread while the start of the intent is in another thread. The thread starting the intent does not wait for the progress bar to be finished because they are asynchronous. You could solve this by starting the intent in the runnable after the while loop is done.

Run a progress dialog while an other process is running

I am trying to run a progress dialog while an other process is running, and I can't do it.
the process that I want run is this:
public void Onclick_editar (View view)
{
float porc;
String repre;
try{
porc = Float.parseFloat(edit_porcentaje.getText().toString());
repre = edit_representante.getText().toString();
try
{
Hilo hilo;
hilo = new Hilo(2, "UPDATE eleccion SET porcentaje="+porc+", delegados='"+repre+"' WHERE id="+idd );
hilo.start();
while(hilo.isAlive()){}
hilo = new Hilo(4, idd);
hilo.start();
while(hilo.isAlive()){}
Toast.makeText(this, "¡Actualizada con éxito!", Toast.LENGTH_SHORT).show();
}
catch(SQLException e)
{
Toast.makeText(this, "Error: Fallo en la base de datos", Toast.LENGTH_SHORT).show();
}
}catch(Exception e)
{
Toast.makeText(this, "Rellena todos los campos", Toast.LENGTH_SHORT).show();
}
}
this is launching when I click a button. thanks!
EDIT/////////////
well I solved the problem with this code!!
public void button(View v) {
new waiting().execute();
}
class waiting extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressdialog;
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
progressdialog = new ProgressDialog(Tab_adminver_modificar_eleccion.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
return null;
}
}
but I don't use a toast in a method doInBackground (FC)
Do you mean you are waiting for hilo to finish in this line : while(hilo.isAlive()){}?
Use AsyncTask instead, make use of its onPostExecute
you can try like this your process will run in background and progress dialog will be executing as well but when process will complete progress dialog will dismiss..
public class asynTask1 extends AsyncTask<String, Void, Boolean> {
public asynTask1 (MainActivity activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
// do process
}
U can call it onclick or also can onCreate.. it better to make separate class for asyntask1 and write
new asynTask1(MainActivity.this).execute(); where you want to call it..
i hope it will helps ...
If your purpose is to show a ProgressDialog, then you can use this function for displaying a progress dialog-
public static void showProgressLoader(Context context, int duration)
{
final ProgressDialog dialog = ProgressDialog.show(context, "", "Loading...");
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
dialog.dismiss();
}
}, duration);
}
In this finction, pass the context and duration in milliseconds for which you want to show, after that duration it will get dissmissed by itself.
public void launchRingDialog(View view) {
final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Downloading Image ...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
**// the MYSql consultation should be here?**
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();

Create thread to run long-work but not responses

thread = new Thread(new Runnable() {
#Override
public void run() {
synchronized (datahandler) {
while (true) {
try {
if (datahandler.getCount() > 0) {
commitData();
}
datahandler.wait();
} catch (InterruptedException e) {
e.printStackTrace();
Log.e("Service", e.toString());
}
}
}
}
});
thread.start();
Commitdata to connect and commit data form datahandler to server. But I dont kow why it shows not respone dialog. If I do not close it, it continouns to commit. Why UI is influenced when I commit data in other thread
public class ThreadsLifecycleActivity extends Activity {
// Static so that the thread access the latest attribute
private static ProgressDialog dialog;
private static Bitmap downloadBitmap;
private static Handler handler;
private ImageView imageView;
private Thread downloadThread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create a handler to update the UI
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
imageView.setImageBitmap(downloadBitmap);
dialog.dismiss();
}
};
// get the latest imageView after restart of the application
imageView = (ImageView) findViewById(R.id.imageView1);
Context context = imageView.getContext();
System.out.println(context);
// Did we already download the image?
if (downloadBitmap != null) {
imageView.setImageBitmap(downloadBitmap);
}
// check if the thread is already running
downloadThread = (Thread) getLastNonConfigurationInstance();
if (downloadThread != null && downloadThread.isAlive()) {
dialog = ProgressDialog.show(this, "Download", "downloading");
}
}
public void downloadPicture(View view) {
dialog = ProgressDialog.show(this, "Download", "downloading");
downloadThread = new MyThread();
downloadThread.start();
}
// save the thread
#Override
public Object onRetainNonConfigurationInstance() {
return downloadThread;
}
// dismiss dialog if activity is destroyed
#Override
protected void onDestroy() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
super.onDestroy();
}
static public class MyThread extends Thread {
#Override
public void run() {
try {
// Simulate a slow network
try {
new Thread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downloadBitmap = downloadBitmap("http://www.devoxx.com/download/attachments/4751369/DV11");
// Updates the user interface
handler.sendEmptyMessage(0);
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
}
//==========================
You can sea in code that handlers are used to post message on GUI thread. further you can read about it over here
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Also Read This http://android-developers.blogspot.de/2010/07/multithreading-for-performance.html

delay an alertdialog

is it posible ??
I have an activity and an alertdialog on it.
but i need the activity run first and then 2 seconds later appears the alertdialog.
i have no idea how. regards
pd: iam not an english speaker
public class Pantalladeinicio extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 2000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.index);
if(checkInternetConnection()==true) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent mainIntent = new Intent(Pantalladeinicio.this,
NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
public void aceptar() {
// Toast t=Toast.makeText(this,"Bienvenido a probar el programa.", Toast.LENGTH_SHORT);
super.onDestroy();
finish();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("TAG", "Internet Connection Not Present");
return false;
}
}
}
I don't understand your question, but looking at the accepted answer I suggest changing the order of your existing code:
new Handler().postDelayed(new Runnable() {
public void run() {
if(checkInternetConnection()) {
Intent mainIntent = new Intent(Pantalladeinicio.this, NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
}, SPLASH_DISPLAY_LENGTH);
Change your code as using Thread and runOnUiThread
//Your Code here...
else
{
myThread();
}
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
Pantalladeinicio.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(Pantalladeinicio.this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
I assume you want to wait for 2 seconds after you get into the else block.
You could do this by calling Thread.sleep(2000); before you call dialogo1.show();. However, this will make your program appear to "freeze". In order to avoid this you can create a seperate thread that sleeps and then displays the dialog.

Using Threading, Runnable and Message in Android

This is my scenario. A class A implements Runnable. When user click a button, there will show a progress dialog and call the method searchMap() to search an address. The dialog dismisses after 10 seconds. I really misunderstand how to execute the run() method. this is my creepy code.
public class AddLocationMapActivity extends MapActivity implements Runnable {
private ProgressDialog progressDialog;
private MyHandler myHandler;
private Message msg;
#Override
public void run() {
mapCurrentAddress();
}
public void mapLocation(View v) // click event here{
progress();
Thread thread = new Thread(this);
thread.start();
}
private class MyHandler extends Handler{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case NOT_OK_MESSAGE: // Fail
alert(AddLocationMapActivity.this, message());
progressDialog.dismiss();
break;
case OK_MESSAGE: // Success
found(); // Point to the appropiate address
progressDialog.dismiss();
break;
case EXPTION_MESSAGE: // Exception
alert(AddLocationMapActivity.this, "Unexpected error");
progressDialog.dismiss();
break;
}
}
}
protected void mapCurrentAddress() {
String addressString = addressText.getText().toString();
Geocoder g = new Geocoder(this);
List<Address> addresses;
myHandler = new MyHandler();
msg = myHandler.obtainMessage();
try {
addresses = g.getFromLocationName(addressString, 1);
if (addresses.size() > 0) {
//address = addresses.get(0);
msg.what = OK_MESSAGE;
myHandler.sendEmptyMessage(OK_MESSAGE);
} else {
// show the user a note that we failed to get an address
myHandler.sendEmptyMessage(NOT_OK_MESSAGE);
}
} catch (IOException e) {
// show the user a note that we failed to get an address
//e.printStackTrace();
myHandler.sendEmptyMessage(EXPTION_MESSAGE);
}
}
private void progress() {
progressDialog = ProgressDialog.show(this,
"Checking", "Contacting Map Server");
Thread progressThread = new Thread();
progressThread.start();
}
}
When click event occurs, the program fails with exception Uncaught Handler
here's a little bit of my threading code that doesn't give away too much...
progress = ProgressDialog.show(this, "", "Loading...", true);
new Thread(new Runnable() {
#Override
public void run()
{
// get some network content
Chooser.this.runOnUiThread(new Runnable() {
#Override
public void run()
{
progress.dismiss();
// update the UI
}
});
}
}).start();

Categories

Resources