Calling the same method from different activities - java

I have searched for an answer to this issue and while there are many similar topics, none of the solutions suit my needs. I have this code in MainActivity and it works there but I need to call the same 'addPlayer' method in another activity.
I have also tried creating a new java class called 'AddPlayer.java' to call in both activities via buttons in each but I can't find a way to call it. Perhaps its in the way I've defined the .java class?
public class AddPlayer extends AppCompatActivity {
public void addPlayer (View view) {
// followed by same content as method in MainActivity - edited to correct contexts
MainActivity code
public class MainActivity extends AppCompatActivity {
public void addPlayer (View view) {
final ParseObject players = new ParseObject("Players");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog.Builder builderInBuilder = new AlertDialog.Builder(this);
final EditText nameInput = new EditText(this);
nameInput.setInputType(InputType.TYPE_CLASS_TEXT);
final EditText nickInput = new EditText(this);
nickInput.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setTitle("New Player Details")
.setMessage("Enter new player name...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nameInput)
.setPositiveButton("Add Player", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builderInBuilder.setTitle("New Player Details")
.setMessage("Enter player Nickname...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nickInput)
.setPositiveButton("Add Nickname", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
players.add("nickname", nickInput.getText().toString());
players.add("username", nameInput.getText().toString());
players.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Player could not be added.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Player added successfully.", Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
I get no errors calling the method in MainActivity, I am just unsure of how best to call this method from 2 activities and the syntax required to call the separate java class - which has the correct package assignment.
I was expecting to be able to use
AddPlayer.addPlayer(); // or something similar
Perhaps the best way is just to have this code in both locations? Seems inefficient though...

create class todo the task and call it
class AddPlayer{
public void player(Context ctx,View view){
//do your work here
}
}
then call that method like this
AddPlayer addp = new AddPlayer ();
addp.player(context,view);
I think the concept is like that, if you don't want to create a new instance to call the method, you can declare the method as static

Related

How to check Alert Dialog visibility?

I want to check alert dialog is visible or not. In most post I saw that they used isShowing, but seems like its not describable now.
When user click info textview, I pause music. If user close alert dialog, music will be play again.
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create().show();
playstopbutton_builder.setCancelable(false);
//if alert dialog is visible keep music paused
//else if mediaControl.start();
}
});
since you have made Cancelable false, you might need to use
for positive button say like a okay
playstopbutton_builder.setPositiveButton(positiveBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
})
for negative button say like a cancel
playstopbutton_builder.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
})
so it would look like this
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create().show();
playstopbutton_builder.setCancelable(false);
playstopbutton_builder.setPositiveButton(positiveBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
});
playstopbutton_builder.setNegativeButton(negativeBtnText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//resume ur media player here
}
});
}
});
You need to check dialog show or not change you code like this.
info_Button.setClickable(true);
info_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaControl.pause();
AlertDialog.Builder playstopbutton_builder = new AlertDialog.Builder(exercise_arm_triceps_execute.this);
playstopbutton_builder.setTitle("WARNING").setMessage("Please get warm before exercising!");
playstopbutton_builder.create();
playstopbutton_builder.setCancelable(false);
//if alert dialog is visible keep music paused
//else if mediaControl.start();
if(!playstopbutton_builder.isShowing()){
//if its visibility is not showing then show here
playstopbutton_builder.show();
}else{
//do something here... if already showing
}
}
});
You may want to add an OnDismissListener to the playstopbutton_builder:
playstopbutton_builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mediaControl.start();
}
});
This way, when the user dismisses the Alert Dialog, the music will start to play again.
EDIT: if the OnDismissListener approach is not desired, maybe something like this would be better:
public void infoClickHandler(View v) {
mediaControl.pause();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("restart the music?");
b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mediaControl.start();
}
});
b.show();
}
EDIT 2: On the other hand, if the dialog cannot have positive or negative buttons, and you do not want to set cancellable to false, this seems to work:
public void infoClickHandler(View v) {
mediaControl.pause();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("restart the music?");
b.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if (!mediaControl.isPlaying()) {
mediaControl.start();
}
}
});
b.show();
}
The OnDismissListener will be called when the user clicks outside of the dialog box.

Saving Data from an android dialog

I am attempting to save data from an edit text field within a dialog to an ArrayList. I followed the methods of an answer to a similar question (found here How to store edit text data from an Android dialog?) however my code isn't exactly saving data. From my understanding I should be able to do the following(note it isnt the entire class, only the method in question):
public class StartNewGameActivity extends AppCompatActivity {
private ListView lv;
ArrayList<String> game_players = new ArrayList<String>();
public void addPlayerToGame(View view) {
DialogFragment newFragment = new CreatePlayerDialogFragment(
new CreatePlayerDialogFragment.MyMessageDialogListener(){
#Override
public void onClosed(String name) {
game_players.add(name);
}
});
newFragment.show(getSupportFragmentManager(), "players");
}
While using the following class:
public class CreatePlayerDialogFragment extends DialogFragment {
public interface MyMessageDialogListener {
public void onClosed(String name);
}
public AlertDialog onCreateDialog(final MyMessageDialogListener listener) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setMessage(R.string.player_name_dialog)
.setPositiveButton(R.string.player_name_dialog_add, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Add Player
{
if(listener != null) {
listener.onClosed(input.getText().toString());
}
dialog.cancel();
}
}
})
.setNegativeButton(R.string.player_name_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
However with my code I get an error "CreatePlayerDialogFrament() in CreatePlayerDialogFragment cannot be applied to CreatePlayerDialogFrament.MyMessageDialogListener"
Is it possibly because I am trying to do everything in my OnCreate() method? Im not quite sure what the issue is or how to go about solving it.

Firebase Invalid Email Error in Android

I am always getting an error while trying to register a user to firebase in my android app.
"The email specified is invalid"
I noticed this happens on JellyBean devices and I don't know what the problem is, whether it is from the API or something else.
My code snippet is given below:
private void registerUser() {
// Sign Up
mRef.createUser(mAccount.name, mPassword, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
loginUser(true);
}
#Override
public void onError(FirebaseError firebaseError) {
// Sign Up failed
if (firebaseError.getCode() == FirebaseError.NETWORK_ERROR) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.connection_error_message)
.setTitle(R.string.error_title)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkUserExistence();
}
}).setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(firebaseError.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
registerUser();
}
}).setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}

back button alert box(Android Studio)

In my first class, I have this piece of code:
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle(R.string.ALERTA1)
.setMessage(R.string.ALERTA2)
.setPositiveButton(R.string.ALERTA3, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.ALERTA4, null)
.show();
}
This will make an alert box when the back button is pressed, but this works in every class, I only want it to work in this one.
UPDATE:
public void onBackPressed() {
finish();
}
In every class.
Put this in your other classes:
public void onBackPressed() {
super.onBackPressed();
return;
}
That might work.

Execution doesn't wait to Alertdialog.dismiss()

I'm developing an Android application and I have this question:
How can I do to make execution waits until user has selected an option from an AlertDialog?
This is my code:
if (mPerson== null)
{
mPerson = new Person();
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
After dialog.dismiss() I have to execute this:
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
Do the following:
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
postSelection();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
postSelection();
}
});
dialog = builder.create();
dialog.show();
}
Call this method once the selection is complete.
public void postSelection(){
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
}
Think in terms of event based execution. If you want some code to execute when you press a button, then wire it to do so. Place the code in question in a method that you can call whenever you want.
Generally, when you are programming on Android, you need to adhere to the event based nature of the platform. Traditional procedural sequential thinking will lead you to dead ends.
You have to customize your dialog interface like this .
You should use onDismissListener on dialog interface.Dont make it anonymous.
private class MyDialogInterfaceMethod implements DialogInterface.OnClickListener,DialogInterface.OnDismissListener
{
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//when user click a button
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
//put your code here
}
}
Than use it on your alert dialog like this
builder.setNegativeButton("CANCEL",new MyDialogInterfaceMethod ());

Categories

Resources