How to build a ListView with currency masked EditText - java

I am developping an application that needs a ListView with currency masked EditText and a summary TextView showing the sum of the items.
I made a custom adapter. The currency mask (format BRL R$ 0.000,00) is working.
How to make it sum the values when user types in the EditText of each item?
Here is the code of Adapter:
public AdapterFaturamentoMes(Context context, ArrayList<FaturamentoMes> lista) {
this.context = context;
this.lista = lista;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
FaturamentoMes item = lista.get(position);
View view = convertView;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.layout_lista_faturamento_mes, parent, false);
}
TextView txtFaturamentoMes = view.findViewById(R.id.txtFaturamentoMes);
EditText edFaturamento = view.findViewById(R.id.edFaturamento);
txtFaturamentoMes.setText(String.format(context.getString(R.string.txt_faturamento_mes), numberFormat.format(item.getMes()), numberFormat.format(item.getAno())));
edFaturamento.setText(decimalFormat.format(item.getValor()));
TextWatcher oldListener = (TextWatcher) edFaturamento.getTag();
if (oldListener != null) edFaturamento.removeTextChangedListener(oldListener);
TextWatcher watcher = new TextWatcher() {
double valor;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(atual)) {
edFaturamento.removeTextChangedListener(this);
String texto = s.toString().replaceAll("[.,]", "");
valor = Double.parseDouble("0" + texto);
String valorFormatado = decimalFormat.format(valor/100);
atual = valorFormatado;
edFaturamento.setText(valorFormatado);
edFaturamento.setSelection(valorFormatado.length());
edFaturamento.addTextChangedListener(this);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
edFaturamento.setTag(watcher);
edFaturamento.addTextChangedListener(watcher);
return view;
}
public ArrayList<FaturamentoMes> getLista() {
return lista;
}
#Override
public int getCount() {
return this.lista.size();
}
#Nullable
#Override
public FaturamentoMes getItem(int position) {
return this.lista.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
}

Related

Android - setting a listener on items in each row of ExpandableListView

On each row i have two EditTexts.when i change the first one , i want the other to be changed as well(if needed ,for now just setting there '25' for testing).I am using a viewholder pattern,and setting on each of the first edittexts a TextChangedListener,expecting the second to be changed as well .problem is , whenever i change ANY of the first edittexts on ANY of the rows ,only the edittext on the last row is changed. here is the code of the adapter(listener is in getgroupview):
public class CustomExpandableListAdapterNewWorkout extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<String>> expandableListDetail;
private ChildViewHolder childViewHolder;
private GroupViewHolder groupViewHolder;
public CustomExpandableListAdapterNewWorkout(Context context, List<String> expandableListTitle,
HashMap<String, List<String>> expandableListDetail) {
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
}
#Override
public Object getChild(int listPosition, int expandedListPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.get(expandedListPosition);
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(int listPosition, final int expandedListPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String expandedListText = (String) getChild(listPosition, expandedListPosition);
String categoryName= (String)getGroup(listPosition);
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item_exercises_exercise, null);
childViewHolder = new ChildViewHolder();
childViewHolder.mChildTitle = (TextView) convertView.findViewById(R.id.expandedListItem);
childViewHolder.mChildImage = (ImageView) convertView.findViewById(R.id.ImgExercisePic);
convertView.setTag(childViewHolder);
}
else
{
childViewHolder = (ChildViewHolder) convertView.getTag();
}
childViewHolder.mChildTitle.setText(expandedListText);
childViewHolder.mChildTitle.setTextAppearance(context,R.style.TitleStyle);
return convertView;
}
#Override
public int getChildrenCount(int listPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.size();
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(int listPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String listTitle = (String) getGroup(listPosition);
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_group_new_workout_exercise, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.mGroupTitle = (TextView) convertView.findViewById(R.id.exerciseName);
groupViewHolder.mMinSets = (EditText) convertView.findViewById(R.id.edtMinimumSets);
groupViewHolder.mMaxSets = (EditText) convertView.findViewById(R.id.edtMaxSets);
groupViewHolder.mMinSets.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) {
groupViewHolder.mMaxSets.setText("25");
}
});
convertView.setTag(groupViewHolder);
}
else
{
groupViewHolder = (GroupViewHolder) convertView.getTag();
}
groupViewHolder.mGroupTitle.setText(listTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
public final class GroupViewHolder {
TextView mGroupTitle;
EditText mMinSets;
EditText mMaxSets;
}
public final class ChildViewHolder {
TextView mChildTitle;
ImageView mChildImage;
}
}
probably there is something basic i don't understand about adapters and viewholders, and i would like to know the correct method to address it.
ok my bad.
should have declared "GroupViewHolder groupViewHolder" inside the getGroupView method,this way a new one with a new listener is created each time and affects his corresponding row

Recycler View not calling onBindviewHolder

OnBindViewHolder isn't called when I try to select an element inside the recycler view.
I'm using a horizontal layout with all the elements not showing initially (4 out of 7 elements are showing and when user motions to right the 3 elements alternate).
Usually, when the user clicks an element OnBindViewHolder is supposed to fire but it's not happening for me. The only time it fires is on initialization. Since it doesn't fire I can't click any of the elements inside the recycler view. Maybe it might have to do with my layouts? I'm not sure
MyAdapter
public MyAdapter(){
this.setHasStableIds(true);
}
//Set Keys
public void setSelectionTracker(SelectionTracker<Long> selectionTracker) {
this.mSelectionTracker = selectionTracker;
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
public TextView dayView, numberView;
public View view;
ScheduleDetails scheduleDetails = new ScheduleDetails();
public MyViewHolder(View itemView){
super(itemView);
view = itemView;
dayView = itemView.findViewById(R.id.day);
numberView = itemView.findViewById(R.id.day_number);
}
void bind(int position, String dayInit, String numberInit, Boolean isSelected){
scheduleDetails.position = position;
System.out.println("Hit2: " + scheduleDetails.position);
dayView.setText(dayInit);
numberView.setText(numberInit);
view.setSelected(isSelected);
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails(#NonNull MotionEvent motionEvent){
return scheduleDetails;
}
}
static class ScheduleDetails extends ItemDetailsLookup.ItemDetails<Long>{
int position;
Long identifier;
#Override
public int getPosition() {
return position;
}
#Nullable
#Override
public Long getSelectionKey() {
return identifier;
}
#Override
public boolean inSelectionHotspot(#NonNull MotionEvent e){
return true;
}
}
public MyAdapter(String[] day, String[] number){
days = day;
numbers = number;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_layout, parent, false);
MyViewHolder vh = new MyViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String dayInit = days[position];
String numberInit = numbers[position];
Long positions = (long) position;
System.out.println("Position: " + position);
boolean isSelected = false;
if(mSelectionTracker != null){
if(mSelectionTracker.isSelected(positions)){
isSelected = true;
}
holder.bind(position, dayInit, numberInit, isSelected);
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return days.length;
}
#Override
public long getItemId(int position) {
return position;
}
SOLVED
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String dayInit = days[position];
String numberInit = numbers[position];
Long id = getItemId(position);
boolean isSelected = false;
if(mSelectionTracker != null) {
if (mSelectionTracker.isSelected(id)) {
isSelected = true;
}
}
System.out.println("Here: " + isSelected);
holder.bind(position, id, dayInit, numberInit, isSelected);
}
#Override
public long getItemId(int position) {
return position;
}
I retrieved position from getItemId and put that into my id variable (I used setHasStableIds). Click Listener isn't needed for this implementation. This is for the androidx recyclerview-selection library
Lastly I declared these in MyViewHolder:
scheduleDetails.position = position;
scheduleDetails.identifier = key;

ExpandableListView Not Populating In New Fragment Using FirebaseDatabase

CODE
public class QuestInspectingFragment extends Fragment{
// public static ArrayList<String> mParentStepsList;
public ArrayList<QuestObject> mRealQuests;
public ArrayList<QuestObject> mQuestObjectList;
ExpandableListView ExpListView;
LinearLayout toolBarLayout;
ChildEventListener mStepsListener;
DatabaseReference mStepsReference ;
String referencePath;
QuestExpListAdapter questAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.quest_inspect_fragment,container,false);
referencePath = "versions/"+getArguments().getString("questPath")+"/Steps";
mStepsReference = FirebaseHelper.mDatabase.getReference().child(referencePath);
ExpListView = v.findViewById(R.id.ExpandableList);
mQuestObjectList = new ArrayList<>();
questAdapter = new QuestExpListAdapter(this.getContext(),mQuestObjectList);
createStepsListener();
ExpListView.setAdapter(questAdapter);
return v;
}
#Override
public void onResume() {
super.onResume();
mStepsReference.addChildEventListener(mStepsListener);
}
#Override
public void onPause() {
super.onPause();
mStepsReference.removeEventListener(mStepsListener);
}
public static Fragment createInspectFragment(String pathToQuest){
QuestInspectingFragment questInspectingFragment = new QuestInspectingFragment();
Bundle myBundle = new Bundle();
myBundle.putString("questPath",pathToQuest);
questInspectingFragment.setArguments(myBundle);
return questInspectingFragment;
}
public void createStepsListener(){
mStepsListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//System.out.println((String)dataSnapshot.getKey()+"\n \n \n \n \n \n");
QuestObject mQuest = new QuestObject();
//Populate Step Items
if(dataSnapshot.hasChild("title")){
mQuest.setmStepTitleList((String)dataSnapshot.child("title").getValue());
}else {
mQuest.setmStepTitleList((dataSnapshot.getKey().toUpperCase()));
}
//Populate Substeps Items
if (dataSnapshot.hasChild("Substeps")){
for(DataSnapshot childSnapshot : dataSnapshot.child("Substeps").getChildren()){
System.out.println((String)childSnapshot.getKey()+"\n \n \n \n \n \n");
if(childSnapshot.hasChild("title")){
mQuest.mSubstepTitle.add ((String)childSnapshot.child("title").getValue());
;
}
//populate subsubsteps
if(childSnapshot.hasChild("subsubstep")){
QuestObject.SubsubstepList mList = new QuestObject.SubsubstepList();
for(DataSnapshot subsubstep : childSnapshot.child("subsubstep").getChildren()){
mList.mclassSubstepList.add((String) subsubstep.child("title").getValue());
}
mQuest.mSubSubstep.add(mList);
}
}}
mQuestObjectList.add(mQuest);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
}
}
CustomExpandableListAdapter
public class QuestExpListAdapter extends BaseExpandableListAdapter {
private Context mContext;
ArrayList<QuestObject> mQuestsList;
public QuestExpListAdapter(Context context,ArrayList<QuestObject> newQuestList){
mContext = context;
this.mQuestsList = newQuestList;
}
#Override
public int getGroupCount() {
return mQuestsList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return groupPosition;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder mvh = null;
if(row == null){
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.quest_exp_row1,null);
mvh = new MyViewHolder(row);
row.setTag(mvh);
}else {
mvh = (MyViewHolder) row.getTag();
}
mvh.step.setText("Step "+(groupPosition+1)+":"+mQuestsList.get(groupPosition).mStepTitleList);
return row;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
SubstepExpandableList substepExpList = new SubstepExpandableList(mContext);
substepExpList.setAdapter(new SubstepListAdapter(mContext, mQuestsList.get(groupPosition).mSubstepTitle, mQuestsList.get(groupPosition).mSubSubstep));
substepExpList.setGroupIndicator(null);
return substepExpList;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public class SubstepExpandableList extends ExpandableListView {
public SubstepExpandableList(Context context) {
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//999999 is a size in pixels. ExpandableListView requires a maximum height in order to do measurement calculations.
heightMeasureSpec = MeasureSpec.makeMeasureSpec(999999, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public class SubstepListAdapter extends BaseExpandableListAdapter{
ArrayList<String> myPassedList;
ArrayList<QuestObject.SubsubstepList> mySecondList;
private Context mmContext;
public SubstepListAdapter(Context context, ArrayList<String> myPassedList,ArrayList<QuestObject.SubsubstepList> myList ){
mmContext = context;
this.myPassedList = myPassedList;
this.mySecondList = myList;
}
#Override
public int getGroupCount() {
return myPassedList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
try {
return mySecondList.get(groupPosition).mclassSubstepList.size();
}catch (IndexOutOfBoundsException e){
Toast.makeText(mmContext,"No Further Steps",Toast.LENGTH_SHORT).show();
return 0;
}
//else {
// Toast.makeText(mmContext,"No Further Steps",Toast.LENGTH_SHORT).show();
// return 1;
// }
}
#Override
public Object getGroup(int groupPosition) {
return groupPosition;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder mvh = null;
if(row == null){
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.quest_exp_row2,null);
mvh = new MyViewHolder(row);
row.setTag(mvh);
}else {
mvh = (MyViewHolder) row.getTag();
}
mvh.substep.setText(myPassedList.get(groupPosition));
return row;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder mvh = null;
if(row == null){
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.quest_exp_row3,null);
mvh = new MyViewHolder(row);
row.setTag(mvh);
}else {
mvh = (MyViewHolder) row.getTag();
}
if(mySecondList.get(groupPosition)!= null ) {
if (mySecondList.get(groupPosition).mclassSubstepList.size() !=0){
mvh.subsub.setText(mySecondList.get(groupPosition).mclassSubstepList.get(childPosition));
}}
return row;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
private class MyViewHolder{
TextView step;
TextView substep;
TextView subsub;
MyViewHolder(View v){
step = v.findViewById(R.id.questRow1Text);
substep = v.findViewById(R.id.questRow2Text);
subsub =v.findViewById(R.id.questRow3Text);
}
}
}
public class QuestObject {
public void setmStepTitleList(String mStepTitleList) {
this.mStepTitleList = mStepTitleList;
}
public String mStepTitleList ;
public ArrayList<String> mSubstepTitle = new ArrayList<>();
public ArrayList<SubsubstepList> mSubSubstep = new ArrayList<>();
public static class SubsubstepList{
ArrayList<String> mclassSubstepList = new ArrayList<>();
}
}
DESCRIPTION OF PROBLEM
I have my custom adapter which has a second ExpandableList as children to each parent. I know that it works as i had it successfully populating but ONLY every so often when i clicked (from a listView to create the fragment). To clarify, it wouldnt populate EVERY time the fragment was created, usually i had to create the fragment(empty) , hit the back button, and then re-click on the ListViewItem to re-create it, and most of the time that would populate it.
I used those successful tries to make sure that the actual logic of making the children contain the correct data, but after i got that working, i decided to try to tackle whatever was preventing my ExpList from populating 100% consistently, so i stopped using my static ArrayList mParentStepsList, and instead added the list my QuestObject class but now it isnt populating at all.
Im getting an error about notifyDataSetChanged, saying "
Blockquote
Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131296258, class android.widget.ExpandableListView) with Adapter(class android.widget.ExpandableListConnector"
Blockquote
Below is a list of things i've tried.
Things I've tried
I did some reading and seen things about needing to call notifyDataSetChanged and so ive spent 8 hours placing that method and calling it on my adapter from every which way. I've tried runOnUIThread() 6 ways from sunday and every combination i can think of and quite honestly im just stumped. I hope someone can help me. Thanks so much for your time
I was able to get it working. Im calling notifyDataSetChanged in both onResume() AND in onChildAdded() in the childEventListener.
Im thinking the reason i didn't try this particular way earlier is because i assumed you call notifyDataSetChange after you get done adding a bunch of data, but it appears i was supposed to do it after EVERY individual data change. onChildAdded gets called every time for every child of a DatabaseReference - therefore i should call it everytime in that method
EDIT 1- I didnt need to call it in onResume, and i ALSO made my adapter static. hope this helps someone
mStepsListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//System.out.println((String)dataSnapshot.getKey()+"\n \n \n \n \n \n");
QuestObject mQuest = new QuestObject();
//Populate Step Items
if(dataSnapshot.hasChild("title")){
mQuest.setmStepTitleList((String)dataSnapshot.child("title").getValue());
}else {
mQuest.setmStepTitleList((dataSnapshot.getKey().toUpperCase()));
}
//Populate Substeps Items
if (dataSnapshot.hasChild("Substeps")){
for(DataSnapshot childSnapshot : dataSnapshot.child("Substeps").getChildren()){
System.out.println((String)childSnapshot.getKey()+"\n \n \n \n \n \n");
if(childSnapshot.hasChild("title")){
mQuest.mSubstepTitle.add ((String)childSnapshot.child("title").getValue());
//mSubstepList.add((String)childSnapshot.child("title").getValue());
}
//populate subsubsteps
if(childSnapshot.hasChild("subsubstep")){
QuestObject.SubsubstepList mList = new QuestObject.SubsubstepList();
for(DataSnapshot subsubstep : childSnapshot.child("subsubstep").getChildren()){
mList.mclassSubstepList.add((String) subsubstep.child("title").getValue());
// mSubSubStepList.add((String) subsubstep.child("title").getValue());
}
mQuest.mSubSubstep.add(mList);
}
}}
mQuestObjectList.add(mQuest);
**questAdapter.notifyDataSetChanged();**
}
public void onResume() {
//mQuestObjectList = new ArrayList<>();
super.onResume();
mStepsReference.addChildEventListener(mStepsListener);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
questAdapter.notifyDataSetChanged();
}
});
}
#Override
public void onPause() {
questAdapter.mQuestsList.clear();
super.onPause();
mStepsReference.removeEventListener(mStepsListener);
}

Issues with a tagging system using Autocomplete android

I am trying to implement something similar to facebook's search system, where if a user starts typing in a name it brings autocomplete suggestions based on the letters typed, and with an additional option to search for more results. Each result is an object and not a string, and I have tried adding an extra result for search but every time I click on search or one of the objects a replace text occurs with the object as oppose to the name and I know it is a method of the autocomplete widget. Is there another way to go about it?
Here is my code:
private AutoCompleteTextView sx;
sx = (AutoCompleteTextView) findViewById(R.id.sx);
if(sadapter == null) {
sadapter = new Sadapter(PostActivity.this, usersFound);
sx.setAdapter(sadapter);
}
sx.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) {
if (sx.getText().toString().length() <= 3 && sadapter != null) {
usersFound.clear();
sadapter.notifyDataSetChanged();
}
if (sx.getText().toString().length() > 3) {
usersFound.clear();
sadapter.notifyDataSetChanged();
Log.d(Constants.DEBUG, "Changing text " + s);
sxname = s.toString();
testCreate();
sadapter.notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
sx.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DatabaseUser newAdd = usersFound.get(position);
if(position == searchServerIndex) {
sx.setText(sxname);
usersFound.clear();
sadapter.notifyDataSetChanged();
apiGetPossibleCandidates();
} else {
sx.setText("");
}
}
});
private void testCreate() {
DatabaseUser nuser1 = new DatabaseUser("userid", "pictureid", "Jon");
DatabaseUser nuser2 = new DatabaseUser("userid", "pictureid", "Jonny");
DatabaseUser nuser3 = new DatabaseUser("userid", "pictureid", "Jong");
DatabaseUser nuser4 = new DatabaseUser("userid", "pictureid", "Joan");
DatabaseUser searchServer = new DatabaseUser("SearchId", "pictureid", "Search " + sxname);
usersFound.add(nuser1);
usersFound.add(nuser2);
usersFound.add(nuser3);
usersFound.add(nuser4);
searchServerIndex = usersFound.size();
usersFound.add(searchServer);
if(sadapter != null) {
sadapter.notifyDataSetChanged();
}
}
This is the adapter:
public class Sadapter extends ArrayAdapter<DatabaseUser> {
private Context mContext;
private List<DatabaseUser> usersSearch;
private List<DatabaseUser> usersFiltered;
public Sadapter(Context context, List<DatabaseUser> usersAdded) {
super(context, 0, usersAdded);
mContext = context;
usersSearch = usersAdded;
}
#Override
public int getCount() {
return usersSearch.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.user_autosearch_item, null);
}
//helps for recycling
final ViewHolder holder = new ViewHolder();
holder.userTxt = (TextView) v.findViewById(R.id.userTxt);
v.setTag(holder);
String name = usersSearch.get(position).getName();
holder.userTxt.setText(name);
return v;
}
static class ViewHolder {
TextView userTxt;
}
}
you can override getItem() method in your adapater and return the object of DataBaseUser of particular position from the searchlist.. like
#Override public DatabaseUser getItem(int position) {
return usersSearch.get(position);
}
So from your onClick method you can call this method and it will give you DatabaseUser object from which you can retrive your text. I hope it helps you ..

fill a TextView of activity from any class

I have a class called AdapterFilaProducto.java , class show certain information in the list.
This is my class
public class AdapterFilaProducto extends BaseAdapter {
protected Activity activity;
protected ArrayList<ItemFilaProducto> items;
protected ItemFilaProducto item;
protected String tipo;
protected Mascaras msk = new Mascaras();
public ImageButton btnImDerecha ;
public ImageButton btnImIzquierda;
public TextView producto;
private Venta contex;
TextView precio;
private BaseDataAdapter db;
private TextView precioCantidad;
public AdapterFilaProducto(Activity activity, ArrayList<ItemFilaProducto> items,String tipo) {
this.activity = activity;
this.items = items;
this.tipo = tipo;
}
public AdapterFilaProducto(Activity activity,Venta contex, ArrayList<ItemFilaProducto> items,String tipo) {
this.activity = activity;
this.items = items;
this.tipo = tipo;
this.contex=contex;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return items.get(position).getId();
}
public String getItemProducto(int position) {
return items.get(position).getProducto();
}
public String getItemCantidad(int position) {
return items.get(position).getCantidad();
}
public String getItemPercio(int position) {
return items.get(position).getPrecio();
}
public EditText getItemEdit(int position) {
return items.get(position).getEditTxt();
}
public View getView(int position, View convertView, ViewGroup parent)
{
db = new BaseDataAdapter(activity);
View vi=convertView;
final ItemFilaProducto item = items.get(position);
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_producto, null);
}
btnImDerecha = (ImageButton) vi.findViewById(R.id.BtnDerechaVenta);
btnImIzquierda = (ImageButton) vi.findViewById(R.id.BtnIzquierdaVenta);
TextView producto = (TextView) vi.findViewById(R.id.txtProductoVenta);
item.precio = (TextView) vi.findViewById(R.id.txtCantidadVenta);
item.edtxt = (EditText) vi.findViewById(R.id.editTxtListVenta);
producto.setText(item.getProducto());
Log.i("Precio",item.montoPrecio);
if(item.cantidad.equalsIgnoreCase("0")){
item.precio .setText(item.Precio);
}else
item.precio .setText(item.montoPrecio);
item.edtxt.setText(""+item.cantidad);
btnImDerecha.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(item.edtxt.getText().toString());
i=i+1;
item.edtxt.setText(""+i);
}
});
btnImIzquierda.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int i = Integer.parseInt(item.edtxt.getText().toString());
if(0<i){
i=i-1;
item.edtxt.setText(""+i);
}
}
});
item.edtxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
db.open();
Cursor cur = db.obtenerProductosTipo(tipo,item.getIdPro());
if(cur.moveToFirst()){
int precio = cur.getInt(3);
int cantidad = Integer.parseInt(item.edtxt.getText().toString());
int monto = precio*cantidad;
if(0 < monto){
item.setPrecio(msk.mascaraMontoTxt(String.valueOf(monto)));
item.precio .setText(item.getPrecio());
}
db.actualizarProductoMonto(item.getIdPro(),monto);
db.actualizarProductoCantidad(item.getIdPro(),cantidad);
}
cur.close();
int montoTotal = 0;
Cursor curAll = db.obtenerProductosTipo(tipo);
if(curAll.moveToFirst()){
do{
montoTotal = montoTotal + curAll.getInt(5);
Log.e("CANTIDAD", ""+curAll.getInt(5));
}while(curAll.moveToNext());
}
curAll.close();
try{
db.borrarTablaPar("MONTO");
}catch(Exception e){
}
Log.e("MONTO", ""+montoTotal);
DtoParametro dtoParametro = new DtoParametro();
dtoParametro.ID_PAR = "MONTO";
dtoParametro.VALOR = String.valueOf(montoTotal);
Log.i("MONTO",""+String.valueOf(montoTotal));
db.insertarParametro(dtoParametro);
db.close();
contex.mostrarMonto();
}
});
return vi;
}
}
And I need to do is to show in my main Activity is montoTotal. and display it in a total amount in the Textview for my Principal Activity .We tried several methods but none succeeded.
I would appreciate your help, thanks.
Its really hard to follow your code but you should either be able to make this an inner class of your PrincipalActivity and make montoTotal a member variable so that you can access it from where you need or create an instance of this class that retrieves the variable from a function

Categories

Resources