calling method in a separate class - android

I have my main class setup and a worker thread, one of my early requests that I make in run() is to call my second class called login. I do this like so:
login cLogin = new login();
cLogin.myLogin();
class login looks like this:
package timer.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
}
public void myLogin() {
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage(this.getString(R.string.intro));
// add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Register New Account",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
}
});
// add a neutral button to the alert box and assign a click listener
alertbox.setNegativeButton("Login",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
}
});
// show it
alertbox.show();
}
10-01 14:33:33.028: ERROR/AndroidRuntime(440):
java.lang.RuntimeException: Unable to start activity ComponentInfo{timer.test/timer.test.menu}:
java.lang.IllegalStateException:
System services not available to Activities before onCreate()
I put onCreate in but still having the same problem. How can I fix this?

You have a couple of options:
1) Move your public void myLogin() {..} to your main activity. I recommend this solution since you don't need another activity for your purposes.
2) Call startActivity on your login class before calling the myLogin(). Since you inherite from Activity onCreate needs to be called before you call anything else. That's why you get the exception. startActivity is called like this:
Intent i = new Intent(this, login.class);
startActivity(i);

You cannot do it this way simply because you are using the context
AlertDialog.Builder alertbox = new AlertDialog.Builder(this); //this is the activity context passed in..
The context is not available until Activity onCreate is called via startActivity. and not by constructing an new instance of the login object, you can try passing in an context from the activity calling this method
public void myLogin(Context context) {
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
//blah blah blah...
}
yes and never construct an activity instance via the constructor.. -.-

Related

I need to display a simple AlertDialog within a called class

I'm very new to Android, and have a basic question. I need at certain points to display a user notification in a dialog box, which they can simply acknowledge with the OK button.
I'm using:
myActivity.runOnUiThread(new Runnable() {
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(myContext).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("My message");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
This works well in the Main program, but within a called method it needs the Activity and the Context from the main program. Can anybody tell me how to pass these? getApplicationContext() seems to be acceptable, but I can't figure out how to pass the Activity.
Better still of course would be to get the parent Context and Activity within the method, but I can't get that to work either.
I'd be grateful for any help.
-update 10/07/21
Rahul has given me the solution to the problem I posed: how to pass in the Activity and Context.
The problem is that the dialog still doesn't show.
I found a variation online as follows:
AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
builder.setTitle("Alert")
.setMessage("My message")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
but this doesn't work either.
I'm puzzled that such a common and simple task needs so much code. In the desktop languages I'm used to it can be done in a single line.
So my titled question stands, but can anyone see where the code is faulty?
Many thanks
You can either pass activity to the class when initializing the object or you can pass activity when calling the function.
Case 1 (Recommended)
Pass Activity when calling the function:
MyObj myObj = new MyObj();
myObj.showDialog(myValue, ActivityName.this);
Where function will look like this:
public void showDialog(int myValue, Activity activity){
...
}
Then you can use this activity instance inside the method.
Case 2
Pass Activity when initializing the object:
MyObj myObj = new MyObj(ActivityName.this);
Where Class will look like this:
class MyObj{
private Activity thisActivity;
public MyObj(Activity activity){
thisActivity = Activity;
}
...
}
Then you can use this activity instance.
When you have activity object available you can replace context object with it.

how to pass an onclick handler to a custom dialog class

I'm trying to create a custom class for displaying a Yes/No AlertDialog, but I want to onClick handler to be in the activity that instantiates the custom class. So far, the custom class looks like this:
public class YesNoDialog {
private Context gContext = null;
private DialogInterface.OnClickListener onClickListener;
private AlertDialog alertDialog = null;
public YesNoDialog(Context context,
DialogInterface.OnClickListener listener) {
this.gContext = context;
this.onClickListener = listener;
}
public void ShowDialog() {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(this.gContext);
alertDialogBuilder.setTitle("Hello World");
alertDialogBuilder
.setMessage("Are you sure?")
.setCancelable(false)
.setPositiveButton("Yes",this.onClickListener)
.setNegativeButton("No",this.onClickListener);
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
My thinking was to pass the context and onClick handler to the object in the constructor, then assign the handler to the .setPositive and .setNegative buttons.
I implemented the DialogInterface.OnClickListener in my MainActivity class:
public class MainActivity
extends AppCompatActivity
implements DialogInterface.OnClickListener {
And created the onClick handler in MainActivity that should be called when either the Yes or No buttons are clicked in the dialog.
#Override
public void onClick(DialogInterface dialog, int id) {
Log.d("DIALOG RETURNS ID=", Integer.toString(id));
dialog.dismiss();
}
I'm not sure if I'm on the right track or not, but I got stuck in trying to figure out how I would now pass the onClick handler to the YesNoDialog object. I've tried several variations of this:
YesNoDialog dialog = new YesNoDialog(this, MainActivity.onClick);
With no success (won't compile). I have also tried passing only the context, assuming that maybe that's all I really need for .setPositive and .setNegative button handlers, but that didn't work either...this calls require a DialogInterface.OnClickListener.
It feels like I'm close, but I can't get over the hurdle. Can anyone help me connect the dots?
Create a class (DialogUtils) and add this method in it.
public static void showPopUp(Context context
, String title
, String msg
, String positiveBtnTxt
, String negativeBtnTxt
, DialogInterface.OnClickListener positiveBtnListener
, DialogInterface.OnClickListener negativeBtnListener){
final AlertDialog errorDialog;
AlertDialog.Builder errorDialogBuilder = new AlertDialog.Builder(context, R.style.NativeDialogue);
errorDialogBuilder.setTitle(title);
errorDialogBuilder.setMessage(msg);
errorDialogBuilder.setPositiveButton(positiveBtnTxt, positiveBtnListener);
errorDialogBuilder.setNegativeButton(negativeBtnTxt, negativeBtnListener);
errorDialog = errorDialogBuilder.create();
errorDialog.show();
}
Call the method like this :
DialogUtils.showPopUp(this, "title", "message", "positive btn name", "Negative Btn name", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
"Your action"
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
"Your action"
}
});
This is described in the official documentation on dialogs in Android. In short, you need to do the following steps:
Create a DialogFragment for your dialog so it is properly restored when the device rotates or changes the configuration in some other way.
Create an interface which will allow you to send the result of the dialog.
Implement this interface in the activity.
Cast the activity to the interface inside the DialogFragment in onAttach and store it in some field. Don't forget to set to null in onDetach.
When a dialog button is clicked, you can call the appropriate interface method, and the activity will get the result.
Alternatively, if you only ever use this dialog with one activity, you may not declare an interface and simply store a reference to the activity.
Hey you can make one method in your MainActivity class. Like below.
public void onClickOnYesButton(int id){
}
Pass the MainActivity reference like below.
public YesNoDialog(MainActivity context) {
this.gContext = context;
}
And call the onClickOnYessButton by using the MainActivity reference!
Job done!

Android: Exit application from custom dialog

I created a custom dialog for my main activity with two buttons, Exit and Continue:
public class AgeConfirmationDialog extends Dialog {
public AgeConfirmationDialog(Activity a) {
super(a);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setCancelable(false);
setContentView(R.layout.age_dialog);
// .....
// Find the View objects; checkboxes and buttons logic; SharedPreferences
// .....
}
// .....
}
This is how the dialog is launched from the MainActivity:
AgeConfirmationDialog d = new AgeConfirmationDialog(this);
d.show();
This custom dialog pops out every time the main activity is started, and asks for a age confirmation. I don't want the users to close this dialog using the back button, so I added setCancelable(false) in the onCreate method. The Continue button is disabled until a checkbox is checked. If the Continue button is pressed, the dialog is dismissed - using setOnClickListener.
The problem is that I don't know how to dismiss that custom dialog AND finish the main activity when the Exit button is pressed.
Is it possible to do this from the AgeConfirmationDialog class by setting a View.OnClickListener on the Exit button?
change the code to something like this:
public class AgeConfirmationDialog extends Dialog {
Activity mainActivity;
public AgeConfirmationDialog(Activity a) {
super(a);
this.mainActivity = a;
}
//in onClick method of finish-button
public void onFinishClick(View v) {
mainActivity.finish(); //finish activity
}
}
I don't know how to dismiss that custom dialog AND finish the main
activity when the Exit button is pressed.
Then you just have to put in your ExitButton Click Listener:
finish();
For example:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("Exit", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create().show();
Do something in your onclicklistener of exit button. Like:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
And your MainActivity do something like:
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
What you basically do here is going to mainactivity which is your start activity with some key/value extra and check it in your mainactivity through getintent.
This is best process to exit application or you can use it also in logout.

Dismiss a popup from another activity

I am writing an application which is having an activity and I am launching a pop up ( pop up I have implemented in another class which is not an activity).
In my main activity I have code to display the popup when there is an event. I am successfully able to do that. But I need to cancel the popup when I get another event. ( I will get this event only in the main activity).
How can I finish the popup from the main activity when I receive the event?
create a public method in the class where you have created the popUP(dialog) and write inside it as
public void dismissDialog(){
dialog.dismiss();
}
then whenever you want to remove the dialog call this method...
If this pop up is a dialog you can do it with
dialog.cancel();
final AlertDialog.Builder aBuilder;
//constructor(Context c){//mContext = c;}
public void showMessage(final String title, final String s) {
aBuilder = new AlertDialog.Builder(mContext);
aBuilder.setTitle(title);
aBuilder.setIcon(R.drawable.ic_launcher);
// aBuilder.setIcon(R.drawable.icon);
aBuilder.setMessage(s);
}
public void dismissMessage() {
aBuilder.dismiss();
}

passing this to an outer class and starting an activity from alertdialog's list on Android

I am developing an Android app, this app has a dozen of Activities, each one is for a corresponding screen. Now I have this common subtitle bar on top of the screens.
this subtitle bar has a button to display an alert dialog which shows link list to go to a different screen.
I could write a same function for each activity to call the alert dialog, but that would be tedious if I want to modify them, so I created this class:
public class MenuAlertDialog extends Activity {
/*
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
*/
public void createMenu(final Context context){
AlertDialog.Builder dlg = new AlertDialog.Builder(context);
dlg.setTitle("menu");
String[] items = {"pageA", "pageB", "pageC", "pageD", "pageE"};
dlg.setItems(items, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
switch(which){
case 0:
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
break;
default:
break;
}
}
});
dlg.show();
}
}
and call it from each activity, like this:
MenuAlertDialog menu = new MenuAlertDialog();
menu.createMenu(this);
from inside of onCreate.
It can display the alertDialog, but whenever I press pageA link, it fails with an unexpected error.
Logcat says its a nullpointererror and the cause seems
startActivity(intent);
What am I doing wrong?
Remove the code
extends Activity
as you have no need to extend your class that you are creating since it does not rely on any activity related functionality.
Where you call startActivity(intent); replace it with
context.startActivity(intent);
You should change the class to Extends Dialog and not activity.
Also for Try this:
Check out this tutorial on how to create a custom dialog. Custom Dialog
Also Here Another Tutorial
And Here

Categories

Resources