is there a way to speed up the time when changing to another activity? or is there something wrong with my code?
public void connectedAnim(){
final Dialog dialog = new Dialog(LogIn.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.connected);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
IVcon = (ImageView)dialog.findViewById(R.id.IVcon);
IVcon.setBackgroundResource(R.anim.connectedanim);
final AnimationDrawable animcon = (AnimationDrawable)IVcon.getBackground();
dialog.setCancelable(true);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
animcon.start();
Toast.makeText(getApplicationContext(), "Connected to HC-05", Toast.LENGTH_SHORT).show();
}
});
dialog.show();
new Handler().postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 1000);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Intent Menu = new Intent(LogIn.this, Menu.class);
LogIn.this.startActivity(Menu);
}
});
}
this is my method that is to be called when i connected my bluetooth to arduino, and i have an animation to it so after the animation comes the change to a new activity. this is how i called the connectedAnim() method
pwordtxt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable sa) {
}
#Override
public void beforeTextChanged(CharSequence sa, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence sa, int start,
int before, int count) {
if (sa.length() == 4) {
progressDialog = ProgressDialog.show(LogIn.this, "", "Loading..");
password = getPass("password", getApplicationContext());
Runnable runnable = new Runnable() {
#Override
public void run() {
if ((password.equals(""))) {
if (s.toString().equals("1234")) {
findBT();
try {
openBT();
}
catch (IOException e) {}
beginListenForData();
handler.post(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
connectedAnim();
}
});
} else {
Toast.makeText(LogIn.this, "Incorrect Password", Toast.LENGTH_SHORT).show();
}
} else {
realpass = getPass("password", getApplicationContext());
if (s.toString().equals(realpass)) {
findBT();
} else {
Toast.makeText(LogIn.this, "Incorrect Password", Toast.LENGTH_SHORT).show();
}
}
}
};
new Thread(runnable).start();
}
}
});
}
Related
beacon manager.addMonitorNotifier(new MonitorNotifier()
in this method, there are two methods and both are not running .... it is a small app of beacon I want to show the alert .... and that alert in my method in if condition ... but it is not running I did debugger but it is not working
import java.util.Collection;
public class WebViewScreen extends AppCompatActivity implements BeaconConsumer {
public static final String TAG="MainActivity";
private Button startbtn,stopbtn;
private BeaconManager beaconManager=null;
private static final String ALTBEACON_LAYOUT="m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25";
private Region beaconRegion=null;
private void ShowAlert(final String title, final String message){
runOnUiThread (new Thread(new Runnable() {
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(WebViewScreen.this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}));
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
Log.d(TAG,"on create called");
startbtn=findViewById(R.id.startButton);
stopbtn=findViewById(R.id.stopButton);
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1234);
beaconManager=BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(ALTBEACON_LAYOUT));
beaconManager.bind(this);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startBiconMonitoring();
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopBiconMonitoring();
}
});
}
private boolean entryMessageRaised=false;
private boolean exitMessageRaised=false;
private boolean rangingMessageRaised=false;
private void stopBiconMonitoring() {
Log.d(TAG,"Stop Beacon Monitering");
try {
beaconManager.stopMonitoringBeaconsInRegion(beaconRegion);
beaconManager.stopRangingBeaconsInRegion(beaconRegion);
}catch (RemoteException e){
e.printStackTrace();
}
}
private void startBiconMonitoring() {
Log.d(TAG,"Start Beacon Monitering");
try {
beaconRegion = new Region("My Bicons",Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"),Identifier.parse("4"),Identifier.parse("200"));
beaconManager.startMonitoringBeaconsInRegion(beaconRegion);
beaconManager.startRangingBeaconsInRegion(beaconRegion);
}catch (RemoteException e){
e.printStackTrace();
}
}
private void findID() {
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
if (!entryMessageRaised){
showAlert("didEnterRegion","Entering Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+region.getId1()+"/"+region.getId2()+"/"+region.getId3());
entryMessageRaised=true;
}
else {
Log.d(TAG,"somrething go wrong");
}
}
#Override
public void didExitRegion(Region region) {
if (!exitMessageRaised){
showAlert("didExitRegion","Exiting Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+region.getId1()+"/"+region.getId2()+"/"+region.getId3());
exitMessageRaised=true;
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
if (rangingMessageRaised && collection != null && !collection.isEmpty()){
for (Beacon beacon:collection){
showAlert("didExitRegion","Ranging Region"+region.getUniqueId()+"Beacon Detected UUID/Major/Minor:"+beacon.getId1()+"/"+beacon.getId2()+"/"+beacon.getId3());
}
rangingMessageRaised=true;
}
}
});
}
}
I want to show the alert if the device will found bacon
I am trying to show a custom dialog within Activity and this error occur. I know why this error occur from here and here and also know it's solution. But the problem is I can't find the problem in my code. I've spent anlot of time in finding the error with no luck.
I've called below method on button click
public void changePassword(View view){
DialogChangePassword dialogChangePassword = new DialogChangePassword(ActivityMyAccount.this);
dialogChangePassword.show();
Window window = dialogChangePassword.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
I am showing the dialog here while Activity should live. My question;
I can't dismiss the dialog here, I am dismissing it from within Dialog class.
I am not finishing the activity. If error occurs because the activity is finishing, why is it finishing?
If error is not because of finishing the activity then why does this error occur?
I have a NetworkOperation to be performed in Dialog class, does it have to do something with that?
Here is my Dialog class
public class DialogChangePassword extends Dialog {
Context context;
Button confirm, cancel;
CustomEditText edtOldPwd, edtNewPwd, edtConfirmNewPwd;
ProgressDialog progressDialog;
String PASSWORD_INCORRECT_MESSAGE = "Old password is incorrect.";
public DialogChangePassword(Context context) {
super(context);
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_change_password);
if(progressDialog != null)
progressDialog = null;
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Updating Password.");
progressDialog.show();
confirm = (Button) findViewById(R.id.btnChangePassword);
cancel = (Button) findViewById(R.id.btnCancel);
edtOldPwd = (CustomEditText) findViewById(R.id.edtOldPassword);
edtNewPwd = (CustomEditText) findViewById(R.id.edtNewPassword);
edtConfirmNewPwd = (CustomEditText) findViewById(R.id.edtConfirmNewPassword);
edtConfirmNewPwd.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!edtNewPwd.getText().toString().equals(edtConfirmNewPwd.getText().toString()))
edtConfirmNewPwd.setError("Password doesn't match");
}
});
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!edtNewPwd.getText().toString().equals(edtConfirmNewPwd.getText().toString())) {
Toast.makeText(context, "Password doesn't match", Toast.LENGTH_SHORT).show();
progressDialog.cancel();
return;
}
HashMap<String, String> params = new HashMap<>();
params.put("email", Utility.classUser.getEmailId());
params.put("password", edtOldPwd.getText().toString());
params.put("newPassword", edtNewPwd.getText().toString());
new NetworkOperation().execute(params);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
}
private class NetworkOperation extends AsyncTask<HashMap<String,String>, Void, String> {
#Override
protected String doInBackground(HashMap<String, String>... params) {
try {
ClassAPIRoutes routes = ClassAPIRoutes.initializeRoutes();
return routes.editUserPassword(params[0]);
} catch (final IOException e) {
e.printStackTrace();
getOwnerActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
});
return "error";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.cancel();
dismiss();
if(!s.equals("error")){
JSONObject jsonObject;
try {
jsonObject = new JSONObject(s);
if (jsonObject.get("success").toString().equals("true")) {
Toast.makeText(context, "Password successfully changed.", Toast.LENGTH_SHORT).show();
dismiss();
} else if (jsonObject.get("success").toString().equals("false")) {
if (jsonObject.get("message").toString().equals(PASSWORD_INCORRECT_MESSAGE)) {
Toast.makeText(context, PASSWORD_INCORRECT_MESSAGE, Toast.LENGTH_SHORT).show();
resetFields();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
}
}
}
}
private void resetFields(){
edtOldPwd.setText("");
edtNewPwd.setText("");
edtConfirmNewPwd.setText("");
}
}
I've removed showing progress dialog from onCreate(...) and put it in Async class inside OnPreExecute(...) and it's working fine
My alert dialog keep pops up for 27 times. I have implement handler and inside the handler, i use the CountDownTimer. Alert dialog code is on CountDownTimer's onFinish. Below are my codes.
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.face_detect_surface_view);
mOpenCvCameraView = (Tutorial3View) findViewById(R.id.tutorial3_activity_java_surface_view);
mOpenCvCameraView.setCvCameraViewListener(this);
mPath=getFilesDir()+"/facerecogOCV/";
labelsFile= new labels(mPath);
Iv=(ImageView)findViewById(R.id.imageView1);
textresult = (TextView) findViewById(R.id.textView1);
mHandler = new Handler() {
#Override
public void handleMessage( Message msg) {
Log.e("X", (String) msg.obj);
if (msg.obj=="IMG")
{
Canvas canvas = new Canvas();
canvas.setBitmap(mBitmap);
Iv.setImageBitmap(mBitmap);
if (countImages>=MAXIMG-1)
{
toggleButtonGrabar.setChecked(false);
grabarOnclick();
}
}
else
{
textresult.setText(msg.obj.toString());
textpercent.setVisibility(View.VISIBLE);
textpercent.setText( mLikely + "%");
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
mOpenCvCameraView.enableView();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
final AlertDialog ad = new AlertDialog.Builder(FdActivity.this).create();
ad.setTitle("Recognition Status");
ad.setMessage("Criminal ID :" + textresult.getText().toString() + "\nSimilarities : " + textpercent.getText().toString() );
ad.setButton("Rescan", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Rescanning", Toast.LENGTH_SHORT).show();
Bundle configBundle = new Bundle();
onCreate(configBundle);
mOpenCvCameraView.enableView();
}
});
ad.show();//pops out 27 times
mOpenCvCameraView.disableView();
buttonSearch.setChecked(false);
}
}.start();
}
}
};
text=(EditText)findViewById(R.id.editText1);
buttonCatalog=(Button)findViewById(R.id.buttonCat);
toggleButtonGrabar=(ToggleButton)findViewById(R.id.toggleButtonGrabar);
buttonSearch=(ToggleButton)findViewById(R.id.buttonBuscar);
toggleButtonTrain=(ToggleButton)findViewById(R.id.toggleButton1);
textState= (TextView)findViewById(R.id.textViewState);
textpercent = (TextView)findViewById(R.id.textViewpercent);
imCamera=(ImageButton)findViewById(R.id.imageButton1);
textpercent.setVisibility(View.INVISIBLE);
text.setVisibility(View.INVISIBLE);
textresult.setVisibility(View.INVISIBLE);
toggleButtonGrabar.setVisibility(View.INVISIBLE);
text.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((text.getText().toString().length()>0)&&(toggleButtonTrain.isChecked()))
toggleButtonGrabar.setVisibility(View.VISIBLE);
else
toggleButtonGrabar.setVisibility(View.INVISIBLE);
return false;
}
});
toggleButtonTrain.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (toggleButtonTrain.isChecked()) {
textState.setText(getResources().getString(R.string.SEnter));
buttonSearch.setVisibility(View.INVISIBLE);
textresult.setVisibility(View.VISIBLE);
text.setVisibility(View.VISIBLE);
textresult.setText(getResources().getString(R.string.SFaceName));
if (text.getText().toString().length() > 0)
toggleButtonGrabar.setVisibility(View.VISIBLE);
textpercent.setVisibility(View.INVISIBLE);
} else {
textState.setText(R.string.Straininig);
textresult.setText("");
text.setVisibility(View.INVISIBLE);
buttonSearch.setVisibility(View.VISIBLE);
;
textresult.setText("");
{
toggleButtonGrabar.setVisibility(View.INVISIBLE);
text.setVisibility(View.INVISIBLE);
}
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Straininig), Toast.LENGTH_LONG).show();
fr.train();
textState.setText(getResources().getString(R.string.BLANK));
}
}
});
toggleButtonGrabar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
grabarOnclick();
}
});
imCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mChooseCamera==frontCam)
{
mChooseCamera=backCam;
mOpenCvCameraView.setCamBack();
}
else
{
mChooseCamera=frontCam;
mOpenCvCameraView.setCamFront();
}
}
});
buttonSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (buttonSearch.isChecked())
{
if (!fr.canPredict())
{
buttonSearch.setChecked(false);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.SCanntoPredic), Toast.LENGTH_LONG).show();
return;
}
textState.setText(getResources().getString(R.string.SSearching));
toggleButtonGrabar.setVisibility(View.INVISIBLE);
toggleButtonTrain.setVisibility(View.INVISIBLE);
text.setVisibility(View.INVISIBLE);
faceState=SEARCHING;
textresult.setVisibility(View.VISIBLE);
}
else
{
faceState=IDLE;
textState.setText(getResources().getString(R.string.SIdle));
toggleButtonGrabar.setVisibility(View.INVISIBLE);
toggleButtonTrain.setVisibility(View.VISIBLE);
text.setVisibility(View.INVISIBLE);
textresult.setVisibility(View.INVISIBLE);
}
}
});
boolean success=(new File(mPath)).mkdirs();
if (!success)
{
Log.e("Error", "Error creating directory");
}
}
Somebody please help me to fix this problem. I am still a learner in Android Programming. I did not have idea on how to fix this.
Thanks
I think your handler gets passed that amount of messages. You could verify that with a
Log.e("X", msg.obj);
and check the logcat for that output.
I am implementing an android app.My problem no wis that when I send the data from the client to the server I want the client to know that the data was sent successfully. I have implemented an AlertDialog but when I send the data,I get a message "Can't create handler inside thread that has not called Looper.prepare()". I have attached my code below.
private void saveOrder(final Order order) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
getConnection().saveOrder(order);
handleSuccessSaveOrder();
}
catch (Exception exc) {
Log.d("--- ERROR ---", exc.getMessage());
handleException(exc.getMessage());
}
}
});
thread.start();
}
private void handleSuccessSaveOrder() {
showAlert(Farsi.Convert(" j "),R.drawable.warning);
//showActivity(MainMenuActivity.class);
}
private void showAlert(String message, int iconId) {
alert = new AlertDialog.Builder(ReviewOrderActivity.this);
alert.setTitle("Status Dialog");
alert.setMessage(message);
alert.setIcon(iconId);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
showActivity(MainMenuActivity.class); } });
alert.show();
}
You cannot modify the ui from a non ui thread, use runOnUiThread:
private void saveOrder(final Order order) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
getConnection().saveOrder(order);
runOnUiThread(new Runnable() {
public void run() {
handleSuccessSaveOrder();
}
});
}
catch (Exception exc) {
Log.d("--- ERROR ---", exc.getMessage());
handleException(exc.getMessage());
}
}
});
thread.start();
}
you can not change UI from backgroung thread.
use like this
private void handleSuccessSaveOrder() {
ReviewOrderActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
showAlert(Farsi.Convert(" j "),R.drawable.warning);
}
});
//showActivity(MainMenuActivity.class);
}
Make Handler for display AlertDialog and Try below code instead of your above code, it will solve your problem.
private void saveOrder(final Order order) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
getConnection().saveOrder(order);
mHandler.sendEmptyMessage(0);
}
catch (Exception exc) {
Log.d("--- ERROR ---", exc.getMessage());
handleException(exc.getMessage());
}
}
});
thread.start();
}
public Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
handleSuccessSaveOrder();
}
};
private void handleSuccessSaveOrder() {
showAlert(Farsi.Convert(" j "),R.drawable.warning);
}
private void showAlert(String message, int iconId) {
alert = new AlertDialog.Builder(ReviewOrderActivity.this);
alert.setTitle("Status Dialog");
alert.setMessage(message);
alert.setIcon(iconId);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
showActivity(MainMenuActivity.class);
}
});
alert.show();
}
"Can't create handler inside thread that has not called Looper.prepare()" is due to:
Cannot display the Alert dialog in UI thread while running the process in the background thread.
So, place the alert dialog in UI thread in your handleSuccessSaveOrder() as below:
this.runOnUiThread(new Runnable() {
public void run() {
showAlert(Farsi.Convert(" j "),R.drawable.warning);
}
});
I need to do some validations sequentially and some of them involve complex database operations.
So, I need to do this in a separated thread of UI Thread, ok?
But some validations show messages to user, what need confirmation and
when user confirm, the next validation should be call.
This code example explains what I want to implement:
void makeValidation1(){
if(condition1Valid()){
makeValidation2();
}else{
DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
makeValidation2();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("really want to do this?")
.setPositiveButton("Yes", onClick);
builder.create().show();
}
}
void makeValidation2(){
if(condition2Valid()){
}else{
//...
}
}
boolean condition1Valid() {
// complex database Operations
return false;
}
boolean condition2Valid() {
//complex database Operations
return false;
}
//...
void makeValidation9(){
//...
}
My question is: What the best way/pattern to implement this?
1 - Create one asyncTask for each validation? (I cant create only one AsyncTask, because confirmation messages can stop flux).
2 - Create a Runnable for each validation and create thread to run that when need call next validation?
3 - ???
edit
I tested this code #BinaryBazooka, but isnt work. Any help?
public class MainActivity extends Activity implements OnClickListener {
Thread mThread;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
validations();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
mThread.run();
}
});
builder.create().show();
}
void validations(){
//this method go on separated thread
validation1();
validation2();
validation3();
}
void validation1(){
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
//wait for user confirmation
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
Log.i("TAG", "<<<<<<<<<< >>>>>>>>>>>>");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT);
}
});
}
}
I would create a new thread and sleep it during these dialog calls, you can access the UI directly from within your runnable with..
runOnUiThread(new Runnable() {
public void run() {}
});
So something like..
Thread someThread = new Thread(new Runnable() {
#Override
public void run(){
runOnUiThread(new Runnable() {
public void run()
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.msg);
builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
someThread.notify();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
someThread.wait();
Works with AsyncTask. Ty.
Code:
public class MainActivity extends Activity implements OnClickListener {
//Thread mThread;
ProgressDialog mProgressDialog;
private ValidationsAsyncTask async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
async = new ValidationsAsyncTask();
async.execute();
}
});
builder.create().show();
}
void validation1(){
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
Log.i("TAG - validation1", Thread.currentThread().getName());
try {
synchronized (async) {
//wait for user confirmation
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (async) {
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
});
}
class ValidationsAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
validation1();
validation2();
validation3();
return null;
}
#Override
protected void onCancelled() {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_LONG).show();
}
}
}