EditText value in dialog not being stored - android

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);
...
}

Related

how to call a fragment method in an activity

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.

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)

Unable to refresh the ListView with customAdapter

I have been working and messing with my code from last two days.
I have a List View in a Fragment and a Button .
On clicking a button i add the data to List View entered through Dialog
What I am unable to do is refresh the ListView after clicking Ok Button.
Here is my Code
However it loads when i exit the app and resume again
Any Help will be appreciated
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
final EditText input = new EditText(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
return new AlertDialog.Builder(getActivity())
.setView(input)
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String Value = input.getText().toString();
String normalizednumber = NormalizePhoneUtilities
.normalizePhoneNumber(Value);
ContactModel contactModel = new ContactModel(
"Hitesh", normalizednumber, String
.valueOf(3));
ContactsDatabaseWorker sm = new ContactsDatabaseWorker(
getActivity());
sm.AddSmartContact(contactModel);
databaseWorker = new ContactsDatabaseWorker(
getActivity());
// LinkedList<Cursor> list = new
// LinkedList<Cursor>();
// list=databaseWorker.getAllData();
run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
customAdapter = new CustomCursorAdapter(
getActivity(), databaseWorker
.getAllData());
customAdapter.notifyDataSetChanged();
listview.invalidateViews();
listview.refreshDrawableState();
listview.setAdapter(customAdapter);
}
};
getActivity().runOnUiThread(run);
isModal = false;
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (isModal) // AVOID REQUEST FEATURE CRASH
{
View view = inflater.inflate(R.layout.smartalert_fragment,
container, false);
listview = (ListView) view.findViewById(R.id.lvSmartAlert);
return super.onCreateView(inflater, container, savedInstanceState);
}
View view = inflater.inflate(R.layout.smartalert_fragment, container,
false);
Button bAdd = (Button) view.findViewById(R.id.bAddContact);
bAdd.setOnClickListener(this);
listview = (ListView) view.findViewById(R.id.lvSmartAlert);
new Handler().post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
customAdapter = new CustomCursorAdapter(getActivity(),
databaseWorker.getAllData());
listview.setAdapter(customAdapter);
}
});
return view;
}
Call notifyDataSetChanged (); in adapter.
Your CursorAdapter has a swapCursor() method, which you can use each time you get an updated cursor.

DialogFragment with extra space below ListView

As you can see, below the bottom list element in my ListView, there is excess space I can't seem to be rid of. I've tried Relative and Linearlayout, both look like this. Here's the code:
public class ChooseDialog extends DialogFragment implements
DialogInterface.OnClickListener {
String URLhome;
String Title;
String type;
/* public static ChooseDialog newInstance() {
ChooseDialog dialog = new ChooseDialog();
Log.v("a", "shit runs");
Bundle bundle = new Bundle();
dialog.setArguments(bundle);
return dialog;
}*/
public ChooseDialog(String type) {
this.type = type;
}
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setCancelable(true);
int style = DialogFragment.STYLE_NORMAL, theme = 0;
setStyle(style, theme);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(type);
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
And the code that launches the dialog:
public OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
showNationalityDialog();
}
};
private void showNationalityDialog() {
FragmentManager fm = getSupportFragmentManager();
ChooseDialog nationalityDialog = new ChooseDialog("Nationality");
nationalityDialog.show(fm, "fragment_edit_name");
}
I know this question never drew much attention, but I finally solved the problem.
By using the listview that I created in XML rather than setting the builder's adapter, I managed to get rid of all the excess space.
Here's what the new code looks like:
switch (editText.getId()) {
case (0) :
ListView list = (ListView) dialogLayout.findViewById(R.id.listView1);
list.setAdapter(new ArrayAdapter<String>(activity, R.layout.dialoglist,
activity.getResources().getStringArray(R.array.ageArray)));
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
editText.setText(activity.getResources().getStringArray(R.array.ageArray)[arg2]);
dismiss();
}
});
builder = (Integer.parseInt(android.os.Build.VERSION.SDK) < 11)? new AlertDialog.Builder(activity) :
new AlertDialog.Builder(activity, android.R.style.Theme_Translucent);
builder.setNegativeButton("Cancel", this);
builder.setView(dialogLayout);
return builder.create();
If you are setting a custom view on the alert dialog (via setView()) that ONLY has a ListView then you don't need to use a custom view. The builder will automatically add a ListView into the view if set adapter is called.
The extra space at the end of the list view is probably your custom view with no content.
For example:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AccountChooserListAdapter adapter = new AccountChooserListAdapter(getActivity(), R.layout.choose_account_list_item,
accountMetadataFactory.getAccountsAsList());
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(getActivity().getString(R.string.title_add_account))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listener.onAddAccount(which);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}

Categories

Resources