support.v7.app.AlertDialog throws NullPointerException on dismiss - android

I updated AppCompat to the newly released revision 22.1.0 and changed my AlertDialog to support.v7.app.AlertDialog. But on a Lollipop device, it throws the following exception on dismissDialog().
java.lang.NullPointerException: attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v7.internal.app.WindowDecorActionBar.getDecorToolbar(WindowDecorActionBar.java:248)
at android.support.v7.internal.app.WindowDecorActionBar.init(WindowDecorActionBar.java:201)
at android.support.v7.internal.app.WindowDecorActionBar.<init>(WindowDecorActionBar.java:184)
at android.support.v7.app.AppCompatDeleg ateImplV7.cre ateSupportActionBar(AppCompatDelegateImplV7.java:176)
at android.support.v7.app.AppCompatDelegateImplBase.getSupportActionBar(AppCompatDelegateImplBase.java:85)
at android.support.v7.app.AppCompatDelegateImplV7.onStop(AppCompatDeleg ateImplV7.java:221)
at android.support.v7.app.AppCompatDialog.onStop(AppCompatDialog.java:108)
at android.app.Dialog.dismissDialog(Dialog.java:438)
at android.app.Dialog.dismiss(Dialog.java:414)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
How do I fix it?
(Lower-version devices seems to work well. This just happens in Lollipop)
+
I don't call dismiss() explicitly in my code. The dialog throws the exception when it is dismissed by back-button or positive/negative button.
++ Here is my code that uses v7.app.AlertDialog. Thank you.
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
public class SimpleYesNoFragment extends DialogFragment {
public interface OnConfirmListner {
public void onConfirm();
}
public static SimpleYesNoFragment newInstance(String title, String message) {
SimpleYesNoFragment fragment = new SimpleYesNoFragment();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
fragment.setArguments(args);
return fragment;
}
private OnConfirmListner mListener;
public void setOnConfirmListener(OnConfirmListner l) {
mListener = l;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder b= new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.yes, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mListener != null) {
mListener.onConfirm();
}
}
})
.setNegativeButton(R.string.no, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Bundle args = getArguments();
String title = args.getString("title",null);
if(!TextUtils.isEmpty(title)) {
b.setTitle(title);
}
String message = args.getString("message",null);
if(!TextUtils.isEmpty(message)) {
b.setMessage(message);
}
return b.create();
}
}

By chance I've noticed that my project has values-v21/themes.xml and it applies android:Theme.Material.Light.Dialog.Alert to the support.v7.app.AlertDialog. This caused the weird bug.
Using a proper AppCompat Theme, such as Theme.AppCompat.Light.Dialog.Alert, to the support.v7.app.AlertDialog solved the problem. Thanks to everyone for helping me out.

Related

Android listener always null when attach in a DialogFragment

high school teachers here trying to teach how to implement a DialogFragment with listener attach with an interface to the fragment that show it. for some reason the listener is always null and while the dialog show, when I press the ok or Cancel button of the Dialog, the transfert to the implement method dont work, it stop a the line where I call the listener class (always null) in the alertDialog.Builder Here my code, thank
here my Fragment that call the dialogfragment
package net.ccl.monapp.ui;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.ccl.monapp.R;
public class AnimationFragment extends Fragment implements MonDialogFragment.MonDialogListener {
public AnimationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_animation,container,false);
Button myButton = root.findViewById(R.id.bt_dialog);
final TextView tvTitre = root.findViewById(R.id.tv_titre);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment myDialog = new MonDialogFragment();
// Show Alert DialogFragment
myDialog.show(getFragmentManager(), "Dialog");
}
});
return root;
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
TextView myTitre = getView().findViewById(R.id.tv_titre);
myTitre.setText("Mon nouveau titre");
dialog.dismiss();
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
Toast.makeText(getActivity(),"Vous avez canceler l'action du dialog",Toast.LENGTH_SHORT);
}
}
here my DialogFragment
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
public class MonDialogFragment extends DialogFragment {
public MonDialogFragment() {
}
public interface MonDialogListener {
void onDialogPositiveClick(DialogFragment dialog);
void onDialogNegativeClick(DialogFragment dialog);
}
// Use this instance of the interface to deliver action events
public MonDialogListener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = (MonDialogListener) context;
} catch (ClassCastException e) {
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Mon interface dialog");
builder.setMessage("Ceci est un message qui explique que tu peux changer le titre du fragment animation en cliquant sur ok");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onDialogPositiveClick(MonDialogFragment.this);
}
});
builder .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onDialogNegativeClick(MonDialogFragment.this);
}
});
return builder.create();
}
}
and here my logcat
Process: net.ccl.monapp, PID: 13691
java.lang.NullPointerException: Attempt to invoke interface method 'void net.ccl.monapp.ui.MonDialogFragment$MonDialogListener.onDialogPositiveClick(androidx.fragment.app.DialogFragment)' on a null object reference
at net.ccl.monapp.ui.MonDialogFragment$1.onClick(MonDialogFragment.java:56)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Your onAttach() isn't actually doing anything since the Context you're attempting to cast is your Activity, not your AnimationFragment.
Instead of reaching up to get your listener, your AnimationFragment should set the listener on the Dialog by overriding onAttachFragment().
First, you need to make sure that your MonDialogFragment is a child fragment of your AnimationFragment by changing your show() to use getChildFragmentManager():
myDialog.show(getChildFragmentManager(), "Dialog");
Then, override onAttachFragment() in your AnimationFragment:
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof MonDialogFragment) {
((MonDialogFragment) fragment).listener = this;
}
}
You can then remove onAttach() from MonDialogFragment entirely.

How to get the current item inside FragmentPagerAdapter?

I have the following code -
#Override
public void sendDeviceIdResult(String deviceId, boolean isAlreadyExist) {
int currentItem = viewPager.getCurrentItem();
Fragment item = adapter.getItem(currentItem);
if (item instanceof PhoneStateAndAgeVerificationFragment) {
Dialog dialog = ((PhoneStateAndAgeVerificationFragment) item).getProgressDialog();
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
Intent intent = new Intent();
intent.putExtra(KEY_DEVICE_ID, deviceId);
intent.putExtra(KEY_IS_SUCCESS, !isAlreadyExist);
setResult(RESULT_OK, intent);
finish();
}
The issue is that one the line of getItem(position) it does not get the actual reference of the current fragment, but creates a brand new one.
I want to get the reference to the current one and dismiss it's AlertDialog on it.
I know this has been asked many times but I got completely lost while reading all the solutions, so if someone could please show me something that is relevant to my case?
here is my PhoneStateAndAgeVerificationFragment -
package com.onemdtalent.app.ui.verification;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import com.onemdtalent.app.App;
import com.onemdtalent.app.R;
import com.onemdtalent.app.core.base.AbstractFragment;
import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
public class PhoneStateAndAgeVerificationFragment extends AbstractFragment{
#BindView(R.id.frag_verification_phone_checkbox_age)
CheckBox checkBoxAge;
private AlertDialog.Builder mBuilder;
private Dialog mDialog;
public static Fragment newInstance() {
return new PhoneStateAndAgeVerificationFragment();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBuilder = new AlertDialog.Builder(getActivity(), R.style.DialogTheme);
}
#OnCheckedChanged(R.id.frag_verification_phone_checkbox_age)
void OnAgeCheckedChanged(CompoundButton button, boolean checked) {
if (checked) {
button.setTextColor(ContextCompat.getColor(button.getContext(), R.color.black));
}
}
#OnClick(R.id.verification_button_got_it)
void onBtnGotItClicked(View view) {
if (!checkBoxAge.isChecked()) {
checkBoxAge.setTextColor(ContextCompat.getColor(checkBoxAge.getContext(), R.color.accent_red));
return;
}
showProgressDialog();
if (getContext() instanceof VerificationPageListener) {
((VerificationPageListener) getContext()).onPageAgreed();
}
}
#Override
protected int getLayoutResourceId() {
return R.layout.layout_verification_phone_age;
}
private void showProgressDialog(){
if (mBuilder == null) {
mBuilder = new AlertDialog.Builder(App.getAppContext());
}
mBuilder.setCancelable(false);
mBuilder.setView(R.layout.custom_proggress_dialog);
mDialog = mBuilder.create();
mDialog.show();
}
public Dialog getProgressDialog() {
return mDialog;
}
}
Try adding the following code in your FragmentPagerAdapter, this has worked for me.
public class MyPagerAdapter extends FragmentPagerAdapter {
private Fragment mCurrentFragment;
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
}
Call the getCurrentFragment() method from your sendDeviceIdResult() method
I hope this helps.

null pointer exception in captcha [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am implementing the captcha code in my form but I am getting a null pointer exception the method getImage().
I have two captcha codes in the project one is working fine but the other one is showing the following error. I don't know why it is not taking the captcha as a parameter.
I am providing the logcat and the mainactivity.java below.
Logcat
FATAL EXCEPTION: main
Process: com.mws.tms_application, PID: 6983
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mws.tms_application/com.mws.tms_application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
at com.mws.tms_application.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6540) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
main activity.java
package com.mws.tms_application;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView Registerlink;
Button Submit_btn ,Reset_btn,Link_btn;
EditText Username,Usermob,UserAddress,Usermailid,Userpass,Usercapt;
ActionBar actionBar;
ImageView imageView1;
TextCaptcha textCaptcha1;
//#2eb82e
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Registerlink = (TextView) findViewById(R.id.loginlink);
Submit_btn=(Button)findViewById(R.id.Submit_btn);
Reset_btn=(Button)findViewById(R.id.Main_Reset_btn);
Username=(EditText)findViewById(R.id.username_edtext);
Usermob=(EditText)findViewById(R.id.usermob_no_edtext);
UserAddress=(EditText)findViewById(R.id.userAddresss_edtext);
Usermailid=(EditText)findViewById(R.id.usermailid_edtext);
Userpass=(EditText)findViewById(R.id.userpass_edtext);
Usercapt=(EditText)findViewById(R.id.usercapt_edtext);
Link_btn=(Button)findViewById(R.id.Link_btn);
imageView1=(ImageView)findViewById(R.id.register_capt_imageview);
imageView1.setImageBitmap(textCaptcha1.getImage());
actionBar=getSupportActionBar();
actionBar.show();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2eb82e")));
MainLogic();
}
private void MainLogic()
{ Link_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Home_Navigation_Activity.class);
startActivity(i);
}
});
Submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isValidData();
}
});
Reset_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
claredata();
}
});
Registerlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Login_Activity.class);
startActivity(i);
}
});
}
/* Userid,Username,usermob,userAddress,usermailid,userpass,usercapt;*/
public boolean isValidData()
{
String id,name,mobile,address,email,password,captch;
name=Username.getText().toString();
mobile=Usermob.getText().toString();
address=UserAddress.getText().toString();
email=Usermailid.getText().toString();
password=Userpass.getText().toString();
/*captch=Usercapt.getText().toString();*/
if (!name.equals("")&&!mobile.equals("")&&mobile.length()>=10&&mobile.length()<=13&&!address.equals("")&&!email.equals("")&&!password.equals(""))
{
if (validEmail((email)))
{
return true;
}
else
{
AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
alt.setMessage("Invalid Email_Id");
alt.setCancelable(true);
alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog=alt.create();
alertDialog.show();
return false;
}
}
else
{
AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
alt.setMessage("Please fill all details");
alt.setCancelable(true);
alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog=alt.create();
alertDialog.show();
}
return false;
}
public boolean claredata()
{
Username.setText("");
Usermob.setText("");
UserAddress.setText("");
Usermailid.setText("");
Userpass.setText("");
/*captch=Usercapt.getText().toString();*/
return false;
}
private boolean validEmail(String email) {
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (email.trim().matches(emailPattern))
{
return true;
}
return false;
}
}
It is coming from
imageView1.setImageBitmap(textCaptcha1.getImage());
you are using textCaptcha1 but you have not initialized it anywhere

How to call Fragment method from activity to update listview in fragment?

I want to update listview in fragment from main activity after selecting item from dialog.
I am using FragmentPagerAdapter in this Activity
My Dialog method
private void showDialog(String routeName) {
MyTTCDB db = new MyTTCDB(this);
List<String> directions = db.getDirectionByRoute(routeName);
AlertDialog.Builder builderSingle = new AlertDialog.Builder(this);
builderSingle.setTitle("Direction");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.select_dialog_singlechoice);
for (String string : directions) {
arrayAdapter.add(string);
}
builderSingle.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builderSingle.setAdapter(arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String side = arrayAdapter.getItem(which);
FragmentStops fragment = (FragmentStops) mSectionsPagerAdapter
.getItem(1);
fragment.refresh(side);
}
});
builderSingle.show();
}
My Fragment
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.anilvasani.myttc.StopsActivity.Interface_FragmentStops;
import com.anilvasani.myttc.adapter.AdapterStops;
import com.anilvasani.myttc.data.MyTTCDB;
import com.anilvasani.myttc.models.Stop;
public class FragmentStops extends Fragment {
View view;
AdapterStops myAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragement_stops, container, false);
return view;
}
public void refresh(String side) {
// TODO Auto-generated method stub
String routeName = getActivity().getIntent()
.getStringExtra("routeName").toString();
ListView listStops = (ListView) view.findViewById(R.id.dialog_listView);
// EditText txtSearch=(EditText)
// view.findViewById(R.id.dialog_txtSearch);
MyTTCDB db = new MyTTCDB(getActivity());
List<Stop> allStops = db.getAllStopsByRouteAndSide(routeName, side);
myAdapter = new AdapterStops(getActivity(), allStops);
listStops.setAdapter(myAdapter);
}
}
I am getting errors like...
12-14 23:43:02.696: E/MessageQueue-JNI(7577): java.lang.NullPointerException
12-14 23:43:02.696: E/MessageQueue-JNI(7577): at com.anilvasani.myttc.FragmentStops.refresh(FragmentStops.java:34)
12-14 23:43:02.696: E/MessageQueue-JNI(7577): at com.anilvasani.myttc.StopsActivity$3.onClick(StopsActivity.java:120)
12-14 23:43:02.696: E/MessageQueue-JNI(7577): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
So please help me, How to call method of Fragment from Activity based on user's input.
It seems your error is coming from the line:
String routeName = getActivity().getIntent()
.getStringExtra("routeName").toString();
Make sure of the following things:
That when you started the activity that you calling refresh method (the activity that the dialog is attached to) that you start the activity in an intent since getIntent() is trying to return that intent.
Next make sure that there is a String named "routeName" and that that String is not null.
I hope this helps

Get value from DialogFragment [duplicate]

This question already has answers here:
Receive result from DialogFragment
(15 answers)
Closed 9 years ago.
I want the DialogFragment to return a value to me that was entered in editQuantity when dismissed.
But i am not getting any way to make it work. I can do this by passing the value through the intent but that destroys the progress of the current activity.
Is there any way other than passing through intent that will return me value?
package com.example.myprojectname;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
public class QuantityDialogFragment extends DialogFragment implements OnClickListener {
private EditText editQuantity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.app_name)
.setMessage("Please Enter Quantity")
.setPositiveButton("OK", this)
.setNegativeButton("CANCEL", null)
.setView(editQuantity)
.create();
}
#Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
dialog.dismiss();
}
}
Assuming that you want to foward result to the calling Activity:) try this code snippet:
public class QuantityDialogFragment extends DialogFragment implements OnClickListener {
private EditText editQuantity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
editQuantity = new EditText(getActivity());
editQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
return new AlertDialog.Builder(getActivity()).setTitle(R.string.app_name).setMessage("Please Enter Quantity")
.setPositiveButton("OK", this).setNegativeButton("CANCEL", null).setView(editQuantity).create();
}
#Override
public void onClick(DialogInterface dialog, int position) {
String value = editQuantity.getText().toString();
Log.d("Quantity: ", value);
MainActivity callingActivity = (MainActivity) getActivity();
callingActivity.onUserSelectValue(value);
dialog.dismiss();
}
}
and on Your activity add :
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.show(getSupportFragmentManager(), "Dialog");
}
/**
* callback method from QuantityDialogFragment, returning the value of user
* input.
*
* #param selectedValue
*/
public void onUserSelectValue(String selectedValue) {
// TODO add your implementation.
}
}
Taking this idea a little further, I created a listener interface inside the dialog and implemented it in the main activity.
public interface OnDialogResultListener {
public abstract void onPositiveResult(String value);
public abstract void onNegativeResult();
}
public void setOnDialogResultListener(OnDialogResultListener listener) {
this.onDialogResultListener = listener;
}
Call onNegativeResult() inside an overriden onCancel(DialogInterface) and onPositiveResult(String) where you want your dialog to return the value.
Note: don't forget to dismiss() your dialog after calling onPositiveResult() or the dialog window will stay opened.
Then inside your main activity you can create a listener for the dialog, like so:
QuantityDialogFragment dialog = new QuantityDialogFragment();
dialog.setOnDialogResultListener(new QuantityDialogFragment.OnDialogResultListener() {
#Override
public void onPositiveResult(String value) {
//Do something...
}
#Override
public void onNegativeResult() {
//Do something...
}
});
This will make your dialog easier to reuse later.

Categories

Resources