how to call a fragment method in an activity - android

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.

Related

AlertDialog in Adapter() Error Android Studio

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();

how to call setAction in dialog?

i want to create add data to SQL lite with pop up dialog, in dialog just have one textedit and buttom save. in Snackbar usually use setAction(). but in dialog I don't know how to call "AddData".
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.list_category_expanses, container, false);
mTextMessage = (TextView) view.findViewById(R.id.message);
textSubcategoryExpanses = (AppCompatTextView) view.findViewById(R.id.textSubcategoryExpanses);
recyclerViewCategoryExpanses = (RecyclerView) view.findViewById(R.id.recyclerViewCategoryExpanses);
Button btn1 = view.findViewById(R.id.buttonListCategoryExpanses);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog fbDialogue = new Dialog(getActivity());
fbDialogue.setContentView(R.layout.layout_add_category_expanses);
fbDialogue.setCancelable(true);
fbDialogue.show();
}
});
initObjects();
return view;
}
and i want to call this code AddData to onCreate, this code to save text in sqlLite.
public View.OnClickListener AddData = new View.OnClickListener() {
#Override
public void onClick(View view) {
View customLayoutView = View.inflate(getActivity(), R.layout.layout_add_category_expanses, null);
final EditText edNim = customLayoutView.findViewById(R.id.inputcategoryexpanses);
final AlertDialog.Builder builder;
builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle(R.string.strTitleAlert);
builder.setView(customLayoutView);
builder.setPositiveButton(R.string.btnKlikstr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nim = edNim.getText().toString();
if (databaseHelper.addCategoryExpanses(new CategoryExpanses(nim))) {
getDataFromSQLite();
Toast.makeText(getActivity(), "Data berhasil disimpan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Data gagal disimpan", Toast.LENGTH_LONG).show();
}
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
};
Please help me solve this problem. thank you.
You must do some like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.list_category_expanses, container, false);
mTextMessage = (TextView) view.findViewById(R.id.message);
textSubcategoryExpanses = (AppCompatTextView) view.findViewById(R.id.textSubcategoryExpanses);
recyclerViewCategoryExpanses = (RecyclerView) view.findViewById(R.id.recyclerViewCategoryExpanses);
Button btn1 = view.findViewById(R.id.buttonListCategoryExpanses);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View customLayoutView = View.inflate(getActivity(), R.layout.layout_add_category_expanses, null);
final EditText edNim = customLayoutView.findViewById(R.id.inputcategoryexpanses);
final AlertDialog.Builder builder;
builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle(R.string.strTitleAlert);
builder.setView(customLayoutView);
builder.setPositiveButton(R.string.btnKlikstr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String nim = edNim.getText().toString();
if (databaseHelper.addCategoryExpanses(new CategoryExpanses(nim))) {
getDataFromSQLite();
Toast.makeText(getActivity(), "Data berhasil disimpan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Data gagal disimpan", Toast.LENGTH_LONG).show();
}
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
initObjects();
return view;
}

EditText value in dialog not being stored

I have an application with a listview and a button on screen that opens a dialog box. Dialog box has one EditText field where user can input text and click Add. onClickListener for Add button makes a async call and passes text to api. Problem is EditText value is not being saved. I cant even get it to show in the Log. Im sure Im missing something simple. Your help is imprecated. Here is the code.
SignInActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Log.v("SignInActivity","Activity has began");
final DancerAdapter adapter = new DancerAdapter(this,oneDancerArrayList,1);
Log.v("SignInActivity","DancerAdapter");
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
getGirlList();
nameInput = (EditText) findViewById(R.id.cr_room_name);
loginDancer = (Button) findViewById(R.id.addDancer);
loginDancer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = new AddDancerDialog();
newFragment.show(getFragmentManager(), "newDancer");
}
});
static public class AddDancerDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(R.layout.signin_dialog);
LayoutInflater inflater = LayoutInflater.from(getContext());
final View dialogview = inflater.inflate(R.layout.signin_dialog, null);
//final EditText dancerName = (EditText)dialogview.findViewById(R.id.etDancerName);
builder.setMessage("Login New Dancer")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final ProgressBar newProgress = (ProgressBar)dialogview.findViewById(R.id.progressBar);
final EditText dancerName = (EditText)dialogview.findViewById(R.id.etDancerName);
String nameSubmit = dancerName.getText().toString();
Log.v("SignInActivity-Dialog",nameSubmit);
newProgress.setVisibility(View.VISIBLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("action", "addDancer");
params.put("name",nameSubmit);
Log.v("SignInActivity-Dialog", "Add Dancer Function");
Log.v("SignInActivity-Dialog",dancerName.getText().toString());
client.post("http://peekatu.com/apiweb/girlList.php", params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.v("response", response);
responseString2 = response;
//parseDancerList(response);
Log.v("SignInActivity",response);
}
#Override
public void onFailure(Throwable error, String content) {
Log.v("response", "response failed network error");
//waitncall(true);
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
}
Problem is here:
Here you set a view to dialog
builder.setView(R.layout.signin_dialog);
Then, you search a EditText in this view:
LayoutInflater inflater = LayoutInflater.from(getContext());
final View dialogview = inflater.inflate(R.layout.signin_dialog, null);
final EditText dancerName = (EditText)dialogview.findViewById(R.id.etDancerName);
That dialogView was inflated but it is not the view that was added to
dialog. They are different..
I think you can fix as follows:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = LayoutInflater.from(getContext());
final View dialogview = inflater.inflate(R.layout.signin_dialog, null);
builder.setView(dialogview);
...
}

Android getting the EditText value from an AlertDialog in a Fragment

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.

How to get custom dialog activity while clicking on a button in listview in android?

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)

Categories

Resources