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
Related
I have a class which extends Activity.
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id,someactivitylayout);
new Game(getApplicationContext());
}
My Game class looks like
public class Game{
Game(final Context context){
cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* here i need to call runOnUIThread*/
}
}
}
My code does not have any syntax errors, so it compiles fine.
In the place where i have to call runOnUIThread, i have tried
Thread t = new Thread() {
public void run() {
while (progressBar.getProgress() < 100) {
((Activity) context).runOnUiThread(new unnable() {
public void run() {
}
});
}
};
t.start();
But when i try to cast context to Activity it gives an exception
java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
Why is it not possible to cast context to Activity??
I have tried many ways but did not find anyway to get Activity in my Game class.
Is there any way to do that??
You are sending ApplicationContext to the Game class. Just replace the getApplicationContext() with this to pass the Activity Context. It will work.
It should be new Game(this)
try with
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id,someactivitylayout);
new Game(this);
}
}
I am creating an android application with custom OnClickListener that's defined in it's own class.
The problem is when I want to create Indeterminate Progress Bar in title bar that will be started when the onClick method will be called.
I can't setProgressBarIntederminateVisibility from MyOnClickListener class because it's not the main activity, and I can't request getParent because it's not a activity.
public class MyOnClickListener implements OnClickListener {
private message;
public MyOnClickListener(Context context,TextView mstatus, TextView message) {
this.message=message;
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.next:
this.message.setText(GetValue.getNextValue());//during this operation I want progress bar to be spinning
Log.v("MyOnClickListener", "next pressed");
break;
case R.id.prev:
this.message.setText(GetValue.getPrevValue());
Log.v("MyOnClickListener","prev pressed");
break;
case R.id.last:
this.message.setText(GetValue.getlastvalue());
break;
default: break;
}
}
}
What Can I do?
Typically, you'd have this as an inner class of your Activity, which then has an implicit reference to your "outer" Activity class. As an alternative, you can of course pass a reference to your Activity when you construct your listener object.
In case it helps someone else, I have an activity that calls a non-activity class which downloads an xml data file from a server. I wanted to show a progress indicator. I did it like this (this isn't a complete implementation of the classes but should give a good idea):
/*Setup Activity Class */
public class MySetup extends Activity implements ThreadCompleteListener{
Button btnLogin, btnItems, btnConfig, btnStart;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_activity);
//set up links to buttons, etc
}
public void onBtnClicked(View v){
Intent intent;
switch(v.getId()){
case R.id.btn_download_items:
final Context ctx = this;
startProgressIndicator();
//async read a list of items from a server
myList=ItemsList.getItemsListInstance(ctx);
btnConfig.setEnabled(true);
break;
//other options here
}
}
public void startProgressIndicator(){
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading items...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
public void endProgressIndicator(){
pDialog.dismiss();
}
}
Then in my non-activity class - I do the download
public class ItemsList implements ThreadCompleteListener{
//create a list of MyItem
private ArrayList<MyItem> items = new ArrayList<MyItem>();
//create a single static instance
private static ItemsList itemsListInstance;
String baseUrl; //to connect to webservice
Context ctx;
public ItemsList(Context context){
readJSONFeed("http://someurl/", context);
ctx=context;
}
public void readJSONFeed(String theURL, Context context) {
//Read JSON string from URL
final Context ctx = context;
setBaseUrl();
//NotifyThread is a class I found in a Stack Overflow answer
//that provides a simple notification when the async process has completed
NotifyThread getItemsThread = new NotifyThread(){
#Override
public void doRun(){
try {
//do the JSON read stuff here...
}catch (Exception e) {
}
};
getItemsThread.addListener(this);
getItemsThread.start();
}
//Overload the NotifyThread method
public void notifyOfThreadComplete(final Thread thread){
//CALL the method in the calling activity to stop the progress indicator
((MySetup)ctx).endProgressIndicator();
}
public static AuctionItemsList getItemsListInstance(Context context) {
if (itemsListInstance == null){
itemsListInstance = new itemsList(context);
}
return itemsListInstance;
}
}
I have an activity that roughly follows this structure:
public class myActivity extends Activity implements myCallback{
//Code
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
new myAsyncTask(myActivity.this).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(context,"Hello",Toast.LENGTH_SHORT).show();
}
}
And myAsyncTask has the myCallback() interface defined and it calls it eventually. No matter what I do, whatever UI element I try to show, be it a Toast or a ProgressDialog, it won't show. Nor do I get any exceptions. The rest of the callback code gets perfectly executed. Why is this?
Try using:
public class myActivity extends Activity implements myCallback{
//Code
Context mContext;
#Override
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
mContext = this;
new myAsyncTask(getApplicationContext()).execute();
}
public void myCallback(Context context){
//Code
Toast.makeText(mContext,"Hello",Toast.LENGTH_SHORT).show();
}
}
Instead of using context , use getApplicationContext... i hope it will show toast... like this
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
During onCreate(), I'm downloading resources from the web, which takes time. I'd like to display a message on the screen to advise the user. I tried toast, but nothing shows up. Is there another way to print something to the screen?
i think onCreate() work like a constructor for a class and you can not load any visual when it is not finished yet.
so i advice you to use another activity with your message and then call your activity in it.
You have to create a splash screen , that's the way it's called.
It's a mediator Activity that is handling such actions.
Example:
public class SplashScreen extends BaseActivity {
public ProgressDialog ProgressBar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HideTitle();
setContentView(R.layout.splash);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (!IsConnected()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 4000);
} else {
ProgressBar = ProgressDialog.show(this, "", "Loading...", false, false);
SplashScreenDelay splashScreenDelay = new SplashScreenDelay(this, this);
splashScreenDelay.execute(10);
}
}
here is the class that does the loading and after that sends to the main
public class SplashScreenDelay extends AsyncTask<Integer, Integer, List<RssItem>> {
private Context _context;
private SplashScreen _activity;
public SplashScreenDelay(SplashScreen activity, Context context) {
_context = context;
_activity = activity;
}
#Override
protected List<RssItem> doInBackground(Integer... params) {
return RssParsingService.getListOfItems();
}
#Override
protected void onPostExecute(List<RssItem> result) {
Intent intent = new Intent(_context, Viewport.class);
_context.startActivity(intent);
if (_activity.ProgressBar != null) {
_activity.ProgressBar.dismiss();
}
}
}
I'm working on a little program, and I need to add a custom dialog that passes some info to the calling acitivity when it closes.
I extended the dialog class, and when I try to capture the custom dialog when it closes,using an onDismiss listener, it never reaches it because I used a custom dialog.
This is part of my activity -
.
.
.
attributes customizeDialog = new attributes(con,position,pick.getLastVisiblePosition());
customizeDialog.show();
(The attributes being the name of the class that extends the dialog class).
Here is the event listener I set up when the dialog finishes -
customizeDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Log.v("LOG_CAT",attributes.selectedIndexes.get(0) + " " + attributes.selectedIndexes.get(1) + " " + attributes.selectedIndexes.get(2) + " " + attributes.selectedIndexes.get(3) + " " + attributes.selectedIndexes.get(5) + " ");
}
});
I know i'm doing it wrong,I just don't know how to fix it.
I would really appreciate any help with this problem.
Thanks!
I tend to have my activity implement listeners like this...
public class MyActivity extends Activity
implements DialogInterface.OnDismissListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
attributes customizeDialog = new attributes(con,position,pick.getLastVisiblePosition());
customizeDialog.setOnDismissListener(this);
customizeDialog.show();
}
#Override
public void onDismiss(DialogInterface dialog) {
// Do whatever
}
}
You could have your calling activity implement a custom listener interface that is called when the dialog closes:
public interface MyDialogListener {
void OnCloseDialog();
}
public class MyActivity implements MyDialogListener {
public void SomeMethod() {
MyDialog myDialog = new MyDialog(this, this);
myDialog.show();
}
public void OnCloseDialog() {
// Do whatever you want to do on close here
}
}
public class MyDialog extends Dialog {
MyDialogListener mListener;
public MyDialog (Context context, MyDialogListener listener) {
super(context, R.style.Dialog);
mListener = listener;
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.CloseButton:
mListener.OnCloseDialog();
dismiss()
break;
default:
//...
}
}
}
This is especially useful if you want to send stuff back to the caller at any other time besides on dismissal.
And if you want to have some sort of saving inside the dialog, again, you have to use onDicmissListener since for custom dialogs onDismiss is not called by default:
public class CustomDialog extends Dialog implements DialogInterface.OnDismissListener {
public CustomDialog(Context context) {
super(context);
setupLayout(context);
}
public CustomDialog(Context context, int theme) {
super(context, theme);
setupLayout(context);
}
protected CustomDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
setupLayout(context);
}
private void setupLayout(Context context) {
this.context = context;
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = WindowManager.LayoutParams.FILL_PARENT;
getWindow().setAttributes(params);
setOnDismissListener(this);
loadPreferences();
}
private void loadPreferences() {
// ...
}
private void savePreferences() {
// ...
}
#Override
public void onDismiss(DialogInterface dialogInterface) {
savePreferences();
}
}
If you are using custom dialog and can't dismiss it, try below code.
It worked for me.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
}, 1500);
One thing to remember is that an OnDismissListener is listening for the dismiss of the child processes. The parent of your customer dialog needs the onDismissListener, not the dialog itself.
"Interface used to allow the creator of a dialog to run some code when the dialog is dismissed."
To add dialog inside CustomDialog class:
public class MessageBoxDialog extends Dialog implements DialogInterface.OnDismissListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
...
setOnDismissListener(this);
...
}
#Override
public void onDismiss(DialogInterface dialogInterface) {
}
}