I am making a simple app to download video from a website using volley.
So when i opened my app for first time everything was fine but when i opened app second time after closing app with back button , then i got a error or warning.
Now i can't use alertDialogs ( process dialogs are working fine) because of it ( app crashed if i did)
i am using singleton class AlertUser for AlertDialogs
public class AlertUser {
private static final AlertUser AlertUserInstance = new AlertUser();
private Context ActivityContext = null;
private AlertUser() { }
public static AlertUser getInstance() {
return AlertUserInstance;
}
public void init(Context ctx) {
if (ActivityContext == null)
ActivityContext = ctx;
}
public void alertUser(String msg) {
if (!((AppCompatActivity)ActivityContext).isFinishing()) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityContext);
alertDialogBuilder.setTitle(R.string.app_name);
alertDialogBuilder.setMessage(msg);
alertDialogBuilder.setPositiveButton("Got it!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
Here is some code from MainActivity
public class MainActivity extends AppCompatActivity {
private RequestQueue queue;
private AlertUser alert = AlertUser.getInstance();
ProgressDialog progressDialog;
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
Log.d("Main","onCreate");
alert.init(MainActivity.this);
queue = new Volley().newRequestQueue(MainActivity.this);
}
}
Edit : Now i am using System.exit(0) and now it's working in every run after being killed but i don't think its good solution and still i am unaware from exact problem.
Related
I made a custom dialog (extends DialogFragment) that appears in several activities.
If the activity comes to foreground while the dialog is opened, I get the following error:
FATAL EXCEPTION: main
Process: package.name, PID: 11137
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = myFragmentOrActivityWhereOccuredTheError)
...
Caused by: java.io.NotSerializableException: android.support.v7.widget.AppCompatButton
Depends on the activity or fragment, "Caused by" changes, because the problem is not there, is the DialogFragment (without showing the dialog fragments everything works)
There is a solution: calling dismiss() before the activity goes to foreground. But I have to write a lot of code because I have to show it again in case the dialog was opened before the activity came to foreground and also is not simple to handle that with the complexity of the activies.
What I need: Solve the problem without dismissing the dialog. I think I have an error on my DialogFragment Class. So... this is the code of my class:
public class RequestDialog extends DialogFragment {
public static String DIALOG_INTERFACE = "dialogInterface";
public static String REQUIERE_ACTIVACION_MANUAL = "activationMode";
public static String SCHEME = "package";
public interface MyDialogInterface extends Serializable {
void onClickContinuarEvent(int permisoRequerido);
void onClickCancelarEvent(int permisoRequerido);
}
private MyDialogInterface callbackListener;
/**
* dialogInterface - instance of MyDialogInterface which will handle
* callback events
*/
public static RequestDialog getInstance(MyDialogInterface dialogInterface, boolean activationMode) {
RequestDialog fragmentDialog = new RequestDialog();
// set fragment arguments
Bundle args = new Bundle();
args.putSerializable(DIALOG_INTERFACE, dialogInterface);
args.putBoolean(REQUIERE_ACTIVACION_MANUAL, activationMode);
fragmentDialog.setArguments(args);
return fragmentDialog;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle extras = getArguments();
callbackListener = (MyDialogInterface) extras.getSerializable(DIALOG_INTERFACE);
final boolean activationMode = extras.getBoolean(REQUIERE_ACTIVACION_MANUAL);
View view = View.inflate(getActivity(), R.layout.rationale_dialog, null);
TextView texDetalle = view.findViewById(R.id.texDetalle);
TextView texContinuar = view.findViewById(R.id.texContinuar);
TextView texCancelar = view.findViewById(R.id.texCancelar);
ImageView imgCabecera = view.findViewById(R.id.imgCabecera);
imgCabecera.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.ic_folder));
Typeface typeFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/MyFont.ttf");
texDetalle.setTypeface(typeFace);
final AlertDialog.Builder requestDialogBuilder = new AlertDialog.Builder(getActivity(), R.style.NarrowDialog);
requestDialogBuilder.setView(view);
final AlertDialog dialog = requestDialogBuilder.create();
dialog.setContentView(view);
final Window window = dialog.getWindow();
if(window != null){
window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
dialog.getWindow().setLayout(size.x*70/100, WindowManager.LayoutParams.WRAP_CONTENT);
texContinuar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(activationMode){
goToPreferencesSystem();
callbackListener.onClickCancelarEvent(1);
}
else{
callbackListener.onClickContinuarEvent(0);
}
dialog.dismiss();
}
});
texCancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callbackListener.onClickCancelarEvent(2);
dialog.dismiss();
}
});
}
setCancelable(false);
return dialog;
}
}
As you can see, there is two callback that I have to handle in the activies.
So... Do you have any idea hoy to solve this problem?
Thanks!
EDIT:
In any activity I have to implement the dialog like this:
MyActivity implements RequestDialog.MyDialogInterface
And then override the callbacks:
#Override
public void onClickContinuarEvent(int request) {
}
#Override
public void onClickCancelarEvent(int permisoRequerido) {}
You really should not be making anything Serializable that should die when the lifecycle of a fragment/activity die. For this solution, remove the interface on the getInstance(). You should not pass interfaces via fragment creation. You should create a setter for the interface. I don't have nearly enough information to solve the issue but, I believe this may be the solution. Let me know if it works, so I can delete if it it doesn't.
Dialog
public class RequestDialog extends DialogFragment {
private MyDialogInterface callbackListener;
public interface MyDialogInterface {
void onClickContinuarEvent(int permisoRequerido);
void onClickCancelarEvent(int permisoRequerido);
}
public void setCallbackListener(MyDialogInterface callbackListener) {
this.callbackListener = callbackListener;
}
public static RequestDialog getInstance( boolean activationMode) {
RequestDialog fragmentDialog = new RequestDialog();
Bundle args = new Bundle();
args.putBoolean(REQUIERE_ACTIVACION_MANUAL, activationMode);
fragmentDialog.setArguments(args);
return fragmentDialog;
}
}
Create Dialog
RequestDialog requestDialog = RequestDialog.getInstance(true);
requestDialog.setCallbackListener(new RequestDialog.MyDialogInterface() {
#Override
public void onClickContinuarEvent(int permisoRequerido) {
}
#Override
public void onClickCancelarEvent(int permisoRequerido) {
}
});
requestDialog.show(getSupportFragmentManager(), "REQUEST_DIALOG");
Hello and thank you for taking the time to read this question.
I am trying to write an instrumentation test for an activity. The scenario is the following:
If on create of the activity the GPS is not enabled, an alertDialog should be shown to the user to suggest turning on the sensor. The check is performed by an utility class that checks the connectivity and shows the alertDialog if necessary. I want to be able to test in my class if the dialog is shown to the user.
Now for some code:
The activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Utils.checkGPSProvider(this);
}
The Utility class:
public final class Utils {
private Utils() {
}
private static void createAlertDialog(final Context context, final String message, final String intentAction) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
final Intent callSettingIntent = new Intent(intentAction);
alertDialogBuilder.setMessage(message).setPositiveButton(POSITIVE_BUTTON,
new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int id) {
context.startActivity(callSettingIntent);
}
});
alertDialogBuilder.setNegativeButton(NEGATIVE_BUTTON, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public static void checkGPSProvider(final Context context) {
String message;
message = "GPS message";
final LocationManager mlocManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createAlertDialog(context, message, android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
}
}
}
The test class:
public class UtilsTest extends ActivityInstrumentationTestCase2<MyActivity> {
private MyActivity activity;
#Mock
LocationManager mlocManager;
public UtilsTest() {
super(MyActivity.class);
}
public UtilsTest(Class<MyActivity> activityClass) {
super(activityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
activity = getActivity();
MockitoAnnotations.initMocks(this);
}
public void testWhenGPSIsDisabled_ShouldShowAlertDialog() {
when(mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(false);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Assert.fail("GPS should be disabled");
}
(insert code here that should test that the alertDialog is shown)
}
}
I know that the Dialog class has an isShown() method but I do not know how to get the dialog reference to test the isShown method.
If there is any other necessary information I will try to provide it to you.
Thank you.
You can return the reference of the AlertDialog from the method createAlertDialog
example:
private static AlertDialog createAlertDialog(final Context context, final String message, final String intentAction)
When you call this method you can then get the return reference value of the method same as your checkGPSProvider should also return AlertDialog.
sample:
public static AlertDialog checkGPSProvider(final Context context) {
String message;
message = "GPS message";
final LocationManager mlocManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return createAlertDialog(context, message, android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
}
}
And in your oncreate method of the activity create a Field for AlertDialog and instantiate with the Utils.checkGPSProvider(this);
solution:
your_alert_dialog = Utils.checkGPSProvider(this);
I want to show an Alert Dialog via AlertDialogManager class to a non-activity class DeviceAdminReceiverSample's method onDisabled, but whenever I call alertDialog via that method it generates error with following text
Error
06-12 12:01:19.923: E/AndroidRuntime(468): FATAL EXCEPTION: main
06-12 12:01:19.923: E/AndroidRuntime(468): java.lang.RuntimeException: Unable to start
receiver com.android.remotewipedata.DeviceAdminReceiverSample:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not
for an application
I know the issue is with context thing but I don't know what to put there so that it work, I tried this, getApplicationContext() but all vain. My code for both classes is below
AlertDialogManager
public class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
if (status != null)
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
}
DeviceAdminReceiverSample
public class DeviceAdminReceiverSample extends DeviceAdminReceiver {
static final String TAG = "DeviceAdminReceiver";
AlertDialogManager alert = new AlertDialogManager();
/** Called when this application is no longer the device administrator. */
#Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
Toast.makeText(context, R.string.device_admin_disabled,
Toast.LENGTH_LONG).show();
// intent.putExtra("dialogMessage", "Device admin has been disabled");
// intent.setClass(context, DialogActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
alert.showAlertDialog(context, "Alert",
"Device admin has been disabled", true);
}
Just add this before your alertDialog.show();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
or try following if above didn't work:
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
and use this permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
The problem is 'You can show AlertDialogs from Activity only'. This is not an issue of context.
Although this is not a good idea to show dialog from receiver (better is to use Notification), But if you want to do so you can create an Activity as dialog and show
If you always want to get the current activity from anywhere in the app you can register an ActivityLifecycleCallback on your Application instance.
Here's an untested implementation that might get you closer.
public class TestApp extends Application {
private WeakReference<Activity> mActivity = null;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mActivity = new WeakReference<Activity>(activity);
}
#Override
public void onActivityDestroyed(Activity activity) {
mActivity.clear();
}
/** Unused implementation **/
#Override
public void onActivityStarted(Activity activity) {}
#Override
public void onActivityResumed(Activity activity) {}
#Override
public void onActivityPaused(Activity activity) {}
#Override
public void onActivityStopped(Activity activity) {}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
});
}
public Activity getCurrentActivity() {
return mActivity.get();
}
}
Then to use this throughout your app you would do some call like this ...
Activity activity = ((TestApp)getApplicationContext()).getCurrentActivity();
The advantages are you can always keep track of your current activity, however its a little too overkill for just handling Dialogs from within the Activity.
call this method in activity class
public static void showAlert(Activity activity, String message) {
TextView title = new TextView(activity);
title.setText("Title");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// builder.setTitle("Title");
builder.setCustomTitle(title);
// builder.setIcon(R.drawable.alert_36);
builder.setMessage(message);
builder.setCancelable(false);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Here's what I made and use:
myDialog.java:
import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
public class myDialog {
private Activity mActivity;
myDialog(Activity a) {
this.mActivity = a;
}
#SuppressWarnings("InflateParams")
public void build(String title, String msg) {
LayoutInflater inflater = LayoutInflater.from(mActivity);
View subView = inflater.inflate(R.layout.dialog_box_text, null);
final TextView message = subView.findViewById(R.id.message);
message.setText(msg);
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(title);
builder.setView(subView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
dialog_box_text.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:orientation="horizontal">
<TextView
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" "
android:maxLines="1"
android:textColor="#color/colorBlack" />
</LinearLayout>
Example code:
public class MainActivity extends AppCompatActivity {
private myDialog md;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
md = new myDialog(this);
...
md.build("Title", "Message");
You can define a public Context var in the MainActivity with initial value (this); As show here:
public class MainActivity< alertdail > extends AppCompatActivity {
////////////////////////////////////////////////////////////
//Public var refers to Main Activity:
Context mainActivity = this;
////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
AlertDialogManager alert =new AlertDialogManager ();
alert.showAlertDialog ( this,"Title","Message",true );
}
public class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
final AlertDialog alertDialog = new AlertDialog.Builder ( mainActivity ).create ( );
alertDialog.setTitle ( title );
alertDialog.setMessage ( message );
if (status != null)
alertDialog.setButton ( "OK", new DialogInterface.OnClickListener ( ) {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss ( );
}
} );
alertDialog.show ( );
}
public void showAlertDialog(Context c) {
}
}
public class DeviceAdminReceiverSample extends DeviceAdminReceiver {
static final String TAG = "DeviceAdminReceiver";
AlertDialogManager alert = new AlertDialogManager ( );
/**
* Called when this application is no longer the device administrator.
*/
#Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled ( context, intent );
Toast.makeText ( context, R.string.device_admin_disabled,
Toast.LENGTH_LONG ).show ( );
// intent.putExtra("dialogMessage", "Device admin has been disabled");
// intent.setClass(context, DialogActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
alert.showAlertDialog ( context, "Alert",
"Device admin has been disabled", true );
}
}
}
Here's a quick method of properly performing this task that has done the job for me. Basically, what you would do is just create a new thread.
Declare a public and static variable with a type that matches the original activity class.
public static Activity1 activity;
Activity1 is the class that the variable resides in.
Upon calling the method onCreate();, set the variable to be equal to the context of the activity, otherwise known as this.
Example:
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
activity = this;
}
3. Since we now have the context of the activity, we can use it to create a function with an alert dialog by using the runOnUiThread(); method inside of the function that will call the alert dialog. We would use a new Runnable() for the runnable action required for runOnUiThread();, and to have the alert dialog actually open, we would override the run function of a runnable item and place the code for the alert dialog in there.
Example function:
public static void exampleDialog(){
Activity1.activity.runOnUiThread(new Runnable){
#Override
public void run(){
//alert dialog code goes here. For the context, use the activity variable from Activity1.
}
}
}
Hope this helps :)
I have created simple application with login feature. I have created separate task for do the login into server called LoginTask and a listener class called LoginListener.
public interface LoginListener {
public void onLoginComplete();
public void onLoginFailure(String msg);
}
public class LoginTask extends AsyncTask<String, Void, Boolean>{
private final LoginListener listener;
private final Context c;
private String msg;
public LoginTask(final Context c, final LoginListener listener) {
this.c = c;
this.listener = listener;
}
#Override
protected Boolean doInBackground(String... args) {
// loging in to server
//return true if success
}
#Override
protected void onPostExecute(Boolean status) {
if(!status){
if(listener != null) listener.onLoginFailure(msg);
return;
}
// the problem is here, listener is null, because activity/fragment destroyed
if(listener != null) listener.onLoginComplete();
}
}
I executed LoginTask from LoginFragment. The LoginFragment implements LoginListener.
public class LoginFragment extends Fragment implements LoginListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.frg_login, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
doInitView();
};
private void doInitView(){
Button loginButton = (Button) getActivity().findViewById(R.id.login_btn);
Button regButton = (Button) getActivity().findViewById(R.id.toreg_btn);
ButtonListener listener = new ButtonListener();
loginButton.setOnClickListener(listener);
regButton.setOnClickListener(listener);
}
private void doLogin(){
Activity activity = getActivity();
EditText emailText = (EditText)activity.findViewById(R.id.login_email);
EditText pwdText = (EditText)activity.findViewById(R.id.login_pwd);
String email = emailText.getText().toString().trim();
String pwd = pwdText.getText().toString().trim();
if(StringUtil.isAnyNull(email, pwd)){
Popup.showMsg(getActivity(), "Silahkan lengkapi data", Popup.SHORT);
return;
}
savedEmail = email;
savedPwd = pwd;
String url = getActivity().getResources().getString(R.string.url_login);
Popup.showLoading(getActivity(), "Login", "Please wait...");
LoginTask task = new LoginTask(getActivity(), this);
task.execute(url, email, pwd);
}
private final class ButtonListener implements OnClickListener{
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.login_btn:
doLogin();
break;
case R.id.toreg_btn:
doToRegister();
break;
case R.id.demo_btn:
doDemo();
break;
}
}
}
#Override
public void onLoginComplete() {
// getActivity() is null
((MainActivity)getActivity()).gotoMain();
}
#Override
public void onLoginFailure(String msg) {
}
}
Because of the login task takes time, sometime the device light turn off before the task was finished so activity was destroyed. This caused the task failed to call the listener(fragment). How to solve this problem?
Thanks
AsyncTask should be used for tasks that take a bit longer and return a result into the current activity. However it's not intended for really long running tasks or for those cases where you want to evaluate its results even if the activity has been destroyed. You might consider using a Service here. In any case you shouldn't do updates in onPostExecute() anymore cause the activity context might be gone (see Doctoror Drive's post). Having that service in place, you can either send an Intent or a Broadcast event to the system. Then do the further processing in that intent activity / broadcast receiver.
You can cancel the asynctask in onDestroy() of your LoginActivity.
Override onCancelled() of the asynctask. When the activity is destroyed, a call to onCancelled() will be made instead of onPostExecute()
Here you can avoid a call back to the LoginActivity.
You should use Service or IntentService. because AsyncTask does not record any variables or context of Activity. When you finish login task launch PendingIntent or startActivity(intent). This can be best practice of Android. This way you never get exception.
In onLoginComplete and onLoginFailure check if the fragment is still attached to the activity. If not, do nothing.
#Override
public void onLoginComplete() {
if (isAdded() && !isRemoving() && !isDetached()) {
((MainActivity)getActivity()).gotoMain();
}
}
I have a problem with closing a custom dialog. I have two classes
class 1-> AndroidHTMLActivity
class 2-> CustomizeDialog
In my AndroidHTMLActivity I use java interface which is call from javascript, in this class i call CustomizeDialog
public class AndroidHTMLActivity extends Activity {
WebView myBrowser;
setContentView(R.layout.main);
myBrowser = (WebView)findViewById(R.id.mybrowser);
myBrowser.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/mypage.html");
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void openAndroidDialog(){
CustomizeDialog customizeDialog = new CustomizeDialog(mContext);
customizeDialog.show();
}
CustomizeDialog .java
public class CustomizeDialog extends Dialog {
Context ctx ;
public CustomizeDialog(Context context) {
super(context);
ctx = context;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
MyThread downloadThread = new MyThread();
downloadThread.start();
}
public class MyThread extends Thread {
#Override
public void run() {
try {
handler.post(new MyRunnable());
}
}
}
static public class MyRunnable implements Runnable {
public void run() {
// here i want to close this customized dialog
}
}
Here i can't use finish() method, I want to close the customized dialog box via the thread. Anyone has any idea about this?
Well I know this question is asked in the past and maybe already answered but haven't shared the correct answer but I still want to share this since I also got the same problem. Well here's what I did.
1st create the base class let say and create a static declaration for dialog.
public class Dialogs {
static Dialog dialog;
}
2nd is to put your custom dialog.
public void customDialog(Context context){
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_login);
dialog.setTitle(title);
//... other parts here
dialog.show();
}
then the dialog dismiss:
public static void dismissDialog(){
dialog.dismiss();
}
and on the other class to close the currect customDialog just call
Dialogs.dismissDialog();
That's it. :) Hope it helps.
close it with outside handler like this
App.HANDLER.post(new Runnable() {
#Override
public void run() {
dismiss();
cancel();
}
});
App is a application class