I have a main_activity in which by pressing a button I launch a form to be completed:
popup= getLayoutInflater().inflate(R.layout.pop_up, null);
signup = new SignUp(popup);
register = (Button) findViewById(R.id.sign_up);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MyLocalBartender.this);
alertBuilder.setView(popup);
final AlertDialog dialog = alertBuilder.create();
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
dialog.show();
}
});
By what you can see I'm using a second activity class (SignUp) to manage the form and not the root class from which it was launched (main_activity).
In this new class I set all the click listeners etc to verify the inputs through a third class that implements an OnClickListener.
Everything works fine until this point. But now I want to test the page/activity called HomePage in which the user should land to if the form is filled.
So what I don know is I remove the click listener from the previous handler and I create an anonymous one to simply open the new activity on register button pressed:
// signup_registerButton.setOnClickListener(new SignupListener(signup_emailField,signup_passwordField1,
// signup_passwordField2, signup_textTemp,signup_organiserRadio, signup_staffRadio,signup_alertMessage));
////*************************TEST******************* START
signup_registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu = new Intent(getApplicationContext(), HomePage.class);
startActivity(menu);
}
});
////*************************TEST******************* END
but this returns a NullPointerException.
I've tried to launch the HomePage.class from the main_activity directly and it works and also I've tried to launch the main activity from this REGISTER button, which didn't work, so this tells me that the problem it is somewhere here.
You need to pass an Activity Context to the Intent constructor. Activities context and Applications context are not the same. Activities context hold much more inforamtions.
In your case you can do like this:
signup_registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu = new Intent(yourActivity, HomePage.class);
startActivity(menu);
}
});
where yourActivity is your activity instance. You can pass it as variable or access it via main_activity.this from inner classes (Listeners) on anywhere inside your class.
Related
In Android Studio, I am trying to open the second activity when corresponding button is pressed.However, I cannot reach that listener that I create in "onCreate" from onPause. I am following an approach like this:
public class MainActivity extends Activity {
private View.OnClickListener openSecondPage = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button button_newPage = findViewById(R.id.button_newpage);
button_newPage.setText("Clicked");
Intent secondPage = new Intent(getApplicationContext(), SecondActivity.class );
startActivity(secondPage);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_newPage = findViewById(R.id.button_newpage);
button_newPage.setOnClickListener(openSecondPage);
}
public void onPause(){
super.onPause();
Button button_newPage = findViewById(R.id.button_newpage);
//Destroy the on click listener
button_newPage.setOnClickListener(null);
}
}
Also user will be able to come back to main activity and then go back to the second activity again. In that case I don't want to open a new activity. Instead I want to open previously created activity. For that case should I create a onResume() method and in that, call startActivity(secondPage). But in that case, since the secondPage is declared in onStart I won't be able to use in onResume. How can I handle that situation?
So there are actually 2 questions.. sorry about that, I didn't want to open 2 different questions for it.
Put Button button_newPage = findViewById(R.id.button_newpage); and button_newPage.setOnClickListener(openSecondPage); inside onResume instead of onCreate, like so:
#Override
protected void onResume() {
super.onResume();
Button button_newPage = findViewById(R.id.button_newpage);
button_newPage.setOnClickListener(openSecondPage);
}
That should solve at least part of your problem.
I have successfully implemented a custom Dialog box that appears when the user tries to leave an activity via a back button or by using onBackPressed(). They can simply cancel the dialog box or continue, and leave the activity. This function has been implemented in multiple activities, however its making my code a lot longer than it needs to be. I wanted to know how to create a util that can be referenced in different activities, without the need for the chunk of code to copy pasted multiple times. Please note that I am retrieving the dialog title and description from string.xml
This is my code:
Dialog customDialog;
Button button_one, button_two;
TextView dialog_title, dialog_description;
customDialog = new Dialog(this);
//Back button will close app
#Override
public void onBackPressed() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description); dialog_description.setText(getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
UPDATE
Created a Java file called "DialogBoxMessage"
DialogBoxMessage Code:
class DialogBoxMessage {
private Dialog customDialog;
private TextView dialog_title, dialog_description;
private Button button_one, button_two;
//Custom Dialog Box Initialization
DialogBoxMessage(Button myButtonOne, TextView myDialogTitle, TextView myDialogDescription, Dialog myCustomDialog) {
customDialog = myCustomDialog;
button_one = myButtonOne;
button_two = myButtonOne;
dialog_title = myDialogTitle;
dialog_description = myDialogDescription;
}
void leaveActivity() {
customDialog.setContentView(R.layout.custom_dialog_box);
dialog_title = customDialog.findViewById(R.id.dialog_title);
dialog_title.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_title));
dialog_description = customDialog.findViewById(R.id.dialog_description);
dialog_description.setText(Resources.getSystem().getString(R.string.leaving_activity_warning_description));
button_one = customDialog.findViewById(R.id.button_one);
button_one.setText(Resources.getSystem().getString(R.string.cancel));
button_two = customDialog.findViewById(R.id.button_two);
button_two.setText(Resources.getSystem().getString(R.string.leave_anyway));
button_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
button_two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.show();
}
}
I input the following code in another activity
Other activity code:
//Reusable exit dialog message
DialogBoxMessage dialogBoxMessage;
//Back button will close app
#Override
public void onBackPressed() {
dialogBoxMessage.leaveActivity();
finish();
}
But it doesn't seem to work, I think there are a lot of issues... please help :(
I assume customDialog is a seperate class you wrote - therefore i would suggest you put main information like contentview, title, message or type in the constructor when you initialize ur Dialog.
For your onClick Method I suggest you create an Interface to handle Button Clicks in your
customDialog class.
This could be implemented as a static method in a utilities class. The method would require 'this' as a parameter, which contains the activity context. The method should return the result of the button press. The activity can use this response to determine if finish() should be called or not.
UPDATE
I had suggested a simple static method, but you've gone down the object-oriented route. That's fine.
However, your constructor requires passing in several views, which wouldn't appear to achieve the code efficiency you are after.
Your constructor should just require the Activity context; everything else is encapsulated in your new class.
In each Activity's onBackPressed method you will need to create the object with
dialogBoxMessage = new DialogBoxMessage(this);
before you can call any of that object's methods.
I want to make buttons once I click on the button I go to another activity?
and the problem is only the first button is working!
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button PageOneButton = (Button) findViewById(R.id.btnPageOne);
PageOneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), PageOne.class);
v.getContext().startActivity(myIntent);
Button PageTwo = (Button) findViewById(R.id.btnPageTwo);
PageTwoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), PageTwo.class);
v.getContext().startActivity(myIntent);
}
{}
});
}
});
}
}
Think it is because most of your code is closed inside the scope of the first onClickListener, try something like this.
Button PageOneButton = (Button) findViewById(R.id.btnPageOne);
PageOneButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent myIntent = new Intent(Main.this, PageOne.class);
startActivity(myIntent);
});
Button PageTwoButton = (Button) findViewById(R.id.btnPageTwo);
PageTwoButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent myIntent = new Intent(Main.this, PageTwo.class);
startActivity(myIntent);
});
Using v.getContext() should be ok, this is just how I usually would do as the Activity itself is indeed a valid context. I guess it just seems more readable to me.
Edit:
Just as a clarification to the current state of your code. The second button is assigned a onClickListener only after the first button is pressed. But since the first button takes the app to a new Activity, inherently destroying the Main Activity, the second button will never have a chance to reach it's onClickListener.
Hope it makes sense, nevertheless the code above should fix the issue.
There are a couple of issues currently in your code. The first issue is that your second button is being defined inside the first button's declaration. The next issue is that you're setting the second OnClickListener to the wrongly named button. You've made a typo and instead of PageTwo, which you've called the Button (presumably you wanted to call it PageTwoButton in accordance with the first Button) and then set the OnClickListener to PageTwoButton instead. Seeing as you're also using multiple Buttons, it's a lot cleaner and more efficient to use a GroupOnClickListener. I'd probably also suggest using 'this' instead of 'v.getContext()' as well when setting up your Intents. Change your code to be like so:
Button PageOneButton = (Button) findViewById(R.id.btnPageOne);
Button PageTwoButton = (Button) findViewById(R.id.btnPageTwo);
PageOneButton.setOnClickListener(addGroupOnClickListener);
PageTwoButton.setOnClickListener(addGroupOnClickListener);
private OnClickListener addGroupOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (v == PageOneButton) {
Intent myIntent = new Intent(Main.this, PageOne.class);
startActivity(myIntent);
} else if (v == PageTwoButton) {
Intent myIntent = new Intent(Main.this, PageTwo.class);
startActivity(myIntent);
}
}
};
Hope this helps!
Two words: Code Indentation
Were you to indent your code properly, you would have noticed that you're setting OnClickListener INSIDE your first buttons' listener. Move it outside your first listener, as has already been advised by others.
There's also an extra pair of {}, which is redundant.
Also, #edwoollard noticed that for the second button, you're using two different names, PageTwo and PageTwoButton. Keep that in mind, unless it's a typo.
In my app i have to use same dialog box on all the activities but then on to the click of button on dialog box i need to perform different operations for different activities, i have kept a common code for dialog but then how to call different functions, here is my code:
final Dialog dialog = new Dialog(mContext,R.style.Theme_Levels);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert);
TextView title = (TextView)dialog.findViewById(R.id.title);
title.setText("Network Error");
TextView msg = (TextView)dialog.findViewById(R.id.msg_txt);
msg.setText("The system is down, please check after some time ");
ImageView cancel = (ImageView)dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView continue_btn = (TextView)dialog.findViewById(R.id.continue_btn);
continue_btn.setBackgroundResource(R.drawable.feedback_button_purple);
continue_btn.setText("Retry");
continue_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//TODO perform different operation depending upon from where this function has been called
dialog.dismiss();
}
});
dialog.show();
Create an interface, say DialogActivity, with one method "handlePositiveButton". Let all your Activities implement this interface. From the Dialog.onClick you do this:
DialogActivity activity = (DialogActivity) getActivity();
activity.handlePositiveButton();
Put the code you have specified in a function of a Utils file.
Then pass the positive button onclick listener in that function.
Refer the below code.
public static void showAlertDialog(OnClickListener listener) {
// enter your code here
continue_btn.setOnClickListener(listener);
// more code here
}
I'm creating a dialog box and using the (this) isnt working. Up until now its just been a button calling a dialogbox but now the button within the called dialogbox needs to call another dialog. The Dialog dialogdelcon is the one with problem.
Here is the code:
case R.id.delappt:
//rmvall();
final Dialog dialogdelsel = new Dialog(this);
dialogdelsel.setContentView(R.layout.delsel);
dialogdelsel.setTitle("What would you like to do?");
dialogdelsel.setCancelable(true);
Button btndelsel = (Button) dialogdelsel.findViewById(R.id.btndelsel);
btndelsel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// delete selected code here.
}
});
Button btndelall = (Button) dialogdelsel.findViewById(R.id.btndelall);
btndelall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// delete all code here.
final Dialog dialogdelcon = new Dialog();
dialogdelcon.setContentView(R.layout.delcon);
dialogdelcon.setTitle("Deletion Confirmation");
dialogdelcon.setCancelable(true);
Button buttoncnclok = (Button) dialogdelcon.findViewById(R.id.btndelcon);
buttoncnclok.setOnClickListener(new OnClickListener() {
// on click for cancel button
#Override
public void onClick(View v) {
dialogdelcon.dismiss();
}
});
dialogdelcon.show();
}
});
dialogdelsel.show();
break;
getApplicationContext() or use YourActictyName.this Because this refers the button click listner ,not your class Object
If this code is in the onCreate() method, or similiar, add getApplicationContext() instead of this and you should be fine. That's because this in a Button-context will refer to the button environment.
To improve the isolation between the two dialogs, it would be best to call showDialog(R.id.delapptcon) from the onClick handler. Then load the new dialog in the onCreateDialog of your activity. In this way, you can create more reusable dialogs and avoid the scoping issue you have now.