AlertDialog.Builder dlg = new AlertDialog.Builder(context:??);
I get an error when I put "this"
No "activity.this"
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
final View v = View.inflate(context, R.layout.trend_2019, null);
final TextView colorName = (TextView)v.findViewById(R.id.colorName);
TextView colorNameEn = (TextView)v.findViewById(R.id.colorNameEn);
TextView colorCode = (TextView)v.findViewById(R.id.colorCode);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("log", colorDataList.get(i).getColorCode());
AlertDialog.Builder dlg = new AlertDialog.Builder(view.getContext());
dlg.setNegativeButton("닫기", null);
dlg.show();
}
});
v.setTag(colorDataList.get(i).getColorCode());
return v;
}
You should pass context in constructor of adapter
public class ColorAdapter extends BaseAdapter {
private Context context;
private List<ColorData> colorDataList;
public ColorAdapter(Context context, List<ColorData> colorDataList) {
this.context = context;
this.colorDataList = colorDataList;
}
and use that context in your dialog and you are missing dlg.create() in your code
AlertDialog.Builder dlg = new AlertDialog.Builder(context);
dlg.setNegativeButton("닫기", null);
dlg.create();
dlg.show();
It will solve that error
Before show AlertDialog you should create it.
Call create() before show()
Your edited code
AlertDialog.Builder dlg = new AlertDialog.Builder(view.getContext());
dlg.setNegativeButton("닫기", null);
dlg.create();
dlg.show();
Related
I have a dialog method in my fragment, which I want to call from my main activity FAB.
I tried to call it, but got this error;
Attempt to invoke virtual method 'android.view.LayoutInflater android.support.v4.app.FragmentActivity.getLayoutInflater()' on a null object reference
editProfileDialog() is the dialog method in my fragment that I tried to call in my main activity.
public class Edit_fragment extends Fragment {
private EditPresenter mEditPresenter;
public Edit_fragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.edit_profile_fragment, container, false);
ButterKnife.bind(this, view);
mEditPresenter = new EditPresenter(this);
mEditPresenter.onCreate();
return view;
}
public void editProfileDialog(){
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.edit_profile_dialogue, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(dialoglayout);
builder.setCancelable(true);
TextView edit_profile = (TextView)dialoglayout.findViewById(R.id.edit_me);
Typeface Sms = Typeface.createFromAsset(getActivity().getAssets(), "fonts/FTLTLT.TTF");
edit_profile.setTypeface(Sms);
TextView new_profile_photo = (TextView)dialoglayout.findViewById(R.id.addAvatar);
new_profile_photo.setTypeface(Sms);
TextView edit_username = (TextView)dialoglayout.findViewById(R.id.editUsernameBtn);
edit_username.setTypeface(Sms);
TextView Change_bio = (TextView)dialoglayout.findViewById(R.id.statusLayout);
Change_bio.setTypeface(Sms);
final AlertDialog dialog = builder.create();
new_profile_photo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
editPhotoDialog();
}
});
edit_username.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
Change_bio.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
private void editPhotoDialog(){
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.edit_photo_dialogue, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(dialoglayout);
builder.setCancelable(true);
FrameLayout cameraBtn = (FrameLayout)dialoglayout.findViewById(R.id.cameraBtn);
FrameLayout galleryBtn = (FrameLayout)dialoglayout.findViewById(R.id.galleryBtn);
AppCompatTextView cameraBtnTxt = (AppCompatTextView)dialoglayout.findViewById(R.id.cameraBtnTxt);
Typeface Sms = Typeface.createFromAsset(getActivity().getAssets(), "fonts/FTLTLT.TTF");
cameraBtnTxt.setTypeface(Sms);
AppCompatTextView galleryBtnText = (AppCompatTextView)dialoglayout.findViewById(R.id.galleryBtnText);
galleryBtnText.setTypeface(Sms);
final AlertDialog dialog = builder.create();
cameraBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
setCameraBtn();
}
});
galleryBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
setGalleryBtn();
}
});
dialog.show();
}
private void setGalleryBtn() {
if (PermissionHandler.checkPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
AppHelper.LogCat("Read data permission already granted.");
new PickerBuilder(getActivity(), PickerBuilder.SELECT_FROM_GALLERY)
.setOnImageReceivedListener(imageUri -> {
Intent data = new Intent();
data.setData(imageUri);
AppHelper.LogCat("new image SELECT_FROM_GALLERY" + imageUri);
mEditPresenter.onActivityResult(this, AppConst.SELECT_PROFILE_PICTURE, RESULT_OK, data);
})
.setImageName(getActivity().getString(R.string.app_name))
.setImageFolderName(getActivity().getString(R.string.app_name))
.setCropScreenColor(R.color.colorPrimary)
.withTimeStamp(false)
.setOnPermissionRefusedListener(() -> {
PermissionHandler.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
})
.start();
} else {
AppHelper.LogCat("Please request Read data permission.");
PermissionHandler.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
private void setCameraBtn() {
if (PermissionHandler.checkPermission(getActivity(), Manifest.permission.CAMERA)) {
AppHelper.LogCat("camera permission already granted.");
new PickerBuilder(getActivity(), PickerBuilder.SELECT_FROM_CAMERA)
.setOnImageReceivedListener(imageUri -> {
AppHelper.LogCat("new image SELECT_FROM_CAMERA " + imageUri);
Intent data = new Intent();
data.setData(imageUri);
mEditPresenter.onActivityResult(this, AppConst.SELECT_PROFILE_CAMERA, RESULT_OK, data);
})
.setImageName(getActivity().getString(R.string.app_name))
.setImageFolderName(getActivity().getString(R.string.app_name))
.setCropScreenColor(R.color.colorPrimary)
.withTimeStamp(false)
.setOnPermissionRefusedListener(() -> {
PermissionHandler.requestPermission(getActivity(), Manifest.permission.CAMERA);
})
.start();
} else {
AppHelper.LogCat("Please request camera permission.");
PermissionHandler.requestPermission(getActivity(), Manifest.permission.CAMERA);
}
}
}
On my fab.setOnClickListener() that is in my main_activity. I called editProfileDialog() like this;
mEdit_profile_fragment.editProfileDialog();
AND THAT ERROR SHOWED UP IN THE LOGCAT.
LayoutInflater inflater=(LayoutInflater)getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialoglayout = inflater.inflate(R.layout.edit_profile_dialogue, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(dialoglayout);
builder.setCancelable(true);
Try this way..
Edit_fragment homeFragment = (Edit_fragment) getSupportFragmentManager().findFragmentByTag(Edit_fragment.class.getSimpleName());
if(fragment != null){
fragment.editProfileDialog();
}
Use this,
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Change your method to this:
public void editProfileDialog(Context context){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialoglayout = inflater.inflate(R.layout.edit_profile_dialogue, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(dialoglayout);
builder.setCancelable(true);
This is because getActivity() is not available in activity class.
I am getting a null pointer exception when I click the OK button. and I am trying to get the value form an EditText in an AlertDialog. I am calling the AlertDialog from a fragment.
I believe this line is the problem
View promptView = layoutInflater.inflate(R.layout.passchange_dialog, null);
I think it is because I am passing null but I am not sure what eles to pass. Please note I am calling the AlertDialog from a fragment not an Activity.
public class fragment_account extends myFragment {
private final String firebase = "https://xxxxxxxx.firebaseio.com";
private String email = "";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_account, container, false);
SharedPreferences sp = getActivity().getPreferences(0);
TextView address = (TextView) view.findViewById(R.id.textViewEmailAddress);
email = sp.getString("email", "");
address.setText(email);
ImageView imageChangePass = (ImageView) view.findViewById(R.id.imageChangePass);
imageChangePass.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
showInputDialog(v);
}
}
);
return view;
}
protected void showInputDialog(final View view) {
try
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View promptView = layoutInflater.inflate(R.layout.passchange_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(view.getContext());
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText edittextOldPass = (EditText) view.findViewById(R.id.edittextOldPass);
EditText edittextNewPass = (EditText) view.findViewById(R.id.edittextNewPass);
EditText edittextConfirmPass = (EditText) view.findViewById(R.id.edittextConfirmPass);
final String oldPass = edittextOldPass.getText().toString().trim();
final String newPass = edittextNewPass.getText().toString().trim();
final String confirmPass = edittextConfirmPass.getText().toString().trim();
Firebase ref = new Firebase(firebase);
ref.changePassword(email, oldPass, newPass, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
}
#Override
public void onError(FirebaseError firebaseError) {
}
});
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
catch (Exception e)
{
Log.i("myStuff", e.getMessage());
}
}
}
Any help or suggestions would be greatly appreciated. Thanks
I think you should call findViewById on promptView instead of on view variable
I guess you should initialize all those textview's before setting the layout of your dialog instead of inside your onClick method. As you have to access their values, you'll have to declare them final in order to get what the user typed in inside of your onClick function.
here is my code for ArrayAdapter. When i click on LinearLayout "cat" it gives error on dialog.show(). I don't know how to create custom dialog within ArrayAdapter class.
Everything work fine when i remove creating dialog part.
Thanks in advance
CategoryAdapter.java
public class CategoryAdapter extends ArrayAdapter<String> {
private final Context context;
String[] menu = new String[25] ;
String[] menu2 = new String[25];
String[] menu3 = new String[25];
private LayoutInflater inflater;
viewholder vh;
public CategoryAdapter(Context context, String [] menu,String [] menu2,String [] menu3) {
super(context, R.layout.categoryadapter, menu);
this.context = context;
this.menu = menu;
this.menu2=menu2;
this.menu3=menu3;
}
public View getView(final int position, View convertView, ViewGroup parent) {
{
vh=new viewholder();
if (inflater == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.categoryadapter, parent, false);
vh.cat=(LinearLayout) convertView.findViewById(R.id.category);
convertView.setTag(vh);
}
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
public class viewholder
{
LinearLayout cat;
}
}
Use context instead getContext()
final Dialog dialog = new Dialog(context);
Finally, Just pass context
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_LONG).show();
}
});
Try-
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.update_categore_dialog);
dialog.setTitle("Update Your Category");
dialog.show();
try this below link, hope you like it.
OrderDetailListAdatper adapter = new OrderDetailListAdatper(Yourclass.this,Resource,
listorderlistInfo);
//set your adapter..
in your adapter getview, paste that code and it works fine for me.
holder.btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder((Activity)_context);
alert.setMessage("Do you want to delete?");
alert.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int whichButton) {
OrderDetailListAdatper.this._listOrderListInfoAdapter
.remove(position); OrderDetailListAdatper.thisnotifyDataSetChanged();
}
});
alert.create().show(); // btw show() creates and shows it..
}
});
In your getView() method, Replace getContext() with your context variable.
vh.cat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
//remaining code...
}
});
And in your initialization of CateogoryAdapter don't pass getApplicationContext(), instead pass in the context (Activity.this) like this.
CategoryAdapter adapter = CategoryAdapter(YourActivity.this, menu, menu2, menu3)
I want to show the alert dialog inside a class which extends with arrayAdapter.
I am getting this error
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Here my code, what i have tried
public class DeteteAdapter extends ArrayAdapter<Gold> {
private int contexts = Intent.FLAG_ACTIVITY_NEW_TASK;
private Context context;
private List<Gold> subjects = new ArrayList<Gold>();
private TextView subject;
private TextView date_day;
private TextView time;
private ProgressDialog pDialog;
String name;
JSONParser jsonParser = new JSONParser();
// url to create new product
private static String url_create_product = "http://ayyappagold.com/ayyappa/test.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public static String month;
public static String year;
public DeteteAdapter(Context context, int textViewResourceId,
List<Gold> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.subjects = objects;
}
#Override
public int getCount() {
return this.subjects.size();
}
#Override
public Gold getItem(int index) {
return this.subjects.get(index);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d("ExamAdapter", "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_gold, parent, false);
Log.d("ExamAdapter", "Successfully completed XML Row Inflation!");
}
// Get item
Gold text = getItem(position);
subject = (TextView) row.findViewById(R.id.textView1);
time = (TextView) row.findViewById(R.id.textView2);
String content = text.content;
String times = text.time;
subject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
name = getItem(position).id.toString();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Delete");
// set dialog message
alertDialogBuilder
.setMessage("This item will be deleted")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, close
// current activity
new DeleteProduct().execute();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
subject.setText(content.replace("*", "\n"));
return row;
}
Plz help me to show the alert dialog in this class
I found the answer. And i am really happy to share with you,
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
v.getRootView().getContext());
Use v.getRootView().getContext() instead context or v.getContext()
Try this
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( DeteteAdapter.this);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
change this line like ;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
(Activity)context);
maybe it can help you
I'm creating a custom Dialog that is started by a custom spinner. What I was trying to do is customize the dialog the spinner calls. However, there is an annoying space in the dialog. I've tryied all my resources to fix it, but nothing. I also followed this question's answer but didn't solve.
In the spinner xml file I pass it like this. It references the following class named CustomSpinner, that extends a Spinner:
<com.myproject.CustomSpinner
android:id="#+id/customSpinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="13dp"
android:prompt="#string/my_spinner"/>
And I have this class that is my custom dialog class:
public class CustomSpinnerDialog extends Dialog implements OnItemClickListener, View.OnClickListener
{
private OnItemSelectedListener onItemSelectedListener;
public DialogInterface.OnClickListener mListener;
public Context mContext;
public interface OnItemSelectedListener
{
public void onItemSelected(String itemValue);
}
public CustomSpinnerDialog(Context context, CustomSpinner.SpinnerAdapter spinnerAdapter, DialogInterface.OnClickListener listener)
{
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.custom_spinner);
mListener = listener;
mContext = context;
ListView listView = (ListView) this.findViewById(R.id.listview);
listView.setAdapter(spinnerAdapter);
listView.setOnItemClickListener(this);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
public void setOnItemSelectedListener(OnItemSelectedListener listener)
{
this.onItemSelectedListener = listener;
}
#Override
public void onClick(View v)
{
if(mListener != null)
mListener.onClick(this, DialogInterface.BUTTON_POSITIVE);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(mListener != null)
mListener.onClick(this, position);
String text = (String) parent.getItemAtPosition(position);
onItemSelectedListener.onItemSelected(text);
}
public void setDialogTitle(String title)
{
TextView titleText = (TextView) this.findViewById(R.id.titleText);
titleText.setText(title);
}
}
And this is my custom spinner:
public class CustomSpinner extends Spinner implements DialogInterface.OnClickListener
{
public Context mContext;
public String[] mDataList;
public CustomSpinner(Context context, AttributeSet attrs)
{
super(context, attrs);
this.mContext = context;
}
#Override
public boolean performClick()
{
boolean handled = false;
if (!handled)
{
handled = true;
CustomSpinnerDialog dialog = new CustomSpinnerDialog(mContext, (ListAdapter) getAdapter(), this, R.style.FullHeightDialog);
dialog.setDialogTitle(mContext.getResources().getString((R.string.my_dialog_text)));
dialog.show();
}
return handled;
}
#Override
public void onClick(DialogInterface dialog, int which)
{
setSelection(which);
dialog.dismiss();
}
}
My Spinner is created like this in an Activity:
cSpinner= (CustomSpinner) findViewById(R.id.customSpinner);
cSpinner.setDataList(dataList);
cSpinner.setTag("CustomSpinner");
cSpinner.setOnItemSelectedListener(controller);
Here is a screenshot of how the dialog looks like:
diaPhoto = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
I solved it following the documentation
And based in this code as advised by the documentation link above:
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
(ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();