RecyclerView EditText value erase after scrolling - android

EditText input value erase after scrolling down and scrolling up.
I followed many tutorials but nothing worked for me, I tried to implement Textwatcher but I can't perfectly implement it.
Someone please help, I'm stuck with this problem. Please give me a solution if it had multiple edittext too.
here is my adapter code.
public class ClassTestMarkAdapter extends RecyclerView.Adapter<ClassTestMarkAdapter.NviewHolder> {
private Context mCtx;
private List<ClassTestMarkModel> marklist;
public ClassTestMarkAdapter(Context mCtx, List<ClassTestMarkModel> marklist) {
this.mCtx = mCtx;
this.marklist = marklist;
}
#NonNull
#Override
public NviewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int position) {
LayoutInflater inflater =LayoutInflater.from(mCtx);
View v = inflater.inflate(R.layout.class_test_mark_list,null);
NviewHolder holder =new NviewHolder(v,new MyCustomEditTextListener());
return holder;
}
#Override
public void onBindViewHolder(#NonNull final NviewHolder nviewHolder, int position) {
ClassTestMarkModel markModel =marklist.get(position);
nviewHolder.myCustomEditTextListener.updatePosition(nviewHolder.getAdapterPosition());
nviewHolder.wrText.setText(marklist[nviewHolder.getAdapterPosition()]);
nviewHolder.stname.setText(markModel.getUserName());
nviewHolder.stroll.setText(markModel.getRoll());
nviewHolder.wrText.setText(markModel.getMarks());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mCtx);
Long instituteID = prefs.getLong("InstituteID",0);
final String inssid=String.valueOf(instituteID);
final String subId = prefs.getString("subId", "");
final String examids = prefs.getString("examidforct", "");
final String sessionId = prefs.getString("sesId", "");
final String cTMarkID=markModel.getcTMarkID();
final String insCTID=markModel.getInsCTID();
final String userID=markModel.getUserID();
nviewHolder.btnMark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue myRequestQueue = Volley.newRequestQueue(mCtx);
String url = mCtx.getResources().getString(R.string.baseUrlLocal)+"setExamCTMarks";
final String xNon=nviewHolder.wrText.getText().toString();
Double wrsum= Double.valueOf(xNon);
if (wrsum>0){
nviewHolder.btnMark.setText("Success!");
nviewHolder.btnMark.setBackgroundColor(Color.parseColor("#009000"));
}
StringRequest myStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mCtx,"Success! Data Posted Sucessfully",Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mCtx,"Error: Something Wrong...",Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("CTMarkID", cTMarkID);
MyData.put("InsCTID", insCTID);
MyData.put("UserID",userID);
MyData.put("SessionID", sessionId);
MyData.put("SubjectID", subId);
MyData.put("ExamID", examids);
MyData.put("ObtainMarks",xNon);
MyData.put("InstituteID",inssid);
MyData.put("IsAbsent", "");
MyData.put("LoggedUserID", "123");
MyData.put("IP", "123");
return MyData;
}
};
myRequestQueue.add(myStringRequest);
}
});
}
#Override
public int getItemCount() {
return marklist.size();
}
class NviewHolder extends RecyclerView.ViewHolder{
TextView stname, stroll;
LinearLayout parentLayout;
Button btnMark;
EditText wrText;
//String wrMark;
public MyCustomEditTextListener myCustomEditTextListener;
public NviewHolder(#NonNull View itemView, MyCustomEditTextListener myCustomEditTextListener) {
super(itemView);
stname =itemView.findViewById(R.id.clsmarkName);
stroll =itemView.findViewById(R.id.clsmkRoll);
parentLayout = itemView.findViewById(R.id.ctMarkList);
btnMark =itemView.findViewById(R.id.clsmarkBtn);
this.wrText = itemView.findViewById(R.id.editText);
this.myCustomEditTextListener = myCustomEditTextListener;
this.wrText.addTextChangedListener(myCustomEditTextListener);
}
}
private class MyCustomEditTextListener implements TextWatcher {
private int position;
public void updatePosition(int position) {
this.position = position;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
marklist[position] = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
}
}

Update your list item on text change using text watcher after setText to edit text.
Or Alternatively, For best practices use two way data binding to overcome this issue.

Related

Recyclerview not updating on searchview text change

Friends , I have an edittext which is acting like a searchview.On text change,it is fetching data and storing in filterdNames but it is not updating the recyclerview.Kindly help, i am new to andriod.
Here is my recyclerview adapter code-
public class MyCategoryAdaptercheckbox extends RecyclerView.Adapter<MyCategoryAdaptercheckbox.ViewHolder> {
List<GetMyCategoryAdapter> getMyCategoryAdapter;
Context context;
List<String> category_name;
GetMyCategoryAdapter getMyCategoryAdapter1;
public MyCategoryAdaptercheckbox(List<GetMyCategoryAdapter> getMyCategoryAdapter, Context context, List<String> category_name) {
this.getMyCategoryAdapter = getMyCategoryAdapter;
this.context = context;
this.category_name = category_name;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
if (viewHolder instanceof ViewHolder){
}
getMyCategoryAdapter1 = getMyCategoryAdapter.get(i);
((ViewHolder) viewHolder).tv_categorytitle.setText(getMyCategoryAdapter1.getC_name());
((ViewHolder) viewHolder).tv_categoryid.setText(getMyCategoryAdapter1.getC_id());
((ViewHolder) viewHolder).gt= getMyCategoryAdapter1;
}
public void filterList(ArrayList<String> filterdNames) {
this.category_name = filterdNames;
notifyDataSetChanged();
}
}
Here is my GetMyCategoryAdapter class code -
public class GetMyCategoryAdapter {
String c_name,c_id;
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getC_id() {
return c_id;
}
public void setC_id(String c_id) {
this.c_id = c_id;
}
}
And here is the fragment code -
searchView.addTextChangedListener(new TextWatcher() {
#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) {
//after the change calling the method and passing the search input
filter(editable.toString());
}
});
private void filter(String text) {
//new array list that will hold the filtered data
ArrayList<String> filterdNames = new ArrayList<>();
//looping through existing elements
for (String s : category_name) {
//if the existing elements contains the search input
if (s.toLowerCase().contains(text.toLowerCase())) {
//adding the element to filtered list
filterdNames.add(s);
}
}
//calling a method of the adapter class and passing the filtered list
((MyCategoryAdaptercheckbox) MyAdapter).filterList(filterdNames);
}
The problem is in filterList method:
you update category_name, but not getMyCategoryAdapter (which is used in onBindViewHolder). Try change getMyCategoryAdapter as well before notifyDataSetChanged

search is not Working in section RecyclerView

i am trying implement search function in my section recyclerview
its not working but also not showing error...
i try with edittext addTextChangedListener method.
then in adapter add notifydatachanged method.
try with normal recyclerview its working fine but when use with section recyclerview its not working
sorry for bad english
here is mainActivty
here i get data from server and pass to the adapter in this class i am add the method for filter recyclerview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section_rv_search_prac);
init();
initView();
setUpRecyclerView();
tempModels = new ArrayList<TempModel>();
serviceRequest();
searchItem();
}
private void init() {
mAdapter = new ItemRecyclerViewAdapter(SectionRvSearchPrac.this);
}
private void initView() {
mEt_search = findViewById(R.id.et_search_main);
}
///////////////////////////////
private void searchItem() {
mEt_search.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) {
filter(s.toString());
}
});
}
//method for filter list is here..
private void filter(String text) {
ArrayList<TempModel> mFilter_list = new ArrayList<>();
for (TempModel tempModel : tempModels) {
if (tempModel.getName().toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(tempModel);
}
}
Log.d(TAG, "filter: " + mFilter_list);
mAdapter.filterList(mFilter_list);
}
//////////////////
private void setUpRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.sectioned_recycler_view);
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void serviceRequest() {
StringRequest stringRequest =
new StringRequest(
Request.Method.GET,
JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
parseJason(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT)
.show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void parseJason(String response) {
{
Log.d(TAG, "onResponse: " + response);
String[] first;
ArrayList<String> sewction_list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
String data = jsonArray.getString(0);
first = data.split(Pattern.quote("***^^^***"));
myList_sec = new ArrayList<>(Arrays.asList(first));
for (int j = 0; j < myList_sec.size(); j++) {
myList_first =
new ArrayList<>(Arrays.asList(myList_sec.get(j).split(Pattern.quote("^^^^"))));
sewction_list.add(myList_first.get(0));
myList_second =
new ArrayList<>(Arrays.asList(myList_first.get(1).split(Pattern.quote("^^"))));
ArrayList<String> id = new ArrayList<>();
ArrayList<String> url = new ArrayList<>();
ArrayList<String> img = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
for (int i = 0; i < myList_second.size(); i++) {
myList_third =
new ArrayList<>(Arrays.asList(myList_second.get(i).split(Pattern.quote("**"))));
url.add(myList_third.get(0));
img.add(myList_third.get(1));
name.add(myList_third.get(2));
id.add(myList_third.get(3));
tempModels.add(
new TempModel(
myList_third.get(2),
myList_third.get(0),
myList_third.get(1),
myList_third.get(3)));
}
sectionModelArrayList.add(new SectionModel(sewction_list, tempModels));
SectionRecyclerViewAdapter adapter =
new SectionRecyclerViewAdapter(
SectionRvSearchPrac.this, recyclerViewType, sectionModelArrayList);
recyclerView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here is myitemadapter class for child item
public class ItemRecyclerViewAdapter
extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ItemViewHolder> {
private static final String TAG = "adapter";
private Context context;
ArrayList<TempModel> tempModels;
public ItemRecyclerViewAdapter(Context context) {
this.context = context;
}
public void setData(ArrayList<TempModel> data) {
this.tempModels = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_custom_row_layout, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
String path = tempModels.get(position).getImage();
holder.itemLabel.setText(tempModels.get(position).getName());
Picasso.get().load(path).into(holder.imageView);
holder.cardView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {}
});
}
#Override
public int getItemCount() {
return tempModels.size();
}
/// here method for update filter list
public void filterList(ArrayList<TempModel> filterdNames) {
this.tempModels = filterdNames;
notifyDataSetChanged();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemLabel;
ImageView imageView;
CardView cardView;
public ItemViewHolder(View itemView) {
super(itemView);
itemLabel = (TextView) itemView.findViewById(R.id.item_label);
cardView = itemView.findViewById(R.id.cardview);
imageView = itemView.findViewById(R.id.img);
}
}
section model for section item
public class SectionModel {
private ArrayList<String> sectionLabel;
private ArrayList<TempModel> tempModels;
public SectionModel(ArrayList<String> sectionLabel, ArrayList<TempModel> tempModels) {
this.sectionLabel = sectionLabel;
this.tempModels = tempModels;
}
public ArrayList<String> getSectionLabel() {
return sectionLabel;
}
public ArrayList<TempModel> getTempModels() {
return tempModels;
}
}
model class for item
public class TempModel implements Parcelable{
String name;
String url;
String image;
String num;
public TempModel() {
}
public TempModel(String name, String url, String image, String num) {
this.name = name;
this.url = url;
this.image = image;
this.num = num;
}
protected TempModel(Parcel in) {
name = in.readString();
url = in.readString();
image = in.readString();
num = in.readString();
}
public static final Creator<TempModel> CREATOR = new Creator<TempModel>() {
#Override
public TempModel createFromParcel(Parcel in) {
return new TempModel(in);
}
#Override
public TempModel[] newArray(int size) {
return new TempModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
dest.writeString(image);
dest.writeString(num);
}
}
sectionadapter class
public class SectionRecyclerViewAdapter
extends RecyclerView.Adapter<SectionRecyclerViewAdapter.SectionViewHolder> {
private static final String TAG = "section";
class SectionViewHolder extends RecyclerView.ViewHolder {
private TextView sectionLabel, showAllButton;
private RecyclerView itemRecyclerView;
public SectionViewHolder(View itemView) {
super(itemView);
sectionLabel = (TextView) itemView.findViewById(R.id.section_label);
itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler_view);
}
}
private Context context;
private RecyclerViewType recyclerViewType;
private ArrayList<SectionModel> sectionModelArrayList;
public SectionRecyclerViewAdapter(
Context context,
RecyclerViewType recyclerViewType,
ArrayList<SectionModel> sectionModelArrayList) {
this.context = context;
this.recyclerViewType = recyclerViewType;
this.sectionModelArrayList = sectionModelArrayList;
}
#Override
public SectionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rrow, parent, false);
return new SectionViewHolder(view);
}
#Override
public void onBindViewHolder(SectionViewHolder holder, int position) {
final SectionModel sectionModel = sectionModelArrayList.get(position);
holder.sectionLabel.setText(sectionModel.getSectionLabel().get(position));
// recycler view for items
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setNestedScrollingEnabled(false);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
holder.itemRecyclerView.setLayoutManager(gridLayoutManager);
/* set layout manager on basis of recyclerview enum type */
ItemRecyclerViewAdapter adapter = new ItemRecyclerViewAdapter(context);
adapter.setData(sectionModel.getTempModels());
holder.itemRecyclerView.setAdapter(adapter);
}
#Override
public int getItemCount() {
return sectionModelArrayList.size();
}
Your code very confusing so i just write my solution.
public class SomeAdapter extends RecyclerView.Adapter<SomeAdapter.SomeViewHolder> implements Filterable{
...
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
mMainList = mYourJSONResponseList;
FilterResults results = new FilterResults();
ArrayList<YourModel> mFilter_list = new ArrayList<>();
//Place your logic
for (YourModel model : mMainList) {
if(model.getName().
toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(model);
}
}
results.count = mFilter_list.size();
results.values = mFilter_list;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mMainList = (ArrayList<YourModel>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
And add this into your text listener
#Override
public void afterTextChanged(Editable s) {
//Add this
adapter.getFilter().filter(s.toString())
}
NOTE!! You will show mMainList only this list in your RecyclerView, And check nullpointerexceptions

Firebase database my data is not pushing. And getting DatabaseException error when I add a child Manually

Hello I'm using a custom adapter to assign how I handle my firebase objects and then using a dialog to to assign the variables on my fragment. I need help concerning the fact that the data's I'm assigning to is not pushing into my firebase. Can I ask why?
*EDIT ADDDED INFO CLASS AND DATABASE SCHEMA
Codes of my Adapter
public class UserTransactionAdapter extends RecyclerView.Adapter<UserTransactionAdapter.ViewHolder> {
private List<Info> mInfo;
private Callback mCallback;
private DatabaseReference userref;
public UserTransactionAdapter(Callback callback) {
mCallback = callback;
mInfo = new ArrayList<>();
userref = FirebaseDatabase.getInstance().getReference().child("Transactions");
userref.addChildEventListener(new UserChildEventListener());
}
class UserChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Info info = dataSnapshot.getValue(Info.class);
info.setKey(dataSnapshot.getKey());
mInfo.add(0,info);
notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
Info updatedInfo = dataSnapshot.getValue(Info.class);
for (Info info : mInfo){
if (info.getKey().equals(key)){
info.setValues(updatedInfo);
notifyDataSetChanged();
return;
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
for(Info info: mInfo){
if (info.getKey().equals(key)){
mInfo.remove(info);
break;
}
}
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelinfo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Info info = mInfo.get(position);
holder.mNameTextView.setText(info.getName());
holder.mMonthTextView.setText(info.getMonth());
holder.mPayTextView.setText(info.getPay());
holder.mUntilTextView.setText(info.getUntil());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(info);
}
});
}
public void remove(Info info) {
//TODO: Remove the next line(s) and use Firebase instead
userref.child(info.getKey()).removeValue();
}
#Override
public int getItemCount() {
return mInfo.size();
}
public void add(Info info) {
//TODO: Remove the next line(s) and use Firebase instead
userref.push().setValue(info);
}
public void update(Info info, String newName,String newMonth,String newPay, String newUntil) {
//TODO: Remove the next line(s) and use Firebase instead
info.setName(newName);
info.setMonth(newMonth);
info.setPay(newPay);
info.setUntil(newUntil);
userref.child(info.getKey()).setValue(info);
}
public interface Callback {
public void onEdit(Info info);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView mNameTextView;
private TextView mMonthTextView;
private TextView mPayTextView;
private TextView mUntilTextView;
public ViewHolder(View itemView) {
super(itemView);
mNameTextView = (TextView) itemView.findViewById(R.id.nameTxt);
mMonthTextView = (TextView) itemView.findViewById(R.id.monthTxt);
mPayTextView = (TextView) itemView.findViewById(R.id.payTxt);
mUntilTextView = (TextView) itemView.findViewById(R.id.untilTxt);
}
}
And codes of my Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_transaction, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAddEditDialog(null);
}
});
mAdapter = new com.google.firebase.ikuzou.database.UserTransactionAdapter(this);
RecyclerView view1 = (RecyclerView) view.findViewById(R.id.recycler_view);
view1.setLayoutManager(new LinearLayoutManager(getContext()));
view1.setHasFixedSize(true);
view1.setAdapter(mAdapter);
return view;
}
private void showAddEditDialog(final Info info) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getString(info == null ? R.string.dialog_add_title2 : R.string.dialog_edit_title2));
View view = getLayoutInflater().inflate(R.layout.dialog_info, null, false);
builder.setView(view);
final EditText nameEditText = (EditText) view.findViewById(R.id.nameEditText);
final EditText monthEditText = (EditText) view.findViewById(R.id.monthEditText);
final EditText payEditText = (EditText) view.findViewById(R.id.payEditText);
final EditText untilEditText = (EditText) view.findViewById(R.id.untilEditText);
if (info != null) {
// pre-populate
nameEditText.setText(info.getName());
monthEditText.setText(info.getMonth());
payEditText.setText(info.getPay());
untilEditText.setText(info.getUntil());
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// empty
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// empty
}
#Override
public void afterTextChanged(Editable s) {
String name = nameEditText.getText().toString();
String month = monthEditText.getText().toString();
String pay = payEditText.getText().toString();
String until = untilEditText.getText().toString();
mAdapter.update(info, name,month,pay,until );
}
};
nameEditText.addTextChangedListener(textWatcher);
monthEditText.addTextChangedListener(textWatcher);
payEditText.addTextChangedListener(textWatcher);
untilEditText.addTextChangedListener(textWatcher);
}
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (info == null) {
String name = nameEditText.getText().toString();
String month = monthEditText.getText().toString();
String pay = payEditText.getText().toString();
String until = untilEditText.getText().toString();
mAdapter.add(new Info(name, month,pay,until));
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.create().show();
Can I know the errors on my codes so that I can know why this is happening? Or perhaps is it because I still haven't created a transaction node yet that's why this is happening?
EDIT
I tried to add child nodes manually and now I'm getting
DatabaseException: Can't convert object of type java.lang.String to
type error
Here is my info class codes
public class Info {
private String name,month,pay,until,key;
public Info (){
}
public Info(String name, String month, String pay, String expire) {
this.name= this.name;
this.month= this.month;
this.pay= this.pay;
this.until= this.until;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getMonth(){
return month;
}
public void setMonth(String month){
this.month=month;
}
public String getPay(){
return pay;
}
public void setPay(String pay){
this.pay=pay;
}
public String getUntil(){
return until;
}
public void setUntil(String until){
this.until=until;
}
#Exclude
public String getKey(){
return key;
}
public void setKey(String key){
this.key = key;
}
public void setValues(Info updatedInfo) {
this.name=updatedInfo.name;
this.month=updatedInfo.month;
this.pay=updatedInfo.pay;
this.until=updatedInfo.until;
}
My Database
You have added a childEventListner and all of these functions will only run when a child is added,removed or changed under the node "Transactions". So try adding a child to the node "Transactions".
According to the docs, child_added is triggered once for each existing child and then again every time a new child is added to the specified path.
Ref: https://firebase.google.com/docs/database/admin/retrieve-data
userref.child(info.getKey()).setValue(info);
this line should be like this.
userref.child(info.getKey()).push().setValue(info);
FIXED IT. It was a stupid mistake by me from my Info.class
Added a this.
public Info(String name, String month, String pay, String expire) {
this.name= this.name;
this.month= this.month;
this.pay= this.pay;
this.until= this.until;
Instead of
this.name= name;
this.month= month;
this.pay= pay;
this.until= until;
So solution was removing the this and simply put month,pay,until
Problem is fixed now by removing this

Use of different TextWatcher-implementations inside RecyclerView.Adapter

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 !!!
}
}

Add numbers from EditTexts

I've created an Activity where I've got an "Add subject" button. When I press it, it creates an item in a ListView, which is formed by an EditText where the user enters a number.
What I want to do is to add the numbers inside the EditTexts of each item created, depending if the user has created 3, 4, 5, etc. items in the ListView, via button.
Here is the code of the Activity:
public class PersActivity extends Activity {
Button start, calcaverage1;
private SubjectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
ListView atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
}
Here is the code of the adapter:
public class SubjectAdapter extends ArrayAdapter<Mark> {
protected static final String LOG_TAG = SubjectAdapter.class.getSimpleName();
private List<Mark> items;
private int layoutResourceId;
private Context context;
public SubjectAdapter(Context context, int layoutResourceId, List<Mark> items) {
super(context, layoutResourceId, items);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MarkHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MarkHolder();
holder.Mark = items.get(position);
holder.removePaymentButton = (ImageButton)row.findViewById(R.id.remove);
holder.removePaymentButton.setTag(holder.Mark);
holder.name = (TextView)row.findViewById(R.id.subjectname);
setNameTextChangeListener(holder);
holder.value = (TextView)row.findViewById(R.id.subjectmark);
setValueTextListeners(holder);
row.setTag(holder);
setupItem(holder);
return row;
}
private void setupItem(MarkHolder holder) {
holder.name.setText(holder.Mark.getName());
holder.value.setText(String.valueOf(holder.Mark.getValue()));
}
public static class MarkHolder {
Mark Mark;
TextView name;
TextView value;
ImageButton removePaymentButton;
}
private void setNameTextChangeListener(final MarkHolder holder) {
holder.name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
holder.Mark.setName(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
private void setValueTextListeners(final MarkHolder holder) {
holder.value.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.Mark.setValue(Double.parseDouble(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading double value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
I've implemented serializable to pass data through the adapter:
public class Mark implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private String name = "";
private double value = 0;
public Mark(String name, double value) {
this.setName(name);
this.setValue(value);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
Hope there's a solution. Thanks!
Here is how you would do it
addNumberFromText()
{
int total=0;
for(int i=0;i<listView.getChildCount();i++)
{
View wantedView = listView.getChildAt(i);
EditText edtText=view.findViewById(R.id.specificEditTextId);
//not checking wheter integer valid or not, Please do so
int value=Integer.parseInt(edtText.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
update your activity from following code
public class PersActivity extends Activity
{
Button start, calcaverage1;
private SubjectAdapter adapter;
ListView atomPaysListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
addNumberFromText()
{
double total=0;
for(int i=0;i<atomPaysListView.getChildCount();i++)
{
View wantedView = atomPaysListView.getChildAt(i);
/*
// if edit text
EditText edt=(EditText)view.findViewById(R.id.editText);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(edt.toString());
*/
//you say edittext, but its a textview or so it seems
TextView txv=(TextView)view.findViewById(R.id.subjectmark);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(txv.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
}

Categories

Resources