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
Related
I have a simple app with two screen fragments.
When the used select a button in want to make one or more other buttons visible on the fragment.
I have set the buttons as invisible in the layut.
When the buttons is clicked the emulalator jumps to the Home screen.
The app is still running and if I click the overview button I can restore the app but the buttons is still not visible.
view.findViewById(R.id.btn1B).setOnClickListener(new view.OnClickListener() {
public void onClick(View view) {
Button ButtonID2 = view.findViewById(R.id.btn1C);
ButtonID2.setVisibility(View.VISIBLE);
Button ButtonID3 = view.findViewById(R.id.btn2C);
ButtonID3.setVisibility(View.VISIBLE);
}
});
FirstFragmant.java
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_first, null);
return root;
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
view.findViewById(R.id.button_Start).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
}
});
view.findViewById(R.id.btn1A).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Button ButtonID = view.findViewById(R.id.btn1A);
String buttonText = ButtonID.getText().toString();
//get the current timeStamp
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
MainActivity.gameEvent[0]= strDate;
MainActivity.gameEvent[1] = buttonText;
//CharSequence text = buttonText; //ButtonID.set();
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText( getContext(), strDate + "-" + text, duration);
//toast.show();
}
});
view.findViewById(R.id.btn1B).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Button ButtonID2 = view.findViewById(R.id.btn1C);
//ButtonID2.setBackgroundColor(Color.GRAY);
ButtonID2.setVisibility(View.VISIBLE);
Button ButtonID3 = view.findViewById(R.id.btn2C);
ButtonID3.setVisibility(View.VISIBLE);
Button ButtonID1 = view.findViewById(R.id.btn1B);
String buttonText = ButtonID1.getText().toString();
MainActivity.gameEvent[2] = buttonText;
//CharSequence text = buttonText; //ButtonID.set();
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText( getContext(), MainActivity.gameEvent[0] + "," + MainActivity.gameEvent[1] + "," + MainActivity.gameEvent[2], duration);
//toast.show();
}
});
view.findViewById(R.id.btn1C).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Button ButtonID = view.findViewById(R.id.btn1C);
String buttonText = ButtonID.getText().toString();
CharSequence text = buttonText; //ButtonID.set();
int duration = Toast.LENGTH_SHORT;
MainActivity.gameEvent[3] = buttonText;
Toast toast = Toast.makeText( getContext(), MainActivity.gameEvent[0] + "," + MainActivity.gameEvent[1] + "," + MainActivity.gameEvent[2] + "," + MainActivity.gameEvent[3], duration);
toast.show();
}
});
}
}
This being your first question, welcome to the site.
Did you set R.id.btn1B to be invisible in the layout as well? What you've done here is you've made btn1C and btn2Cto be visible ONLY AFTER you click onbtn1B, since it's in the click listener; but if btn1B` is also not visible, there's nothing to happen.
As a side note, if you're just learning Android now, you should start with Kotlin instead of Java, it's a much easiest experience. I would set up Kotlin, with DataBinding, and this exact same code will look like this:
viewBinding.btn1B.onClick {
viewBinding.btn1C.visibility = View.VISIBLE
viewBinding.btn2C.visibility = View.VISIBLE
}
Using the debugger I was able to get a better understanding of the object structure.
Button ButtonID2 = view.findViewById(R.id.btn1C); was returning a null. setting a property/attribute caused an error.
Button Btn = view.findViewById(R.id.btn1B) returned the button object within/of the OnClickListener
But Button ButtonID2 = view.findViewById(R.id.btn1C); returns a null.
I instead used getParentFragment().getView() to get the fragments view.
Button ButtonID2 = getParentFragment().getView().findViewById(R.id.btn1C);
I want to get the data entered in an edittext of android fragment in that same fragment of android.
I want that input details and send to a ble device.
Code is here:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
setCancelable(false);
View view = inflater.inflate(R.layout.verification, null);
verify=(EditText)view.findViewById(R.id.verify);
Next =(Button) view.findViewById(R.id.next);
Cancel=(Button) view.findViewById(R.id.cancel);
Next.setOnClickListener(this);
Cancel.setOnClickListener(this);
appContext = AppContext.getContext();
mContext=getActivity();
appContext = AppContext.getContext();
mOnDataSendListener = appContext.getOnDataSendListener();
timer();
Time=(TextView) view.findViewById(R.id.time);
return view;
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.next){
factoryReset();
}
else {
dismiss();
}
}
Get verify data when you call method factoryReset() & send data as a parameter. Use below line to getText from editText:
verify.getText().toString()
Try with below code :
#Override
public void onClick(View view) {
if(view.getId()==R.id.next){
factoryReset(verify.getText().toString());
}
else {
dismiss();
}
public void factoryReset(String str1){
Log.e("VERIFY_DATA",""+str1);
}
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?
I have a listview with items. I have developed onitemclick() function with a custom dialog to enter a value. I need to update the listview current item with value we enter in the dialog box.
i have done like this
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showCustomDialog(view);
if(quantity>0){
TextView tv=(TextView)view.findViewById(R.id.row_item_quantity);
tv.setTextColor(R.color.white);
tv.setText(quantity+"");
quantity=0;
Toast.makeText(getActivity(), "entered "+quantity , Toast.LENGTH_SHORT).show();
}
}
showCustomDialog function is
protected void showCustomDialog(View view) {
// TODO Auto-generated method stub
final Dialog dialog;
dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_enter_quantity);
dialog.setCancelable(true);
final EditText editText;
editText = (EditText)dialog.findViewById(R.id.quantity_number);
Button buttonCancel;
buttonCancel = (Button)dialog.findViewById(R.id.quantity_cancel_button);
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button buttonOK;
buttonOK = (Button)dialog.findViewById(R.id.quantity_ok_button);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getActivity(), "entered"+editText.getText().toString() , Toast.LENGTH_SHORT).show();
String text=editText.getText().toString();
if(text=="")
text=""+0;
quantity =Integer.parseInt(text);
//setQuantity(qty);
dialog.dismiss();
}
});
dialog.show();
}
It gets the value and will update on the next item i clicks. How can i correct this problem.
use
tv.setText(String.valueOf(quantity);
instead of
tv.setText(quantity+"");
if you are using array for list data you have to update the list in exact position.then call adapter.notifiDataChanged().If u want to change it temporally use view.invalidate();
I have done it.
As below.
write a custom dialog box with an edittext and two buttons for OK and Cancel.
buttonOK = (Button)dialog.findViewById(R.id.quantity_ok_button);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text;
text=editText.getText().toString();
quantity=text;
//Toast.makeText(getActivity(), "entered"+editText.getText().toString() , Toast.LENGTH_SHORT).show();
setQuantity(quantity,position);
dialog.dismiss();
}
});
void setQuantity(String quantity,int position){
if(!selectedItemsMenu.contains(data))
// lines ///
selectedItemsMenu.add(data);
listMenu.add(position, data);
Log.e("new list size", selectedItemsMenu.size() + "");
adapter.notifyDataSetChanged();
i am creating my custom EditText which validate email and other things on focus lost and if it is not valid then focus back. It works fine if i have only one EditText but when i have multiple EditText it infinity focuses between my editText boxes as it try to check validation in both. Here is my sample code.
public void init(){
this.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
final MyEditText ed = MyEditText.this;
//...............check require field validation
if(!hasFocus && isRequire){
if(ed.getText().toString().length()<=0){
String msg = "Require Field";
v.clearFocus();
setErrorMsg(ed,msg);
return;
}
}else if(ed.getText().toString().length()>0){
ed.setError(null);
}
}
}
private void setErrorMsg(final EditText ed,String msg){
if(errorMessage!=null && errorMessage.length()>0){
msg = errorMessage;
}
ed.setError(msg);
ed.post(new Runnable() {
public void run() {
ed.requestFocus();
}
});
}
Put onfocus change lisner on the parent view from the viewGroup get the child view and chek it u will get the perticular edittext. i had some requirement like that i solved it this way.
TableLayout tableView = (TableLayout)findViewById(R.id.mydetails_tableview);
View mytempView=null;
int noOfChilds=tableView.getChildCount();
for(int i=0;i<noOfChilds;i++)
{
mytempView=tableView.getChildAt(i);
if(i%2==0)
{
View vv=((TableRow) mytempView).getChildAt(1);
if(vv instanceof EditText)
{
//Log.v("This one is edit text---", "here there");
((EditText) vv).setText("");
}
}
}
boolean pendingFocus = false;
Before
ed.post(new Runnable() {
public void run() {
ed.requestFocus();
}
});
Add
pendingFocus = true;
and Replace:
if(!hasFocus && isRequire){
with
if(!hasFocus && isRequire && !pendingFocus){
Finally reset pendingFocus with a new else statement here:
if(ed.getText().toString().length()<=0){
String msg = "Require Field";
v.clearFocus();
setErrorMsg(ed,msg);
return;
}
}else if(ed.getText().toString().length()>0){
ed.setError(null);
}else{
pedingFocus = false;
}