Android Show dialog when Runnable with Progress Dialog finishes - android

I have a Fragment. When the Fragment is created I want to show a Progress Dialog for 3 seconds, then dismiss it and show a pop up dialog. I attach below my code.
From the onCreate() of my Fragment:
final ProgressDialog myPd_ring=ProgressDialog.show(context, "Please wait", "text..", true);
myPd_ring.setCancelable(false);
new Thread(new Runnable() {
#Override
public void run() {
try
{
Thread.sleep(3000);
} catch(Exception e)
{
}
myPd_ring.dismiss();
}
}).start();
showPopup(0, 8, 1, "Next photo");
And my popup method:
public void showPopup(final int type, int photoNo, int currPhoto, String message) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup_erroare);
dialog.setCancelable(false);
TextView textHeader;
TextView textContent;
textHeader = (TextView) dialog.findViewById(R.id.text_titlu);
textContent = (TextView) dialog.findViewById(R.id.text_error);
textHeader.setText("Procedura fotografiere");
textContent.setText("Poza nr. " + currPhoto+ " of" + noPhoto+
". " + message);
if (type == 0) {
}
Button btn_nu = (Button) dialog.findViewById(R.id.button_nu);
if (type == 0) {
btn_nu.setText("NU");
}
btn_nu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_nu.setVisibility(View.GONE);
Button btn_da = (Button) dialog.findViewById(R.id.button_da);
btn_da.setText("Fotografiere");
btn_da.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type == 0) {
captureImage();
}
dialog.dismiss();
}
});
dialog.show();
}
The problem is that my ProgressDialog doesn't appear, the popup appears directly. If I put my pop up invoking method in the new Thread() body I get an error. It seems that you can invoke a dialog from a Runnable.

you can use the below code:
final ProgressDialog myPd_ring=ProgressDialog.show(context, "Please wait",
"text..", true);
myPd_ring.setCancelable(false);
myPd_ring.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
myPd_ring.dismiss();
showPopup(0, 8, 1, "Next photo");
}
}, 3000);
If you have any query please let me know.

Never use sleep() in final APP.
try this way, new a Runnable(), and call postDelay(runnable, delayTimes) on a Handle.

Android Handler has a handy method postDelay() that does what you need, for example:
final ProgressDialog myPd_ring=ProgressDialog.show(context, "Please wait", "text..", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
myPd_ring.dismiss();
// show popup
}
}, 3000);
In Android, all View related tasks must be executed in the main thread, doing it in other threads will result in error. If you want to do in inside a background task for example, you'll need to use myactivity.runOnUiThread()
runOnUiThread(new Runnable() {
#Override
public void run() {
// show my popup
}
});

Related

Android: TextView visibility changes

I have started with android programming and I am trying to do:
Let the user enter their login credential.
If the user login credential is valid let them login.
If login credential is invalid then give them an error message saying that the user name or password entered is invalid.
For the last part, the problem is that I have a TextView with default hidden visibility. I want to make it visible for a few seconds and make it disappear.
This post and this post have helped but they are essentially trying to do the opposite.
My code is given below:
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Check the validity of the user name.
if (valid) {
// Let the user log in.
} else {
// Make TextView visible for a few seconds.
}
}
});
How do I go about this?
In your case first you need to show TextView then make it INVISIBLE .
Use textView.postDelayed method as:
if(valid){ //let the user login }
else
{
// make TextView visible here
textView.setVisibility(View.VISIBLE);
//use postDelayed to hide TextView
textView.postDelayed(new Runnable() {
public void run() {
textView.setVisibility(View.INVISIBLE);
}
}, 3000);
//how to make the textview visible for a few seconds
}
To show any information or error message you can use small pop-up message for some time. Following the code and image for toast.
//display in short period of time
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
You can use toast.
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Toasts in android
try this
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mTextView.setVisibility(View.VISIBLE);
v.postDelayed(new Runnable() {
#Override
public void run() {
mTextView.setVisibility(View.GONE);
}
}, 2000);
}
});
you can achieve this with the help of timertask,as your textview is invisible first make it visible and then with the help of timertask make it invisible again
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//check the validity of the user name
if(valid)
{
//let the user login
}
else
{
txt.setVisibility(View.VISIBLE);
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
txt.setVisibility(View.INVISIBLE);
}
});
}
}, 5000);
}
});
but i would suggest if you want user confirmation show error in alertdialog or a toast to show error would be fine
You can do this by using handler.
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//check the validity of the user name
if(valid)
{
//let the user login
}
else
{
//how to make the textview visible for a few seconds
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
mTextView.setVisibility(View.VISIBLE);
}
}, 1000/* 1sec delay */);
}
});

EditText Value in Android

I have a custom dialog with me. In which an editText id there, I am reading input through editText, putting the input to a string. This code is followed by a thread (sub) to handle one url. I want to use this string in the thread mentioned. But the thread is getting invoked before I type to the editText. How can i dynamically use the same text from the userinput inside the thread? Thanks in advance..
public void onClick(View v)
{
switch (v.getId())
{
case R.id.i1:
MyDevice.getInstance().currentUserImageId=R.drawable.jerry1;
MyDevice.getInstance().userName="You";
MyDevice.getInstance().facebook=0;
this.finish();
break;
case R.id.i2:
MyDevice.getInstance().currentUserImageId=R.drawable.chaplin1;
MyDevice.getInstance().userName="You";
MyDevice.getInstance().facebook=0;
this.finish();
break;
case R.id.i3:
MyDevice.getInstance().currentUserImageId=R.drawable.budy;
MyDevice.getInstance().userName="You";
MyDevice.getInstance().facebook=0;
this.finish();
break;
case R.id.facebook:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.usernamefbdialog);
dialog.setTitle("Enter Facebook Username");
Button dialogButton = (Button) dialog.findViewById(R.id.done);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
EditText edit=(EditText)dialog.findViewById(R.id.username);
text=edit.getText().toString();
dialog.dismiss();
}
});
dialog.show();
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
MyDevice.getInstance().bitmap=getUserPic(text);
MyDevice.getInstance().facebook=1;
ImageView facebookImg=(ImageView) findViewById(R.id.facebookimg);
facebookImg.setImageBitmap(MyDevice.getInstance().bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
break;
}
}
Basically what you want to do is run the Thread from within the button click event, that way it runs after you get the text. See your modified code below.
The events that happen to the String occur in this order.
1. Create the String
2. Set the String equal to the edit text String
3. Start the Thread and use the String
final String theStringYouWantToUseInTheThread = null;
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
//use theStringYouWantToUseInTheThread here
MyDevice.getInstance().bitmap=getUserPic(text);
MyDevice.getInstance().facebook=1;
ImageView facebookImg=(ImageView) findViewById(R.id.facebookimg);
facebookImg.setImageBitmap(MyDevice.getInstance().bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
EditText edit=(EditText)dialog.findViewById(R.id.username);
theStringYouWantToUseInTheThread = edit.getText().toString();
thread.start();
dialog.dismiss();
}
});
dialog.show();
thread.start();
I'm not exactly sure if I understand but this sentence "How can i dynamically use the same text from the userinput inside the thread?"sounds like you want to implement a TextWatcher on your EditText
public class TempWatcher implements TextWatcher {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// you can update something here
}
}
But if you check for a valid value in your EditText when clicking the Button and only start your Thread then, it should do what you want. If this doesn't work then please clarify your problem and show where you start the Thread and how it is implemented

Return a value from Popup Window

I have popup window class like the following.
public class Popup extends PopupWindow {
Context context;
EditText et_bankname, et_banknumber;
String bank_name, account_number;
public Popup(Context ctx) {
super(ctx);
context = ctx;
setContentView(LayoutInflater.from(context).inflate(R.layout.bank_details, null));
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
View popupView = getContentView();
setFocusable(true);
Button btn_close = (Button) popupView.findViewById(R.id.popupClose);
Button btn_submit = (Button) popupView.findViewById(R.id.popupSave);
et_bankname = (EditText) popupView.findViewById(R.id.bank_name);
et_banknumber = (EditText) popupView.findViewById(R.id.bankacc_no);
btn_submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bank_name = et_bankname.getText().toString();
account_number = et_banknumber.getText().toString();
if (!bank_name.equals("") && !account_number.equals("")) {
Toast t1 = Toast.makeText(context,bank_name + " "+account_number , Toast.LENGTH_SHORT);
t1.setGravity(Gravity.TOP, 0, 100);
t1.show();
dismiss();
} else {
Toast t1 = Toast.makeText(context,
"Please provide valid details", Toast.LENGTH_SHORT);
t1.setGravity(Gravity.TOP, 0, 100);
t1.show();
}
}
});
}
public void show(View v) {
showAtLocation(v, Gravity.CENTER, 0, 0);
}
}
I will access this popup in my activity by
Popup popup = new Popup(getBaseContext());
popup.show(arg1);
This works perfectly. But I want to know when this popup window gets dismissed. for this purpose now I am using Thread concept like following.
if (isPopupShowing) {
Thread thread = new Thread() {
#Override
public void run() {
while (isPopupShowing) {
if (!popup.isShowing()) {
isPopupShowing = false;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
loadDSP(type);
}
});
}
}
}
};
thread.start();
}
But this thread will run continuesly until the popup window gets dismissed. So I feel it is better to replace this solution by any other way.
What I want?
Just intimate to my activity like "popup is closed" when popup is dismissed.
Why I am use this way?
I will use this popup window in three activty. That is why I am create a separate class for popup window.
Any help will be highly appriciated.
Thank you.
PopupWindow already has its own dismiss listener, just use it as follows
Popup popup = new Popup(getBaseContext());
popup.show(arg1);
Change that to
Popup popup = new Popup(getBaseContext());
popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
// Do your action
}
});
popup.show(arg1);
EDIT
I hadn't noticed you were extending a PopupWindow, which already has this implemented as shown in #Jayabal's answer. Anyway this is how you would do it if the PopupWindow didn't already have it's own onDismissListener.
Simply create your own OnDismissListener Interface.
public interface onDismissListener{
public void onDismiss();
}
Add a reference to a Listener in the PopUp class and a setter.
OnDismissListener listener;
public void setOnDismissListener(OnDismissListener listener){
this.listener = listener;
}
Then in your Activity
Popup popup = new Popup(getBaseContext());
popup.setOnDismissListener(new OnDismissListener(){
public void onDismiss(){
//do what you need to here
}
});
popup.show(arg1);
This pattern should be familiar to you, its used everywhere in Android.

Change onClickListener dynamically in handleMessage depending on Message

I have an Activity with Android.os.Handler, which is used for communication with an openGL thread.
I want to get messages from the opengl thread and draw some GUI in the activity depending on the message data, so I do:
Handler handle = new Handler(new Handler.Callback(){
public boolean handleMessage(Message msg){
// update GUI like
TextView v1 = (TextView) GamescreenActivity .this.findViewById(R.id.mytextview)
// then what I actually would like to do but it does not work:
Button b = (Button) GamescreenActivity.this.findViewById(R.id.mybutton);
b.setOnClickListener(null);
if (msg.what == MY_OWN_CONSTANT) {
b.setOnClickListener(getOnClickDoSomething(msg));
}
}
View.OnClickListener getOnClickDoSomething(final Message msg) {
return new View.OnClickListener() {
public void onClick(View v) {
makeDialog(msg);
}
};
}
private void makeDialog(Message msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(GamescreenActivity.this);
builder.setMessage("yo")
.setTitle(""+ msg.what);
AlertDialog dialog = builder.create();
dialog.show();
}
I hope it is clear what i'm trying to achieve. What I get by now is msg being null in the makeDialog methode almost all the time.
What I get by now is msg being null in the makeDialog methode almost all the time.
I believe the Message has already been recycled when this happens. Let's create a local copy of msg and modify your code a little to make it more efficient. First create a new field variable:
Message message;
Next change your if-else block:
if (msg.what == MY_OWN_CONSTANT) {
message = Message.obtain(msg);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(GamescreenActivity.this);
builder.setMessage("yo")
.setTitle(""+ message.what)
.show();
message.recycle(); // Recycle our message when we're done
}
});
}
else {
b.setOnClickListener(null);
}

android can't close dialog when run socket

I have some problem. Dialog.dismiss() does not work.
I want to input ip, username, password to login WinServer 2003. When I clicked Submit button, the dialog can't be closed. To be noted, my Thread-socket able to retrieve messages from Server and send messages back to Server. The Dialog can only be closed When the Thread-socket got error.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jiemian);
netInit();
JieMianActivity.jiemian = this;
LayoutInflater factory = LayoutInflater.from(JieMianActivity.this);
View view = factory.inflate(R.layout.login, null);
dialog02 = new AlertDialog.Builder(JieMianActivity.this)
.setIcon(android.R.drawable.btn_star)
.setTitle("login")
.setView(view)
.setPositiveButton("submit", onclickButton)
.setNegativeButton("cancel", onclickButton).create();
dialog02.show();
}
private OnClickListener onclickButton = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v("which", which+"");
switch(which){
case Dialog.BUTTON_POSITIVE:
dialog.dismiss();//doesn't work , cann't close dialog.
EditText ip = (EditText) findViewById(R.id.ip);
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
new Connect(JieMianActivity.jiemian).run();//do some socket thing
break;
case Dialog.BUTTON_NEGATIVE:
dialog.dismiss();
JieMianActivity.jiemian.finish();
break;
}
}
};
This is my Thread:
class Connect extends Thread{
private JieMianActivity jiemain;
public Connect(JieMianActivity jiemian){
this.jiemain = jiemian;
}
public void run(){
//Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
try {
Display display = getWindowManager().getDefaultDisplay();
InputStream is = getResources().getAssets().open(
connect2RDP.mapFile);
sfv = (SurfaceView) findViewById(R.id.surfaceView);
sfh = sfv.getHolder();
sfh.addCallback(JieMianActivity.jiemian);
if (conn.connect("192.168.10.134", "Adminstrator", "123",
display.getWidth(), display.getHeight(), 3389, is)) {
Log.v("login", "success");
//dialog02.dismiss();
Log.v("login", "ok");
canvas = new MyCanvas();
canvas.setRop(new RasterOp());
canvas.setHeight(Options.height);
canvas.setWidth(Options.width);
canvas.setRight(Options.width - 1);
canvas.setBottom(Options.height - 1);
canvas.setBackstore(new WrappedImage(Options.width,
Options.height, JieMianActivity.jiemian));
canvas.setJiemian(JieMianActivity.jiemian);
canvas.setSurView(sfv);
canvas.setSurHolder(sfh);
conn.doconnect(JieMianActivity.jiemian);// 启动RDP
// init();
}
} catch (OrderException e) {
} catch (Exception e) {
}
}
};
You need to change your code to start a Thread, You need to call the method start() - that will execute the run() method written in that Thread.
So,
Invoke Connect.start() instead of Connect.run() inside your onClick handler.
I think you should close your alert dialog in UI thread else it wont work. You can do this in two ways : 1. Use message handler 2. Use RunOnUiThread. Sample for your reference :
1.
messageHandler.sendEmptyMessageDelayed(unique_id, 500);
private Handler messageHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case unique_id:
// do here
break;
}
}
};
2.
Runnable hide_ui = new Runnable() {
#Override
public void run() {
// do here
}
};
runOnUiThread(hide_ui);

Categories

Resources