I am trying to get the EditText values from the RecyclerView(Adapter).
class BillingOrderListHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Product, type,vartie,unitnumber, Total;
LinearLayout CardView;
BillingOrderListHolder (View itemView) {
super(itemView);
Product = itemView.findViewById(R.id.Product);
type = itemView.findViewById(R.id.type);
vartie = itemView.findViewById(R.id.vartie);
unitnumber= itemView.findViewById(R.id.unitnumber);
rate = itemView.findViewById(R.id.rate);
Total= itemView.findViewById(R.id.Total);
rate.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (!charSequence.toString().equalsIgnoreCase("")) {
int result = (dataList.get(getAdapterPosition()).getUnitCount() * Integer.valueOf(charSequence.toString()));
Total.setText(" = Rs:" + String.valueOf(result));
onEditTextChanged.onTextChanged(i, charSequence.toString());
}
dataList.get(getAdapterPosition()).setEditTextValue(rate.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
If the user changes the value in EditText the totall amount gets calculated accordingly. I just want to get the EditText value from the RecyclerView and I generate an Invoice with the total amount.
int sNO = 0, qTY = 0, TotalCharges = 0, Price = 0;
String ProductType, Type, Veriety;
for (int i = 0; i < DeliverOrderlist.size(); i++){
sNO = i + 1;
ProductType = DeliverOrderlist.get(i).getProduct();
Type = DeliverOrderlist.get(i).getType();
serilno.addElement(new Paragraph(String.valueOf(sNO)));
Veriety = DeliverOrderlist.get(i).getVariety();
qTY = DeliverOrderlist.get(i).getUnitCount();
qty.addElement(new Paragraph(String.valueOf(qTY)));
description.addElement(new Paragraph(ProductType + " " + Type + " " + Veriety));
Price = Integer.parseInt(Billing_InvoiceAdapter.dataList.get(i).getEditTextValue());
price.addElement(new Paragraph(String.valueOf(Price)));
int result = qTY * Price;
amount.addElement(new Paragraph(String.valueOf(result)));
TotalCharges += result;
}
When I run the above code, it works fine if I do not change the value in EditText. If I change the value in any one of the EditText in recyclerView, it gets the last EditText box value from the recyclerView and sets that value to the EditText value that I edited. I am sorry if I am not clear with the Information. Am I doing anything wrong? Can
I also tried this but it works only if I edit the value in the EditText. Otherwise it gives null point exception error. anyone help me with this please? Thanks in advance.
you need to null the listener in first in bindviewholder and add listener like below in your bindviewholder method.
billingListHolder.rate.addTextChangedListener(null);
billingListHolder.rate.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (!charSequence.toString().equalsIgnoreCase("")) {
int result = (dataList.get(getAdapterPosition()).getUnitCount() * Integer.valueOf(charSequence.toString()));
Total.setText(" = Rs:" + String.valueOf(result));
onEditTextChanged.onTextChanged(i, charSequence.toString());
}
dataList.get(getAdapterPosition()).setEditTextValue(rate.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
Related
I'm making a search function through editText that listens a key from a TextWatcher. Now what I'm trying to do is that when the user types the key # it will shows a dialog and runs the recyclerview to show the data within the dialog. The problem is I cannot continue typing from the previous activity because it is in the back stack already and the front one is the DialogFragment that I created.
How would I still continue my focus on the previous activity in the editText even if the dialog fragment shows?
sample code from activity that triggers the dialog
edit_text_chatbox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
int lastString = s.length();
Character character = s.charAt(lastString - 1);
Log.i("after", "afterTextChanged: "+character);
if (character.toString().equals("#")){
AltTaggingDialogFragment dialog = AltTaggingDialogFragment.newInstance();
dialog.show(getFragmentManager(), "dialog");
}
}
My DialogFragment (AltTaggingDialogFragment)
public class AltTaggingDialogFragment extends DialogFragment{
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter_message;
RecyclerView.LayoutManager mLayoutManager;
List<UserFriendList> mUserFriendList;
View view;
EditText friend_tagging;
int friend_count = 7;
#Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
Window window = dialog.getWindow();
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.WRAP_CONTENT;
WindowManager.LayoutParams windowParams = window.getAttributes();
windowParams.dimAmount = 0.0f;
dialog.getWindow().setLayout(width,height);
windowParams.gravity = Gravity.BOTTOM;
//windowParams.x = width;
windowParams.y = 90;
if (friend_count >= 7)
windowParams.height = (210 * 4) + 150;
dialog.getWindow().setAttributes(windowParams);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
public static AltTaggingDialogFragment newInstance() {
AltTaggingDialogFragment f = new AltTaggingDialogFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate layout with recycler view
view = inflater.inflate(R.layout.fragment_alt_tagging_dialog, container, false);
friend_tagging = view.findViewById(R.id.friend_tagging);
mRecyclerView = view.findViewById(R.id.alt_tagging_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
friend_tagging.requestFocus();
friend_tagging.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
Toast.makeText(getActivity(), "Toast!", Toast.LENGTH_SHORT).show();
}
});
mUserFriendList = new ArrayList<>();
UserFriendList userFriendList = new UserFriendList();
super.onViewCreated(view, savedInstanceState);
for (int i = 0; i < 8; i++) {
userFriendList.setFirst_name("Mar John");
userFriendList.setLast_name("Saycon");
userFriendList.setUsername("MJ");
mUserFriendList.add(userFriendList);
}
mAdapter_message = new AltTaggingAdapter(getActivity(), mUserFriendList);
mRecyclerView.setAdapter(mAdapter_message);
return view;
}
}
This image shows what I'm trying to do.
Sample Image
How can I retrieve the value from all EditTexts created by the RecyclerView in MainActivity?
In my RecyclerView Adapter I'm extending my inner class:
public class MyPersonalAdapter extends RecyclerView.Adapter<MyPersonalAdapter.MyPersonalViewHolder>
I'm getting a reference to the EditText in that inner class:
class MyPersonalViewHolder extends RecyclerView.ViewHolder {
TextView numberTextView;
EditText nameEditText;
public MyPersonalViewHolder(View itemView) {
super(itemView);
numberTextView = (TextView) itemView.findViewById(R.id.tv_number);
nameEditText = (EditText) itemView.findViewById(R.id.et_name);
}
}
and in my MainActivity I want to use:
for (int i = 0; i < count; i++) {
String name = "Somehow get that name";
cv.put(MyContract.MyEntry.COLUMN_NAME, "name");
}
Got it working, here is the edited code:
mAdapter = new MyClassAdapter(this, mDataset.size);
mRecyclerView.setAdapter(mAdapter);
mRecyclerview.setItemViewCacheSize(mDataset.size());
List<ContentValues> list = new ArrayList<>();
for (int i = 0; i < mDataset.size(); i++) {
View view = recyclerView.getChildAt(i);
EditText nameEditText = (EditText) view.findViewById(R.id.et_name);
String name = nameEditText.getText().toString();
ContentValues cv = new ContentValues();
cv.put(MyContract.MyEntry.COLUMN_NAME, name);
list.add(cv)
}
// I encapsulated this in a try catch
for (ContentValues c:list) {
mDb.insert(MyClassContract.MyClassEntry.TABLE_NAME, null, c);
}
try this:
for(int i=0;i<adapter.getItemCount();i++){
MyPersonalViewHolder viewHolder= (MyPersonalViewHolder )
mRecyclerView.findViewHolderForAdapterPosition(i);
EditText editText=viewHolder.nameEditText;
}
Implement a addTextChangedListener inside bindview method in the recyclerview adapter.
everytime the edittext text is modified in any cell modify the arraylist string at that position.
And later when you need the whole arraylist, just send it back from the adapter class via any public getmethod.
This should be enough.
I created a getData function inside my Adapter class.
public String getData()
{
String s;
s=txt1.getText().toString();
return s;
}
Then in my MainActivity
public void onSave(View view) {
String[] s=new String[length];
for(int i=0;i<ad.getItemCount();i++)
{
s[i]=ad.getData().toString();
}
}
By this, you can save edit text entries in the array.
//So the other day I spend full day to get data(list of edittext) from recyclerview to activity when i press
button in activity
//perform onclick of button
Here is the code in adapter,Did't work with textchange listener..So i had to used textchange listener and setOnfoucusChange(100% working)
holder.mComment.setOnFocusChangeListener(new
View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
/* When focus is lost check that the text field
* has valid values.
*/
if (!hasFocus) {
String data=holder.mComment.getText().toString();
commentList[position]=data;
}
if(position==mList.size()-1){
holder.mComment.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
commentList[position]=s.toString();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
});
Intent intent = new Intent("mrn_intent");
Bundle args = new Bundle();
args.putSerializable("comment_list",(Serializable)commentList);
args.putSerializable("rating_list", (Serializable) mRatingList);
intent.putExtra("BUNDLE_COMMENT",args);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
And in activity write the following code
Bundle args2 = intent.getBundleExtra("BUNDLE_COMMENT");
if(args2!=null){
list = (String[]) args2.getSerializable("comment_list");
Log.d(TAG, "onReceive: list+++=>>>>>>"+list);
}
This worked for me:
mySetEnabled is a method I implemented within my viewHolder.
if(mRecView!=null) {
int size=mRecView.getChildCount();
for (int i = 0; i < size; i++) {
myAdapter.myViewHolder wordView = (myAdapter.myViewHolder)mRecView.findViewHolderForLayoutPosition(i);
if(wordView!=null)
wordView.mySetEnabled(state);
}
}
Try this way,
class MyPersonalViewHolder extends RecyclerView.ViewHolder {
TextView numberTextView;
EditText nameEditText;
public MyPersonalViewHolder(View itemView) {
super(itemView);
numberTextView = (TextView) itemView.findViewById(R.id.tv_number);
nameEditText = (EditText) itemView.findViewById(R.id.et_name);
nameEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
values.add(getAdapterPosition(),s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Also, define a function
public String getValue(int position){
return values.get(position);
}
Now getValue can call from MainActivity.
OK. I had the same problem, but my solution was different and simpler. Basically, I'd a list of objects, and I was using the edittext to update their values. So, to do it correctly, instead of using position, I used a for loop and if I reach the object that have the same name of my textview, I break the loop and update using i as my index. You can see the code that I have been using in my adapter bellow:
int i;
for(i = 0; i<list.size(); i++){
if(list.get(i).getName().equals(holder.name.getText())){
break;
}
}
Commodity updated = list.get(i);
updated.setValor(Float.parseFloat(s.toString())); // recovering value of my edit text
list.set(i, updated);
atualizado[i] = Float.parseFloat(s.toString());
Currently I use a RecyclerView to represent a dynamically configuration list form.
Every configuration item (entry at RecyclerView list) contains one EditText item.
To avoid wrong user input (some fields allow only integer, others only one digit after comma), I've implemented two different TextWatcher-filters which correct illegal input ("DecimalFilterDigitsAfterComma" and "DecimalFilterInteger").
My RecyclerView has 16 configuration items in total, but can only display maximum 8 at one time.
My problem is that the TextWatchers are assigned to specific Items (Integers and Decimal-Point TextEdit). But when I'm scrolling a bit, they change their order, so that Decimal- and Integer-Filters get swapped.
The TextWatcher items will be created inside the ConfigurationAdapter which is a RecyclerView.Adapter. I've event managed that the TextWatcher is only created once for each entry by using the mListConfigInit which is a boolean flag list for the items.
ConfigurationAdapter.java:
public class ConfigurationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
/*
...
*/
private List<ConfigItem> mConfiguration = new ArrayList<>();
// make sure that DecimalFilter is only created once for each item
private List<Boolean> mListConfigInit = new ArrayList<>();
public ConfigurationAdapter() {
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.listitem_configuration,
parent,
false);
final ConfigurationViewHolder vh = new ConfigurationViewHolder(v);
/*
...
*/
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ConfigurationViewHolder vh = (ConfigurationViewHolder) holder;
ConfigItem config = mConfiguration.get(position);
if(config.ShowValueAsFloat()) {
vh.SetTextWatcherType(ConfigurationViewHolder.TextWatcherType.type_FloatActive);
} else {
vh.SetTextWatcherType(ConfigurationViewHolder.TextWatcherType.type_IntActive);
}
// set name and unit
vh.mName.setText(config.mName);
vh.mUnit.setText(config.mUnit);
/*
...
*/
}
#Override
public int getItemCount() {
return mConfiguration.size();
}
public void addConfigItem(ConfigItem item) {
mConfiguration.add(item);
mListConfigInit.add(new Boolean(false));
notifyItemInserted(mConfiguration.size() - 1);
//notifyDataSetChanged();
}
/*
...
*/
}
ConfigurationViewHolder.java (changed according to pskink-comments):
public final class ConfigurationViewHolder extends RecyclerView.ViewHolder implements TextWatcher {
public TextView mName;
public CheckBox mCheckbox;
public SeekBar mSeekbar;
public EditText mValueEditText;
public TextView mUnit;
private List<TextWatcher> mListTextWatchers = new ArrayList<>();
public enum TextWatcherType {
type_FloatActive(0),
type_IntActive(1);
private int mValue;
TextWatcherType(int value) {
mValue = value;
}
int val() { return mValue; }
}
private TextWatcherType mTextWatcherType = TextWatcherType.type_FloatActive;
public ConfigurationViewHolder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.textView_configuration_name);
mValueEditText = (EditText) itemView.findViewById(R.id.editText_configuration_value);
mUnit = (TextView) itemView.findViewById(R.id.textView_configuration_unit);
mCheckbox = (CheckBox) itemView.findViewById(R.id.checkbox_configuration);
mSeekbar = (SeekBar) itemView.findViewById(R.id.seekBar_configuration);
mListTextWatchers.add(0, new DecimalFilterDigitsAfterComma(mValueEditText, 1));
mListTextWatchers.add(1, new DecimalFilterInteger(mValueEditText));
mValueEditText.addTextChangedListener(this);
}
public void SetTextWatcherType(TextWatcherType textWatcherType) {
mTextWatcherType = textWatcherType;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
mListTextWatchers.get(mTextWatcherType.val()).afterTextChanged(editable);
}
}
DecimalFilterInteger.java
public class DecimalFilterInteger implements TextWatcher {
private final static String TAG = ConfigurationAdapter.class.getSimpleName();
private final EditText mEditText;
private String mLastTextValue = new String("");
public DecimalFilterInteger(EditText editText) {
this.mEditText = editText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public synchronized void afterTextChanged(final Editable text) {
String strInput = text.toString().trim();
if(strInput.isEmpty()) {
return;
}
if(strInput.equals(mLastTextValue)) { // return when same value as last time to avoid endless loop
return;
}
if ((strInput.charAt(0) == '.')) { // handle dot at beginning
strInput = "";
}
if(strInput.contains(".")){ // cut trailing comma
String numberBeforeDecimal = strInput.split("\\.")[0];
strInput = numberBeforeDecimal;
}
mEditText.removeTextChangedListener(this);
mEditText.getText().clear(); // do not use setText here to avoid changing the keyboard
mEditText.append(strInput); // back to default (e. g. from 123-mode to abc-mode),
// see: http://stackoverflow.com/questions/26365808/edittext-settext-changes-the-keyboard-type-to-default-from-123-to-abc
mLastTextValue = mEditText.getText().toString();
mEditText.setSelection(mEditText.getText().toString().trim().length());
mEditText.addTextChangedListener(this);
}
}
Many thanks in advance for your help!
The cause of the swap/switching behaviour of the two different TextWatcher-implementations inside the RecyclerView was that I called removeTextChangedListenerand addTextChangedListenerinside their afterTextChanged-methods to avoid retriggering of the afterTextChanged-method.
The best way to avoid retriggering is a simple check if the text changed since the last call:
public class DecimalFilterInteger implements TextWatcher {
private final static String TAG = ConfigurationAdapter.class.getSimpleName();
private final EditText mEditText;
private String mLastTextValue = new String("");
// ...
#Override
public synchronized void afterTextChanged(final Editable text) {
String strInput = text.toString().trim();
if(strInput.isEmpty()) {
return;
}
if(strInput.equals(mLastTextValue)) { // return when same value as last time to avoid endless loop
return;
}
if ((strInput.charAt(0) == '.')) { // handle dot at beginning
strInput = "";
}
if(strInput.contains(".")){ // cut trailing comma
String numberBeforeDecimal = strInput.split("\\.")[0];
strInput = numberBeforeDecimal;
}
//mEditText.removeTextChangedListener(this); // CAUSE OF SWAP-ERROR !!!
mEditText.getText().clear(); // do not use setText here to avoid changing the keyboard
mEditText.append(strInput); // back to default (e. g. from 123-mode to abc-mode),
// see: http://stackoverflow.com/questions/26365808/edittext-settext-changes-the-keyboard-type-to-default-from-123-to-abc
mLastTextValue = mEditText.getText().toString();
mEditText.setSelection(mEditText.getText().toString().trim().length());
//mEditText.addTextChangedListener(this); // CAUSE OF SWAP-ERROR !!!
}
}
I am new in android and I have two activities and each activity contains a recycled view. Now when I clicked on my first activity item, then this will go to new activity and get the result from second recycle view and I need to show this in my first recycle view, I have done all this, but am not able to get the value from second recycled view. How can i do this?
This is my some part of my code
holder.mGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent individual = new Intent(Context, `enter code here`A.class);`enter code here`
individual.putExtra(Constants.REQ_TYPE,mCollectionDate);
individual.putExtra(Constants.GROUP_POSITION,position);
individual.putExtra(Constants.CENTER_POSITION,Selectedposition);
individual.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
((Activity)mContext).startActivityForResult(individual, 200);
//mContext.startActivity(individual);
}
});
}
Thank you!
You have to set a result on the second activity before get back:
Intent intent = new Intent();
intent.putExtra("parameter", response);
setResult(Activity.RESULT_OK, intent);
finish();
And then treat on the first activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( requestCode == 200 && resultCode == Activity.RESULT_OK ) {
<<YOUR PARAMETER>> = data.getExtra("parameter");
}
}
public class ApplicantDetailsAdapter extends RecyclerView.Adapter{
Context mContext;
String mCollectionDate;
public DemandSheetModel.DemandSheetResponse demandSheetResponse;
int selectedCenter,selectedGroup;
SingletonConfig instance = SingletonConfig.getInstance();
public ApplicantDetailsAdapter(DemandSheetModel.DemandSheetResponse response,Context context,String date,int group,int center){
if(response == null){
throw new IllegalArgumentException("List data must not be null");
}
demandSheetResponse = response;
mContext = context;
mCollectionDate = date;
selectedCenter = center;
selectedGroup = group;
}
#Override
public ApplicantViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_activity_individual_applicant,parent,false);
return new ApplicantViewHolder(view);
}
#Override
public void onBindViewHolder(final ApplicantViewHolder holder, int position) {
DemandSheetModel.ApplicantDemandSheet demandSheet = demandSheetResponse.centers_collections_list.get(selectedCenter).jlgs.get(selectedGroup).collection_list.get(position);
instance.setApplicantDemandSheet(demandSheetResponse.centers_collections_list.get(selectedCenter).jlgs.get(selectedGroup).collection_list.get(position));
holder.mIndividualTotalDemand.setText(demandSheet.total_demand);
holder.mIndividualAdvance.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String strAdvance = holder.mIndividualAdvance.getText().toString();
String strpreclosureTotal = holder.mIndividualPreclosure.getText().toString();
String strTotalDemand = holder.mIndividualTotalDemand.getText().toString();
int advanceTotal = strAdvance.trim().length() != 0 ? Integer.parseInt(strAdvance) : 0;
float f1 = Float.parseFloat(strTotalDemand);
int totalDemand = (int) f1;
int preclosureTotal = strpreclosureTotal.trim().length() != 0 ? Integer.parseInt(strpreclosureTotal) : 0;
int total = advanceTotal + preclosureTotal + totalDemand;
holder.mIndividualTotalCollection.setText(String.format("%d", total));
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.mIndividualPreclosure.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String strAdvance = holder.mIndividualAdvance.getText().toString();
String strpreclosureTotal = holder.mIndividualPreclosure.getText().toString();
String strTotalDemand = holder.mIndividualTotalDemand.getText().toString();
float f1 = Float.parseFloat(strTotalDemand);
int totalDemand = (int)f1;
int advanceTotal = strAdvance.trim().length() != 0 ? Integer.parseInt(strAdvance) : 0;
int preclosureTotal = strpreclosureTotal.trim().length() != 0 ? Integer.parseInt(strpreclosureTotal) : 0;
int total = advanceTotal + preclosureTotal+totalDemand;
holder.mIndividualTotalCollection.setText(String.format("%d", total));
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.mIndividualPaid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
instance.getGroupDemandSheet().group_total_collection = holder.mIndividualTotalCollection.getText().toString();
instance.getApplicantDemandSheet().individual_payment = "paid";
}
}
});
holder.mIndividualAttendence.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
instance.getApplicantDemandSheet().individual_attended = "present";
}
else {
instance.getApplicantDemandSheet().individual_attended = "absent";
}
}
});
}
#Override
public int getItemCount() {
int size = 0;
for (int i=0;i<demandSheetResponse.centers_collections_list.size();i++) {
DemandSheetModel.DemandSheet adapter = demandSheetResponse.centers_collections_list.get(i);
for(int j=0;j<adapter.jlgs.size();j++){
size = adapter.jlgs.get(j).collection_list.size();
}
}
return size;
}
public class ApplicantViewHolder extends RecyclerView.ViewHolder {
TextView mIndividual,mIndividualDmandPri,mIndividualDmandInt,mIndividualOverduePri,mIndividualOverdueInt,mIndividualTotalDemand,mIndividualTotalCollection;
EditText mIndividualAdvance,mIndividualPreclosure;
CheckBox mIndividualPaid,mIndividualAttendence;
public ApplicantViewHolder(View itemView) {
super(itemView);
mIndividualTotalDemand = (TextView)itemView.findViewById(R.id.individual_total_demand);
mIndividualAdvance = (EditText)itemView.findViewById(R.id.individual_advance);
mIndividualTotalCollection = (TextView)itemView.findViewById(R.id.individual_advance_total_collection);
mIndividualPaid = (CheckBox)itemView.findViewById(R.id.individual_paid_check);
mIndividualAttendence = (CheckBox)itemView.findViewById(R.id.individual_attendance_check);
mIndividualPreclosure = (EditText)itemView.findViewById(R.id.individual_advance_preclosure);
}
}
I'm very beginner to programming in android. Sorry if my question is obvious.
I have an editText with inputType="numberDecimal". I watch it's changes with TextWatcher, calculating from it's value (Double type), and show it on a TextView. The calculation is OK, except if the editText has the value ".". If the editText has the value ".", the program drops an error (force close).
My question is: how can I set the editText value to "0." with the use of addTextChangedListener if the editText gets the value "."? Have You got for this situacion a best practice? Thanks in advance for Your help.
My code is:
public class ConversionsFragment extends Fragment{
private EditText etDistBase;
private TextView tvMeterResult;
private TextView tvKmResult;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_conversions, container, false);
etDistBase = (EditText) rootView.findViewById(R.id.textEdit_conv_distance);
tvMeterResult = (TextView) rootView.findViewById(R.id.conv_dist_result_meter);
tvKmResult = (TextView) rootView.findViewById(R.id.conv_dist_result_km);
etDistBase.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
calculateConvDistances();
}
});
return rootView;
}
private void calculateConvDistances() {
String baseText = etDistBase.getText().toString();
Double baseValue = 0.0,
meterResult = 0.0,
kmResult = 0.0;
// if (baseText == ".") {
// etDistBase.setText("0.");
// baseText = "0";
// }
if (baseText.length() == 0)
baseText = "0";
if (baseText != null) {
baseValue = Double.parseDouble(baseText);
meterResult = baseValue * 1000;
kmResult = baseValue;
} else {
meterResult = 0.0;
kmResult = 0.0;
}
tvMeterResult.setText(Double.toString(meterResult));
tvKmResult.setText(Double.toString(kmResult));
}
}
Try with this
if( editText.getText().toString().equals(".") ){
editText.setText("0.");
}
write into the afterTextChanged() method.
The working solution was to change the "." text to "0." in the afterTextChanged() method, as follows:
public class ConversionsFragment extends Fragment{
private EditText etDistBase;
private TextView tvMeterResult;
private TextView tvKmResult;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_conversions, container, false);
etDistBase = (EditText) rootView.findViewById(R.id.textEdit_conv_distance);
tvMeterResult = (TextView) rootView.findViewById(R.id.conv_dist_result_meter);
tvKmResult = (TextView) rootView.findViewById(R.id.conv_dist_result_km);
etDistBase.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
if (etDistBase.getText().toString().equals("."))
etDistBase.setText("0.");
etDistBase.setSelection(etDistBase.getText().length());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
calculateConvDistances();
}
});
return rootView;
}
private void calculateConvDistances() {
String baseText = etDistBase.getText().toString();
Double baseValue = 0.0,
meterResult = 0.0,
kmResult = 0.0;
if (baseText.equals(".")) {
baseText = "0";
}
if (baseText.length() == 0)
baseText = "0";
if (baseText != null) {
baseValue = Double.parseDouble(baseText);
meterResult = baseValue * 1000;
kmResult = baseValue;
} else {
meterResult = 0.0;
kmResult = 0.0;
}
tvMeterResult.setText(Double.toString(meterResult));
tvKmResult.setText(Double.toString(kmResult));
}
}