Cannot access EditText data from AlertDialog in a Fragment [duplicate] - android

This question already has answers here:
EditText on Dialog returns no text
(3 answers)
EditText setText not displaying on a Dialog Fragment
(2 answers)
How to get EditText from fragment
(2 answers)
Closed 5 years ago.
I am looking to create an AlertDialog with two EditTexts. The AlertDialog exists inside of a fragment.
In the onCreateView I am getting a reference both to the layout of the Fragment as well as the Layout I am using for I am using for the AlertDialog.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.daily_tasks, container, false);
View dialogView = inflater.inflate(R.layout.daily_dialog, container, false);
floatDailyButton = (FloatingActionButton) dialogView.findViewById(R.id.floatDailyButton);
taskTitle = (EditText) dialogView.findViewById(R.id.taskTitleEditText);
taskDescription = (EditText) dialogView.findViewById(R.id.taskDescriptionEditText);
floatDailyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Tapped", "tapped");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(R.layout.daily_dialog);
builder.setPositiveButton("Save Tasks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (getText() == true) {
saveData();
} else {
Toast.makeText(getContext(), "Set a title", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
}
});
return view;
When the user presses the 'positive' button in the Dialog, I want to extract the content from the EditTexts:
public boolean getText() {
try {
titleText = taskTitle.getText().toString();
Toast.makeText(getActivity(), titleText, Toast.LENGTH_SHORT).show();
Log.i("title text", titleText);
} catch (Exception e) {
e.printStackTrace();
return false;
}
try {
descriptionText = taskDescription.getText().toString();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
However no matter what value is in these EditTexts, when I hit the positive button, the AlertDialog closes and the value in the EditTexts is null.
What is wrong here?

Related

Alert dialog coming twice when changing from one tab two another tab in android

I am developing one app related to call block.
I have created one
dashboard activity with "three" fragment tabs. Those are like call log
tab, block tab and settings tab. I want to check the name field
condition at settings tab if valid moving to another tab otherwise
showing alert "please enter valid name". If valid name it is going to
another tab successfully. But the name is not valid i want to show
alert dialog and stay at settings tab. But i am getting twice alert
box "please enter valid name". i have checked sites but i am unable to
get the solution, please help me thanks in advance.
My code is here:
public class SettingsFragment extends Fragment{
private TabLayout tabLayout;
private ViewPager viewPager;
private View view;
private EditText et_consumerName;
DashboardActivity activity;
private static final String TAG = "SettingsFragment";
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (DashboardActivity) context;
setHasOptionsMenu(true);
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.settings_fragment_new, container, false);
et_consumerName = (EditText) view.findViewById(R.id.et_consumerName);
tabLayout = (TabLayout) activity.findViewById(R.id.tab_layout);
viewPager = (ViewPager) activity.findViewById(R.id.pager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// when user click on edit text then save button enable and
// i am getting shared preference boolean value.
boolean isSettingsChanged = TCPAApplication.mPref.getBoolean(Constants.IS_SETTINGS_CHANGED, false);
if (isSettingsChanged) {
int settingsPage = 2;
String consumerNam = et_consumerName.getText().toString().trim();
if (BuildConfig.DEBUGLINES) Log.e(TAG, "counsumer name is " + consumerNam);
if (!isConsumerNameValid(consumerNam)) {
viewPager.setCurrentItem(2);
enterFullNameAlert(getString(R.string.please_enter_firstname_and_lastname));
TabLayout.Tab tab1 = tabLayout.getTabAt(settingsPage);
tab1.select();
}
} else {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected (TabLayout.Tab tab){
}
#Override
public void onTabReselected (TabLayout.Tab tab){
}
}
});
return view;
}
private boolean isConsumerNameValid(String fName) {
if (fName.length() > 0 && fName.contains(" ")) {
return true;
}
return false;
}
}
public void enterFullNameAlert(String msg) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage(msg);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
viewPager.setCurrentItem(2);
}
});
try {
AlertDialog dialog = alertDialog.create();
dialog.setCancelable(false);
dialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
"take a global int for position of tab"
in onTabSelected method check
if(globalposition==systemTabPosition)
{
if(checkcondition)
{
tabOther.select();
globalPosition=position;
}
else
enterFullNameAlert();
}
I solved alert dialog twice problem. Thanks for giving response all.
I have taken two global variables and done the below process.
private Boolean dialogShownOnceFullName = false;
private Dialog mdialog;
private int settingsPage = 2;
public void enterFullNameAndDisplayNameAlert(String msg) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage(msg);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
viewPager.setCurrentItem(settingsPage);
}
});
try {
mdialog = alertDialog.create();
if (!mdialog.isShowing() && !dialogShownOnceFullName) {
mdialog.show();
dialogShownOnceFullName = true;
}
mdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialogShownOnceFullName = false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

android studio edittext field value conversion

I have a fragment with a EditText and save button. when user click the save button, it should check whether the edittext value is out of range or the same data type. For this case, the value type should be "FLOAT" and range is "0.00 - 1000.00".
here's my code for the fragment.java.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.field_fragment,container, false);
int field = getArguments().getInt("field");
//Modify label
// TextView fieldLabel = (TextView)v.findViewById(field);
//fieldLabel.setText(MainActivity.pageNames[field]);
return v;
}
public void onStart() {
super.onStart();
//---Button view---
Button save = (Button)
getActivity().findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
Float conductivity = Float.parseFloat(conductivity_field.getText().toString());
if (conductivity > 0.F && conductivity < 1000.F) {
Toast.makeText(getActivity(), "The value is correct", Toast.LENGTH_SHORT).show();
} else {
//conductivity_field.setText(R.string.conductivity_field);//set text of the edittext back to the hint
Toast.makeText(getActivity(), "Wrong value for float", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
Toast.makeText(getActivity(), "Error converting values. Please enter correct value.", Toast.LENGTH_SHORT).show();
}
}
});
}
So i'm trying to display these errors but when i click it , it ignores the if condition and catches the exception and displays "error converting values msg...."
is there any other way?
Replace you code by this code ->
EditText conductivity_field;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.field_fragment,container, false);
conductivity_field = (EditText) v.findViewById(R.id.conductivity_value);
int field = getArguments().getInt("field");
//Modify label
// TextView fieldLabel = (TextView)v.findViewById(field);
//fieldLabel.setText(MainActivity.pageNames[field]);
return v;
}
public void onStart() {
super.onStart();
//---Button view---
Button save = (Button)
getActivity().findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
Float conductivity = Float.parseFloat(conductivity_field.getText().toString());
if (conductivity > 0.F && conductivity < 1000.F) {
Toast.makeText(getActivity(), "The value is correct", Toast.LENGTH_SHORT).show();
} else {
//conductivity_field.setText(R.string.conductivity_field);//set text of the edittext back to the hint
Toast.makeText(getActivity(), "Wrong value for float , BITCH", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
Toast.makeText(getActivity(), "Error converting values. Please enter correct value.", Toast.LENGTH_SHORT).show();
}
}
});
}
Button save;
Edittext conductivity_field;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.field_fragment, container, false);
initViews(view);
return view;
}
public void initViews(View v) {
conductivity_field = (EditText) v.findViewById(R.id.conductivity_value);
save= (Button) v.findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Float conductivity = Float.parseFloat(edittext.getText().toString());
if (conductivity > 0f && conductivity < 1000f) {
Toast.makeText(getActivity(), "The value is correct", Toast.LENGTH_SHORT).show();
} else {
//conductivity_field.setText(R.string.conductivity_field);//set text of the edittext back to the hint
Toast.makeText(getActivity(), "Wrong value for float", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Error converting values. Please enter correct value.", Toast.LENGTH_SHORT).show();
}
}
});
}
initialize the edittext to onCreateView method of fragment and use the reference of edittext to get the entered value,
what you are doing, initializing a new edittext named as conductivity_field and by default its value is blank so you are getting exception while parsing edittext value to float

Android show dialog alert not exit screen after press OK

I have developed a show dialog alert box in a fragment. After pressing the OK button in the box, It does not exits the screen. The show dialog alert keeps prompting on the screen. I don't want to quit the app after pressing OK, but I want it to go back to the HomeScreen. How to make sure that show dialog alert box will exit the screen after pressing OK?
Here is the code
public class FavouriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
private SharedPreference sharedPreference;
private StaggeredGridView mStaggeredView;
TextView tv;
ImageView iv;
String text;
String favouriteUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favourite_staggeredgridview, container, false);
mStaggeredView = (StaggeredGridView) rootView.findViewById(R.id.staggeredview);
mStaggeredView.setOnScrollListener(scrollListener);
sharedPreference = new SharedPreference();
// iv=(ImageView)rootView.findViewById(R.id.imageView);
text = sharedPreference.getValue(getActivity());
sharedPreference.saveFavourite(getActivity(), text);
String[] photoUrl;
photoUrl = new String[10];
if(photoUrl==null){
Toast.makeText(getActivity(),"no favourite list",Toast.LENGTH_SHORT).show();
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (photoUrl.length == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
}
for (int index = 0; index < photoUrl.length; index++) {
photoUrl[index]=text;
if(text==null){
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
else {
StaggeredGridViewItem item;
item = new FavouriteGridItem(getActivity(), photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
}
// URL url = null;
// try {
// url = new URL(text);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
// iv.setImageBitmap(bmp);
return rootView;
}
private void showAlert(String string, String message) {
if (getActivity() != null && !getActivity().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//getActivity().finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
private StaggeredGridView.OnScrollListener scrollListener = new StaggeredGridView.OnScrollListener() {
public void onTop() {
}
public void onScroll() {
}
public void onBottom() {
}
};
#Override
public void onResume() {
super.onResume();
}
}

How to make a Edit-text box in set error message using without toast ( Alter dialog box ) using Android?

Hey every one has i am create rename application in android ,I will set a Edit-text box in set error message using without toast using Alert Dialog box
Sample Code :
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.rename_title);
folderManager = new FolderManager(getActivity());
folderManager.open();
Cursor c = folderManager.queryAll(itemPos);
if (c.moveToFirst()) {
do {
Newnamefolder = c.getString(1);
} while (c.moveToNext());
}
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(Newnamefolder);
alert.setView(input);
alert.setPositiveButton(R.string.rename_position_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Newnamefolder = input.getText().toString();
String Mesage_one = getResources().getString(R.string.folder_already_exit);
String Mesage_two = getResources().getString(R.string.types_minimum_eight_charcter);
String Mesage_three = getResources().getString(R.string.folder_empty);
String Matchnamerename = folderManager.getmatchfoldername(Newnamefolder);
if(Newnamefolder.equals(Matchnamerename))
{
input.setError(Mesage_one);
}
else if(Newnamefolder.length()>12)
{
input.setError(Mesage_two);
}
else if(Newnamefolder.equals(""))
{
input.setError(Mesage_three);
}
else
{
int newfolder = folderManager.update(itemPos,Newnamefolder);
reload();
}
}
});
alert.show();
But the problem once in click the OK button Don't show error message to exit the Alert Dialog box...
give me any solution ... Friends ?
You can extend Dialog and create your own dialog
public class CustomDialog extends Dialog implements View.OnClickListener {
private boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
Button positive = (Button) findViewById(R.id.button_positive);
Button negative = (Button) findViewById(R.id.button_negative);
EditText field = (EditText) findViewById(R.id.field);
positive.setOnClickListener(this);
negative.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_positive:
onPositiveButtonClicked();
break;
case R.id.button_negative:
//onNegativeButtonClicked();
break;
}
}
private void onPositiveButtonClicked() {
if(verifyForm()) {
success = true;
dismiss();
}
}
public boolean isSuccess() {
return success;
}
private boolean verifyForm() {
boolean valid = true;
/* verify each field and setError() if not valid */
if(!TextUtils.isEmpty(field.getText())) { //or any other condition
valid = false;
field.setError("error message");
}
return valid;
}
}
You can show your CustomDialog like this
final CustomDialog customDialog = new CustomDialog();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(customDialog.isSuccess()) {
//update your folder manager
}
}
}
customDialog.show();

EditText getText() returns empty string

I have an activity with a button, when the user clicks on the button, an AlertDialog appear with 2 EditText where you put email and password to login.
When I try to get the text from the EditText i always get only empty strings.
The layout login_alert is the layout of the AlertDialog.
Here the code:
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
String email = ((EditText) view.findViewById(R.id.emailEditText)).getText().toString();
String password = ((EditText) view.findViewById(R.id.passwordEditText)).getText().toString();
System.out.println("DEBUG: "+email+", "+password); // Empty strings
EDIT:
Activity code:
public class MainActivity extends FragmentActivity {
public static final String mAPP_ID = "...";
public static final String USER_DB_URL = "...";
AssetsExtracter mTask;
private MainFragment mainFragment;
private List<User> usersList = new ArrayList<User>();
private User currentUser = null;
private Button labLoginButton;
private EditText emailET;
private EditText passwordET;
private ProgressDialog dialog;
private View alertView; /* THIS IS THE SOLUTION */
boolean userIsLogged = false;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
/*View view = getLayoutInflater().inflate(R.layout.login_alert, null, false); BEFORE*/
alertView = getLayoutInflater().inflate(R.layout.login_alert, null, false);
emailET = (EditText) view.findViewById(R.id.emailEditText);
passwordET = (EditText) view.findViewById(R.id.passwordEditText);
labLoginButton = (Button) findViewById(R.id.loginLabButton);
updateLoginButton();
dialog = new ProgressDialog(this);
dialog.setMessage("Signin in...");
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mTask = new AssetsExtracter();
mTask.execute(0);
}
/* THIS METHOD IS CALLED BY THE LOGIN BUTTON IN THE MAIN ACTIVITY LAYOUT */
public void onLabLoginButtonClick(View v) {
if (userIsLogged) {
currentUser = null;
userIsLogged = false;
updateLoginButton();
Toast.makeText(this, "Disconnected from Lab", Toast.LENGTH_SHORT)
.show();
} else {
/*View messageView = getLayoutInflater().inflate(
R.layout.login_alert, null, false); BEFORE */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon_launcher);
builder.setTitle(R.string.login_string);
builder.setView(alertView); /* USING THE GLOBAL VARIABLE */
builder.setPositiveButton("Sign me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog.show();
// Download user and return a List of User
DownloadFilesAsyncTask task = new DownloadFilesAsyncTask(USER_DB_URL) {
#Override
protected void onPostExecute(final List<User> result) {
usersList = result;
loginCheckRoutine(); //HERE I MANAGE THE LOGIN AND GETTING EMPTY STRING
}
};
task.execute();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create();
builder.show();
}
}
public void updateLoginButton() {
if (userIsLogged) {
labLoginButton.setText(R.string.logout_string);
} else {
labLoginButton.setText(R.string.login_string);
}
}
public void loginCheckRoutine() {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
System.out.println("DEBUG: " + email + ", " + password); // EMPTY
// controllo nella lista se c'รจ l'utente coi dati inseriti
for (int i = 0; i < usersList.size(); i++) {
if (usersList.get(i).getEmail().equals(email)
&& password.equals("admin")) {
currentUser = usersList.get(i);
userIsLogged = true;
updateLoginButton();
dialog.dismiss();
break;
}
}
if (!userIsLogged) {
userIsLogged = false;
updateLoginButton();
dialog.dismiss();
Toast.makeText(MainActivity.this, "Login Failed",
Toast.LENGTH_SHORT).show();
}
}
}
PROBLEM SOLVED, SOLUTION:
In the onCreate() I inflate the alert_dialog layout in a View variable. I made that View variable global (before onCreate()) and then in onLabLoginButtonClick() I don't inflate the view again, but I use that global instantiated in the onCreate(). hope its clear. thank you all!
You getText just after initialization. Untill you have text in xml you won't get the text. In onclick of alertdialog button get the text.
Declare
EdiText ed1,ed2; // before onCreate if in activity and onCraeteView in fragment
as a instance variable
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
ed1= (EditText) view.findViewById(R.id.emailEditText))
ed2 = (EditText) view.findViewById(R.id.emailEditText);
then on Alert dialog Button click
String email = ed1.getText().toString();
String password= ed2.getText().toString()
you must get the text when you click on login button of alert dialog box
the above mentioned code you get text when you show alert dialog it always return always empty string you should follow the following procedure
first you make a custom alert box layout having two edit text and one button
user write text to edittext for login and give password and then click login button
when you call login button click listener you can get text of edittext easyly
You are trying to get the text immediately after you inflated the view. Try doing it when the user clicks the done button instead.
Before onCreate add:
EditText email;
EditText pass;
Add this in your onCreate
etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);
Then add this to when your button is clicked
String email = etEmail.getText().toString();
String pass = etEmail.getText().toString();
Just ensure that the editText.getText.toString() method is inside the OnClick() method, eg:
TextView submit = enquiryFragment.findViewById(R.id.query_submit_button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
query_type = query_type_editText.getText().toString();
query_text = query_editText.getText().toString();
if (query_text.length()!=0 && query_type.length()!=0) {
postQuery(query_type, query_text, store_id);
// Log.e("query_type ",query_type );
}else{
Toast.makeText(getContext(), "Enter something !", Toast.LENGTH_SHORT).show();
}
}
});
Alternatively add a TextChangedListener to you textview to change the change the string every time the textboxtext changes.
A textwatcher is also possible
you should get the text when you click on save or done button.
If you get this text on click of alert dialog button, you may end up taking it multiple times.

Categories

Resources