I need help with listview I am using in a fragment. The app reads data from an API and my code works fine. I load 15 items initially and every next time I load 10 items more. However if a request to the API return less than 15 items, it doesn't work. Also, the app fails when the number of items is not a multiple of 15 or 25 or 35. That is because I load 10 items after the initial setup.
I need to modify my code for it to work with any number of list items.
My code is as follows:
(ListaFragment.java) -> Here is the ListFragment
public class ListaFragment extends ListFragment implements OnScrollListener {
public ListaFragment(){}
View rootView;
ListAdapter customAdapter = null;
ListaLugares listaLugares;
// values to pagination
private View mFooterView;
private final int AUTOLOAD_THRESHOLD = 4;
private int MAXIMUM_ITEMS;
private Handler mHandler;
private boolean mIsLoading = false;
private boolean mMoreDataAvailable = true;
private boolean mWasLoading = false;
public int ventana = 0;
public int nInitial;
private Runnable mAddItemsRunnable = new Runnable() {
#Override
public void run() {
customAdapter.addMoreItems(10);
mIsLoading = false;
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_lista, container, false);
if (container != null) {
container.removeAllViews();
}
((MainActivity) getActivity()).setBar();
// read number of places of a category
listaLugares.readNumberOfPlaces();
// set
setNumbersOfItems();
// read the places a insert in a List
listaLugares.readPlaces(15, ventana, listaLugares.idCategoria);
//ventana = ventana + 25;
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listaLugares = ((ListaLugares)getActivity().getApplicationContext());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Context context = getActivity();
mHandler = new Handler();
customAdapter = new ListAdapter(context, listaLugares.lista);
mFooterView = LayoutInflater.from(context).inflate(R.layout.loading_view, null);
getListView().addFooterView(mFooterView, null, false);
setListAdapter(customAdapter);
getListView().setOnScrollListener(this);
}
public void setNumbersOfItems() {
if (listaLugares.totalItems > 100) {
MAXIMUM_ITEMS = 100;
nInitial = 25;
} else {
MAXIMUM_ITEMS = listaLugares.totalItems;
nInitial = listaLugares.totalItems;
}
Log.v("NUMBER OF ITEMS", "Number: " + MAXIMUM_ITEMS + "-"+ nInitial);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//Intent myIntent = new Intent(getActivity(), DetalleActivity.class);
//myIntent.putExtra("param_id", appState.lista.get(position).id);
//getActivity().startActivity(myIntent);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (!mIsLoading && mMoreDataAvailable) {
if (totalItemCount >= MAXIMUM_ITEMS) {
mMoreDataAvailable = false;
getListView().removeFooterView(mFooterView);
} else if (totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem + visibleItemCount) {
ventana = ventana + 10;
listaLugares.readPlaces(10, ventana, listaLugares.idCategoria);
mIsLoading = true;
mHandler.postDelayed(mAddItemsRunnable, 1000);
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Ignore
}
#Override
public void onStart() {
super.onStart();
if (mWasLoading) {
mWasLoading = false;
mIsLoading = true;
mHandler.postDelayed(mAddItemsRunnable, 1000);
}
}
#Override
public void onStop() {
super.onStop();
mHandler.removeCallbacks(mAddItemsRunnable);
mWasLoading = mIsLoading;
mIsLoading = false;
ventana = ventana;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
(ListAdapter.java) -> Method in adapter class to add more items.
public class ListAdapter extends ArrayAdapter<Lugar> {
Context context;
List<Lugar> values;
ListaLugares listaLugares;
private int mCount = 20;
public ListAdapter(Context context, List<Lugar> values) {
super(context, R.layout.row, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
TextView firstText = (TextView) row.findViewById(R.id.titulo);
TextView secondText = (TextView) row.findViewById(R.id.categoria);
firstText.setText(values.get(position).nombre);
secondText.setText(values.get(position).categoriaNombre);
return row;
}
public void addMoreItems(int count) {
mCount += count;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mCount;
}
#Override
public long getItemId(int position) {
return position;
}
}
I acceded to a previous edited version to see some code.
The first call works because you are starting with a value of 15 on initiaItems and you set it on mCount on the ListAdapter constructor.
public ListAdapter(Context context, List<Lugar> values, int count) {
super(context, R.layout.row, values);
this.context = context;
this.values = values;
this.mCount = count;
}
So when android renders the listview, it acces to the function ListAdapter.getCount() and returns mCount (15).
But when you scroll it can call to
public void addMoreItems(int count, int idCategoria) {
appState = ((ListaLugares)getContext().getApplicationContext());
appState.readPlaces(15, mCount, idCategoria);
mCount += count;
notifyDataSetChanged();
}
If the number of items returned by the appState.readPlaces is unknown why are you adding a number to mCount mCount += count;?
If appState.readPlaces returns 14 and count is 15 when the listview is rendered it will suppose there are 15+15 items when there are 15+14 so the last item will crash.
mCount should obtain the length from the object that keeps the data from the API calls, in your case I think it will be appState.lista.
Related
I'm trying to crate something that creates a new ListView item on button press, I thing I have somewhere some bug, but as I'm new to this topic I don't know where.
I've tried rewriting the code several times, I've tried to use notifyDataSetChanged(); - it does nothing
tried googling looking on other topics here...
Here is my MainActivity.java:
public Button btn;
private ListView lv;
private CustomeAdapter customeAdapter;
public ArrayList<EditModel> editModelArrayList;
int populateListMaxNum =3;
int listNumber = populateListMaxNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView);
btn = (Button) findViewById(R.id.btn);
editModelArrayList = populateList();
customeAdapter = new CustomeAdapter(this,editModelArrayList);
lv.setAdapter(customeAdapter);
/* TODO activate button */
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToList();
Toast.makeText(getApplicationContext(), "button", Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<EditModel> populateList(){ //this part works perfectly
ArrayList<EditModel> list = new ArrayList<>();
for(int i = 0; i < populateListMaxNum; i++){
EditModel editModel = new EditModel();
//editModel.setEditTextValue(String.valueOf(i));
list.add(editModel);
}
return list;
}
/*TODO make it work = expand */
private void addToList(){ // this part doesn't work nor it doesn't fail
EditModel editModel = new EditModel();
editModelArrayList.add(editModel);
customeAdapter.notifyDataSetChanged();
}
}
Here is my CustomeAdapter.java class:
public class CustomeAdapter extends BaseAdapter {
private Context context;
public static ArrayList<EditModel> editModelArrayList;
public CustomeAdapter(Context context, ArrayList<EditModel> editModelArrayList) {
this.context = context;
CustomeAdapter.editModelArrayList = editModelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return editModelArrayList.size();
}
#Override
public Object getItem(int position) {
return editModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.editText = convertView.findViewById(R.id.editid);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
holder.editText.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) {
editModelArrayList.get(position).setEditTextValue(holder.editText.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
private class ViewHolder {
protected EditText editText;
}
}
I expect to create a new list item (EditText + TextView) but nothing happens (except the Toast message)
(After some tweaks the app crashes due to arrayindexoutofboundsexception length=3 index=3 error, but not in this setting)
here are up to all files nessessary: https://gist.github.com/Atingas/52778a247a78131e5b8cb0239fa30965
Main linear layout in lv_item.xml has match_parent height. Try change it to wrap_content. It seems like one row is just taking whole screen.
I am doing an app which auto-scrolls images, at the bottom of the screen there is a static layout, which I need to display the value of images that have already passed (i.e. position).
I get the correct value of images passed by implementing :
int position = holder.getAdapterPosition();
in the RecyclerViewListAdapter.java
now I need to display this value in the RecyclerViewListActivity.java
on a text view at the static layout beneath the Recycler view?
public class RecyclerViewListAdapter extends RecyclerView.Adapter {
Context context;
List<Data> dataList;
private SharedPreferences preferences;
public RecyclerViewListAdapter(Context context, List<Data> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_recycler_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.mImage.setImageResource(dataList.get(position).getImage());
holder.mImage.setImageResource(dataList.get(position).getImage());
**int position = holder.getAdapterPosition();**
}
#Override
public int getItemCount() {
if (dataList == null || dataList.size() == 0)
return 0;
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mNumberText,mText;
ImageView mImage;
LinearLayout mLinearLayout;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.quran_page);
mLinearLayout = (LinearLayout) itemView.findViewById(R.id.linearLayout);
}
}
}
public class RecyclerViewListActivity extends AppCompatActivity {
RecyclerView mListRecyclerView;
ArrayList<Data> dataArrayList;
RecyclerViewListAdapter recyclerViewListAdapter ;
Runnable updater;
private boolean isTouch = false;
TextViewRemaining;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_list);
final TextView TextViewRemaining = (TextView) findViewById(R.id.TextViewRemaining);
**TextViewRemaining.setText("Position: "+position);**
initializeView();
mListRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
mListRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(RecyclerViewListActivity.this, "Long press on position :" + position,
Toast.LENGTH_LONG).show();
}
}));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
//#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void initializeView()
{
mListRecyclerView = (RecyclerView) findViewById(R.id.vR_recyclerViewList);
setValues();
}
private void setValues(){
prepareData();
recyclerViewListAdapter = new RecyclerViewListAdapter(RecyclerViewListActivity.this,dataArrayList);
mListRecyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewListActivity.this)); // original
mListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mListRecyclerView.setHasFixedSize(false);
mListRecyclerView.setAdapter(recyclerViewListAdapter);
recyclerViewListAdapter.notifyDataSetChanged();
final int speedScroll = 2000; //default is 2000 it need to be 30000
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
// boolean flag = true;
#Override
public void run() {
boolean x=true;
// while(x) {
if (count < recyclerViewListAdapter.getItemCount()) {
if (count == recyclerViewListAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
}
if (flag) count++;
// else count--;
mListRecyclerView.smoothScrollToPosition(count);
handler.postDelayed(this, speedScroll);
}
};
handler.postDelayed(runnable,speedScroll);
}
private void prepareData(){
dataArrayList = new ArrayList<>();
Data data1 = new Data();
data1.setImage(R.drawable.p1);
dataArrayList.add(data1);
Data data2 = new Data();
data2.setImage(R.drawable.p2);
dataArrayList.add(data2);
Data data3 = new Data();
data3.setImage(R.drawable.p3);
dataArrayList.add(data3);
Data data4 = new Data();
data4.setImage(R.drawable.p4);
dataArrayList.add(data4);
Data data5 = new Data();
data5.setImage(R.drawable.p5);
dataArrayList.add(data5);
}
}
So, How can I show the position value on textView in a real-time, as position is a dynamic value, I expect the output on the textView to change as the images passed to the top.
Many Thanks in advance.
This how I solve my problem:
I save the position value in a power Preference(an easier version of shared Preferences)-many thanks to:
Ali Asadi(https://android.jlelse.eu/powerpreference-a-simple-approach-to-store-data-in-android-a2dad4ddc4ac)
I use a Thread that updates the textview every second-many thanks to:
https://www.youtube.com/watch?v=6sBqeoioCHE&t=149s
Thanks for all.
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 ..
When end items in a ListView, i upload new, and after update adapter:
ListView lvMain = (ListView) findViewById(R.id.list);
boxAdapter = null;
boxAdapter = new BoxAdapter(this, products);
lvMain.setAdapter(boxAdapter);
But after this, elements are loaded but the scroll position the top. Ie the position of ListView is lost, and look again at the beginning of all
How fix it?
BoxAdapter code:
public class BoxAdapter extends BaseAdapter {
private final Context ctx;
private final LayoutInflater lInflater;
private final ArrayList<ItemInfo> objects;
private final int loadCount = 10;
private int count = 10;
private String name, desc;
BoxAdapter(Context context, ArrayList<ItemInfo> products) {
this.ctx = context;
this.objects = products;
this.lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
//return objects.size();
return this.count;
}
// элемент по позиции
#Override
public ItemInfo getItem(int position) {
return objects.get(position);
}
// id по позиции
#Override
public long getItemId(int position) {
return position;
}
public void loadAdditionalItems() {
this.count += this.loadCount;
if (this.count > this.objects.size()) {
this.count = this.objects.size();
}
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = lInflater.inflate(R.layout.item, parent, false);
ItemInfo p = getItem(position);
TextView desc_id = (TextView) view.findViewById(R.id.desc);
if (p.username.contains("null"))
{
name = "Автор: Неизвестен";
}
else
{
name = "Автор: " + p.username;
}
if(!p.description.contains("null"))
{
desc = p.description.replaceAll("<br />", "");
desc = desc.replaceAll(""", "");
}
else
{
desc = "";
desc_id.setVisibility(View.GONE);
}
((TextView) view.findViewById(R.id.name)).setText(name);
((TextView) view.findViewById(R.id.desc)).setText(desc);
return view;
}
}
P.S setOnScrollListener code:
lvMain.setOnScrollListener(new OnScrollListener()
{
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
ListView lvMain = (ListView) findViewById(R.id.list);
if(firstVisibleItem + visibleItemCount >= totalItemCount) {
boxAdapter.loadAdditionalItems();
loading = false;
}
if (!loading && (lvMain.getLastVisiblePosition() + 10) >= (60))
{
new LoadLastestPost().execute();
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
The best solution would be to create a setProducts method in your boxAdapter and then just call boxAdapter.notifyDataSetChanged(). For example:
boxAdapter.setProducts(products);
boxAdapter.notifyDataSetChanged();
If you implement this method, there is no need to call lvMain.setAdapter(boxAdapter) more than once.
To add the setProducts() method to your adapter:
public BoxAdapter extends BaseAdapter {
Context mContext;
ArrayList<ItemInfo> objects;
public BoxAdapter(Context context, ArrayList<ItemInfo> products) {
mContext = context;
objects = products;
}
public View getView(int position, View convertView, ViewGroup parent) {
// inflate and adjust view
}
public int getCount() {
return objects.size();
}
public Object getItem(int position) {
return objects.get(position);
}
public void setProducts(ArrayList<ItemInfo> newData) {
objects = newData;
}
}
Also, I wouldn't use a count variable. I would just use the size method in the ArrayList. I would remove count altogether.
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