DialogFragment return onClick result to MainActivity - java

This has been asked and answered at least a dozen times yet I still can't get mine going. I've tried 4 or more of the listed answers and get no errors, a result simply isn't returned. here's the most recent code that I've tried. I really wanted this solution to work because it was the most readable to me.
I welcome any suggestions, Thanks.
MainActivity
...
private void showAlertDialog() {
FragmentManager fm = getSupportFragmentManager();
MyAlertDialogFragment alertDialog =
MyAlertDialogFragment.newInstance("Some title");
alertDialog.setTargetFragment(alertDialog, 1);
alertDialog.show(fm, "fragment_alert");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intentdata)
{
// Stuff to do, dependent on requestCode and resultCode
if(requestCode == 1) // 1 is an arbitrary number, can be any int
{
// This is the return result of your DialogFragment
if(resultCode == 1) // 1 is an arbitrary number, can be any int
{
Toast.makeText(MainActivity.this, "result received",
Toast.LENGTH_SHORT).show();
Log.d("onActivityResult", "result received" + resultCode);
}
}
}
MyDialogFragment
...
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
...
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage("Are you sure?");
alertDialogBuilder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// on success
}
});
alertDialogBuilder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getTargetFragment().onActivityResult(getTargetRequestCode(),
1, getActivity().getIntent());
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}

I found it, added a onDialogOKPressed method to my MainActivity and put this inside the onClick of my dialog ((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
so now it looks like this
MyDialogFragment
...
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage("Are you sure?");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// on success
((MainActivity)(MyAlertDialogFragment.this.getActivity())).onDialogOKPressed();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getTargetFragment().onActivityResult(getTargetRequestCode(), 1, getActivity().getIntent());
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
MainActivity
...
public void onDialogOKPressed () {
// Stuff to do, dependent on requestCode and resultCode
Toast.makeText(MainActivity.this, "OK pressed", Toast.LENGTH_SHORT).show();
}

Related

How to make a button listen again after click?

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dpText = (TextView) findViewById(R.id.dpText);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
updateQuestion(random.nextInt(mdata.questions.length));
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(button1.getText().equals(correctAnswer)){
updateQuestion(random.nextInt(mdata.questions.length));
} else{
gameOver();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(button2.getText().equals(correctAnswer)){
updateQuestion(random.nextInt(mdata.questions.length));
} else{
gameOver();
}
}
});
I was making a quiz app. I created a method, updateQuestion(), which takes a random integer to show questions from array. I am facing problem that when a user clicks the button, it works fine for first time. When Second question pops up, button doesn't listen for answer. On repeated clicks, button work sometimes. Please help, sorry for poor english
update question code -
public void updateQuestion(int num){
dpText.setText(mdata.getQues(num));
button1.setText(mdata.getAlia(num));
button2.setText(mdata.getPari(num));
correctAnswer = mdata.getAnswer(num);
}
game Over code -
private void gameOver(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder
.setMessage("Game Over")
.setCancelable(false)
.setPositiveButton("New Game",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
})
.setNegativeButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

showing alert dialog on pressing back button [duplicate]

This question already has answers here:
How to prevent going back to the previous activity?
(14 answers)
Closed 6 years ago.
I want to show an alert message on pressing back button of Android device asking user weather he is sure or not. If user press "Yes" then he should navigate to previous. in case of "NO" activity should resume. But the problem occurs when I press back button it performs both the actions. It also navigate to previous activity and displays the alert dialog.
Here is my code.
public void onBackPressed() {
super.onBackPressed();
AlertDialog.Builder alertdialog=new AlertDialog.Builder(this);
alertdialog.setTitle("Warning");
alertdialog.setMessage("Are you sure you Want to exit the tutorial???");
alertdialog.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(secAddition.this,addition.class);
startActivity(intent);
secAddition.this.finish();
}
});
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=alertdialog.create();
alertdialog.show();
}
If you want to show the alert dialog without closing the app or clearing the stack, you should not call
super.onBackPressed();
Please check the following code snippet
#Override
public void onBackPressed() {
//super.onBackPressed();
IsFinish("Want to close app?");
}
public void IsFinish(String alertmessage) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
android.os.Process.killProcess(android.os.Process.myPid());
// This above line close correctly
//finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(alertmessage)
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
This is what you are looking for. you don't need to startActivity on back pressed. If user select Yes than call super onBackPress
public void onBackPressed() {
AlertDialog.Builder alertdialog=new AlertDialog.Builder(this);
alertdialog.setTitle("Warning");
alertdialog.setMessage("Are you sure you Want to exit the tutorial???");
alertdialog.setPositiveButton("yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
super.onBackPressed();
}
});
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=alertdialog.create();
alertdialog.show();
}
Remove
super.onBackPressed();
This should work.
public void onBackPressed() {
AlertDialog.Builder alertdialog=new AlertDialog.Builder(this);
alertdialog.setTitle("Warning");
alertdialog.setMessage("Are you sure you Want to exit the tutorial???");
alertdialog.setPositiveButton("yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(secAddition.this,addition.class);
startActivity(intent);
secAddition.this.finish();
}
});
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=alertdialog.create();
alertdialog.show();
}
you can write like this for your code to work :
public void onBackPressed() {
AlertDialog.Builder alertdialog=new AlertDialog.Builder(this);
alertdialog.setTitle("Warning");
alertdialog.setMessage("Are you sure you Want to exit the tutorial???");
alertdialog.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
super.onBackPressed();
}
});
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=alertdialog.create();
alertdialog.show();
}
No need to start the Activity again if you are going to previous Activity,
In your code when you do a back press, super.onBackPressed() gets called so it goes to previous Activity

Is Possible for on Back Pressed method with alert dialog in fragment

#Override
public void onBackPressed() {
Log.d("back button", "back button pressed");
AlertDialog.Builder ad1=new AlertDialog.Builder(getActivity());
ad1.setMessage("Are you sure you want to exit? ");
ad1.setCancelable(false);
ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(getActivity(), LoginActivity.class);
startActivity(i);
}
});
ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(getActivity(), FrndsearchFragment.class);
startActivity(i);
}
});
AlertDialog alert=ad1.create();
alert.show();
}
By using the code i getting the error in #Override and i write the super.onBackPressed i got onBackPressed in super.onBackPressed .
Yes you can do the same by overriding onKeyDown method.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Exit");
builder.setMessage("Do you want to exit the application?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
exit();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void exit() {
finish();
}

Android: Start Dialog Box that return back results from activity

I want to start a dialog box from my activity.
The dialog box return some results that is useful for me.
How can i achieve that?
I dont know what to put in "?"(mentioned below) because my DialogClass extends Fragment and not activity.
Please Correct the below code:
Code Snippet inside my activity:
buttonDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this,?);
startActivityForResult(intent,1);
}
});
//On Activity result method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == GlobalVariables.REQUEST_CODE_LIST_NAME) {
Log.d("Result received","");
}
}
My DialogFragment:
public static class MyDialogClass extends DialogFragment
{
private String textListName;
#Override
public Dialog onCreateDialog(Bundle bundle)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(TagClass.ENTER_NAME);
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(TagClass.OK, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
textListName = input.getText().toString();
if (!textListName.equals("")) {
Intent i = new Intent();
i.putExtra("ListName", textListName);
startActivityForResult(i,1);
} else
input.setError(TagClass.ERROR_BLANK_FIELD);
}
});
builder.setNegativeButton(TagClass.CANCEL, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
check this code snippet, it describes how to show fragment in the activity.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

Inheriting classes from one main class

I am new in programming and i don't have much experience in inheritance. Now a days I am working in android development. This is my class code. I want to inherit all classes from this class. Only difference is inherited class should change AlertDialog message and dial number in call() method. Please tell me how to inherit this class to another what is the code should be?
public class PrepaidChineTown extends AppCompatActivity {
Button chinaButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prepaidchinatown);
chinaButton = (Button)findViewById(R.id.chinaTownBtn);
chinaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(PrepaidChineTown.this);
builder.setTitle("China Town Offer");
builder.setMessage("Are you sure you want to activate China Town Offer? Terms and condition apply");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
call();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public void call(){
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode("*2300#")));
try{
startActivity(in);
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Your Activity is not Found", Toast.LENGTH_LONG).show();
}
}
}
Create a Constant.class
private String number = "";
public class Constant {
public static void alertDialogShow(Context context,String title,String message,String _number)
{
this.number = _number;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//to do your stuff
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void call(){
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode(number)));
try{
startActivity(in);
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Your Activity is not Found", Toast.LENGTH_LONG).show();
}
}
}
And you can call this in any activity.
like this.
Constant.alertDialogShow(CurrentActivity.this,"Title","Message","*2300#");
public class PrepaidChineTown extends AppCompatActivity implements OnClickListener
{
Button chinaButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prepaidchinatown);
chinaButton = (Button)findViewById(R.id.chinaTownBtn);
chinaButton.setOnClickListener(this);
}
public void alertDialogue(String title,String message,Context context)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
call();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void call(){
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode("*2300#")));
try{
startActivity(in);
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Your Activity is not Found", Toast.LENGTH_LONG).show();
}
}
Now Create object of PrepaidChineTown and call alertDialogue() by passing required parameters or by extending this class you can use that method to show dialogue

Categories

Resources