I am developing an android app for Restaurant Ordering system, Now I want to add some Description for the particular Item so that I had added the Dialogfragment and set it to the Custom Adapter ImageView Click listener, the dialog fragment showing correctly, as well as data, is also passing from edit text, but it shows in the last element of the listview.
I had tried various procedures and method but it still getting the same please help me, guys.
I am attaching the screen shots of my project
New TABLE ACTIVITY WHERE IS LISTVIEW
DIALOG FRAGMENT
AFTER ADDING DIALOG FRAGMENT DATA
Here I am Adding Custom Adapter Code
public class CustomAdapter_MenuList extends BaseAdapter{
Activity activity;
Context CONTEXT;
LayoutInflater layoutInflater;
public List<GetandSet> details;
CustomAdapter_MenuList.ViewHolder viewHolder;
GetandSet getandSet;
TextView GrandTotal;
TextView txtTotalItems;
ArrayList<String>Desciption = new ArrayList<>();
private EditText mInput;
Button btnadd,btnclose;
String desc;
public CustomAdapter_MenuList(Activity activity,Context context, List<GetandSet> details,TextView txtGrandtotal,TextView txttotalitems) {
this.activity = activity;
this.CONTEXT = context;
this.details = details;
this.GrandTotal = txtGrandtotal;
this.txtTotalItems = txttotalitems;
this.layoutInflater = (LayoutInflater) LayoutInflater.from(context);
}
#Override
public int getCount() {
return details.size();
}
#Override
public Object getItem(int position) {
return details.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
getandSet = new GetandSet();
final float menu_rate =
Float.parseFloat(details.get(position).getRate());
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater)CONTEXT.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newtable_template, null);
viewHolder = new CustomAdapter_MenuList.ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (CustomAdapter_MenuList.ViewHolder) convertView.getTag();
}
for(int i = 0 ; i<details.size(); i++)
{
for(int j = i+1; j < details.size(); j++)
{
if(details.get(j).getMenu_id().equals(details.get(i).getMenu_id()))
{
details.remove(j);
j--;
getandSet = details.get(i);
getandSet.Menu_qty = details.get(i).getMenu_qty() + 1;
}
}
}
viewHolder.txtsrno.setText(details.get(position).getMenu_id());
viewHolder.txtsrno.setVisibility(View.INVISIBLE);
viewHolder.txtsrnotem.setText(String.valueOf(position+1));
viewHolder.txtmname.setText(details.get(position).getM_name());
viewHolder.txtrate.setText(details.get(position).getRate());
getandSet = details.get(position);
getandSet.Menu_price = menu_rate * getandSet.Menu_qty;
viewHolder.txtqty.setText(getandSet.Menu_qty+"");
viewHolder.txtprice.setText(getandSet.Menu_price +"");
GrandTotal.setText(String.valueOf(grandTotal(details)));
txtTotalItems.setText(String.valueOf(grandTotal(details,position)));
notifyDataSetChanged();
//Add Button Code
viewHolder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getandSet = details.get(position);
//updateQuantity(position, txtqty,itemrate, 1);
getandSet.Menu_qty = getandSet.Menu_qty + 1;
getandSet.Menu_price = menu_rate * getandSet.Menu_qty;
viewHolder.txtqty.setText(""+getandSet.Menu_qty);
viewHolder.txtprice.setText(getandSet.Menu_price +"");
notifyDataSetChanged();
}
});
//Minus Button
viewHolder.btnsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getandSet = details.get(position);
//updateQuantity(position, txtqty,itemrate, -1);
if(getandSet.Menu_qty > 1)
{
getandSet.Menu_qty = getandSet.Menu_qty - 1;
getandSet.Menu_price = menu_rate * getandSet.Menu_qty ;
viewHolder.txtqty.setText(""+getandSet.Menu_qty);
viewHolder.txtprice.setText(getandSet.Menu_price +"");
notifyDataSetChanged();
}
}
});
//Add Description Button
viewHolder.btn_Desc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(position);
}
});
return convertView;
}
//View Holder Class
private class ViewHolder {
TextView txtsrno,txtmname, txtqty,txtrate,txtprice,txtsrnotem,txtdesc;
Button btnadd,btnsub;
ImageView btn_Desc;
public ViewHolder(View view)
{
txtsrno = (TextView)view.findViewById(R.id.txt_NTsrno);
txtsrnotem = (TextView)view.findViewById(R.id.txt_NT_srno);
txtmname = (TextView)view.findViewById(R.id.txt_NT_Item);
txtqty = (TextView)view.findViewById(R.id.txt_Nt_qty);
txtrate = (TextView)view.findViewById(R.id.txt_Nt_rate);
txtprice = (TextView)view.findViewById(R.id.txt_NT_price);
txtdesc = (TextView)view.findViewById(R.id.txt_NT_desc);
btnadd = (Button)view.findViewById(R.id.btn_add);
btnsub = (Button)view.findViewById(R.id.btn_sub);
btn_Desc = (ImageView) view.findViewById(R.id.img_desc);
}
}
//Grand - Total
private float grandTotal(List<GetandSet> items){
float totalPrice = 0;
for(int i = 0 ; i < items.size(); i++) {
totalPrice += items.get(i).getMenu_price();
}
return totalPrice;
}
//Number of Items
private int grandTotal(List<GetandSet> items,int p){
int totalitems = 0;
for(int i = 0 ; i < items.size(); i++) {
totalitems += 1;
}
return totalitems;
}
private void openDialog(final int position){
LayoutInflater inflater = LayoutInflater.from(activity);
View subView = inflater.inflate(R.layout.dialogfragment_description, null);
mInput = subView.findViewById(R.id.edt_desc);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Add Description");
builder.setView(subView);
final AlertDialog alertDialog = builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
desc = mInput.getText().toString();
//getandSet = details.get(position);
details.get(position).setDes(desc);
viewHolder.txtdesc.setText(details.get(position).getDes().toString());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
builder.show();
}
}
viewHolder.txtdesc.setText(details.get(position).getDes().toString());
notifyDataSetChanged();
Just put this lines after completion of openDialog() method
Related
I face a problem in list view. In my list view have edit text and text view. When i scroll the list my data that is entered in text view has lost the value and show the default value. i have two button in list view i increase the quantity and scroll the list for next product when i come back text view lost the value and show default value 1 . And when i open keyboard for enter data then same issue . please help me.
And its my code
Custom Adapter
private List<ShowProducts> listShowProducts;
private Context context;
private int resource;
private String condition;
String uri;
private static final String TAG = "CustomAdapter";
int i = 0;
float total;
ListView listView;
TextView tvTotal;
float sum = 0;
public CustomAdapter(#NonNull Context context, #LayoutRes int resource, List<ShowProducts> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.listShowProducts = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Nullable
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(resource, parent, false);
{
final ShowProducts showProducts = listShowProducts.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageViewOfSelecteditem);
ImageView plus = (ImageView) view.findViewById(R.id.imageviewPlus);
ImageView minus = (ImageView) view.findViewById(R.id.imageviewminus);
TextView tvSetNameOfSeletedItem = (TextView) view.findViewById(R.id.tvSetNameOfSeletedItem);
TextView tvSetSizeOfSeletedItem = (TextView) view.findViewById(R.id.tvSetSizeOfSeletedItem);
TextView tvSetPriceOfSeletedItem = (TextView) view.findViewById(R.id.tvSetPriceOfSeletedItem);
final TextView tvQunatitySetOfSelectedItem = (TextView) view.findViewById(R.id.tvQunatitySetOfSelectedItem);
for (int a = 0; a < 10; a++) {
Log.d(TAG, "onnnnView: ");
}
Log.d(TAG, "getView: +++++");
tvSetNameOfSeletedItem.setText(showProducts.getProduct_name().toString());
tvSetSizeOfSeletedItem.setText(showProducts.getSize_name());
tvSetPriceOfSeletedItem.setText(String.valueOf(showProducts.getSize_price()).toString());
uri = showProducts.getProduct_photo().toString();
Picasso.with(context).load(uri).into(imageView);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
Log.d(TAG, "getView: ");
if (a <= showProducts.getSize_quantity()) {
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a--;
if (a > 0)
{
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price - showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
}
return view;
}
And activity code
public class SelectedProductFromShopingCartShow extends AppCompatActivity {
ArrayList<ShowProducts> arrayList = new ArrayList<>();
String condition = "SelectedItemsFromShoppingCart";
CustomAdapter customAdapter;
ListView listView;
TextView tvTotal;
EditText etDiscount;
int total;
float sum = 0;
Button discount;
private static final String TAG = "SelectedProductFromShop";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
listView = (ListView) findViewById(R.id.listViewSelectedItemsOfShopingCart);
tvTotal = (TextView) findViewById(R.id.tvTotalShow);
etDiscount = (EditText) findViewById(R.id.etDiscount);
arrayList = (ArrayList<ShowProducts>) getIntent().getSerializableExtra("selectedList");
ShowProducts showProducts = arrayList.get(0);
Log.d(TAG, "onnnnCreate: " + showProducts.getProduct_name());
customAdapter = new CustomAdapter(SelectedProductFromShopingCartShow.this, R.layout.show_selected_item_of_shopingcart, condition, arrayList);
listView.setAdapter(customAdapter);
getTotalListView();
Log.d(TAG, "onnnnCreate: Before inner class");
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(SelectedProductFromShopingCartShow.this);
builder.setTitle("Delete this product");
builder.setMessage("Are you sure you want to delete it?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
customAdapter.notifyDataSetChanged();
Toast.makeText(SelectedProductFromShopingCartShow.this, "item deleted", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.show();
return true;
}
});
}
public void getTotalListView() {
sum = 0;
for (int i = 0; i < arrayList.size(); i++) {
ShowProducts showProducts = arrayList.get(i);
sum = sum + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
And watch this video for understand problems
https://youtu.be/WAjtRkI5dl4
You need to follow viewholder pattern. It will resolve your issue. You can check it here https://developer.android.com/training/improving-layouts/smooth-scrolling.html
The only place you're keeping count is in the view. You should make your count a field in the list item ShowProducts and create a getter & setter. For example, in the plus onClickListener, instead of
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
You'll have
// for example, in the `plus` listener
int a = showProducts.getCount();
a++;
showProducts.setCount(a);
And don't forget
notifyDataSetChanged();
I have an app in which listview with two arraylist suppose 1st "listStorage" and second is "existingDataSet" i have to compare these two arraylist value if found same then enable toggle of that index.
code:-
private LayoutInflater layoutInflater;
private List<AllAppList> listStorage;
private Context mContext;
ArrayList<WhiteListModel> newDataSet, existingDataSet;
private String TAG = AppAdapter.class.getSimpleName();
private MySharedPreference sharedPreference;
private WhiteListModel whiteListModel;
private Gson gson;
public AppAdapter(Context context, List<AllAppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.mContext = context;
existingDataSet = new ArrayList<>();
newDataSet = new ArrayList<>();
gson = new Gson();
sharedPreference = new MySharedPreference(mContext);
whiteListModel = new WhiteListModel();
//retrieve data from shared preference
String jsonScore = sharedPreference.getAppsArrayListData();
Type type = new TypeToken<ArrayList<WhiteListModel>>() {
}.getType();
existingDataSet = gson.fromJson(jsonScore, type);
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Adding items in Dataset
AllAppList appList = listStorage.get(position);
whiteListModel.setName(appList.getName());
whiteListModel.setPackName(appList.getPackName());
if (existingDataSet != null) {
existingDataSet.add(whiteListModel);
saveScoreListToSharedpreference(existingDataSet);
} else {
newDataSet.add(whiteListModel);
saveScoreListToSharedpreference(newDataSet);
}
//Notifying adapter data has been changed.....
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}
}
});
return convertView;
}
/**
* Save list of scores to own sharedpref
*
* #param whiteListApps
*/
private void saveScoreListToSharedpreference(ArrayList<WhiteListModel> whiteListApps) {
Gson gson = new Gson();
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(whiteListApps);
Log.e(TAG, "LIST::" + jsonScore);
//save to shared preference
sharedPreference.saveAppsArrayListData(jsonScore);
}
private static class ViewHolder {
static SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
}
for (int i = 0 ; i < existingDataSet.size() ; i++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(i).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
can you try this? switch should retain its value false if not contains within 2 list when on getView because it trigger several times.
boolean isChecked = false
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
isChecked = true;
}
}
}
listViewHolder.switchCompat.setChecked(isChecked);
this is my first post, and I have a doubt about a listview item management, I have seen some post about recycleView, but I donĀ“t understand yet how to implement it in my problem.
Well, I've got a listView that shows some elements like a shopping car where the user clicks the button autorizarDetalleSolicitud, which opens an alertDialog where an user choices a wished amount of that respective item, so if the amount is bigger than zero, the checkbox changes to state TRUE, but when I test this function, I could see that other checkBoxes are activated (or changes to state TRUE) randomly; i.e. When I input an amount to first item, the state of penultimate checkBox changes to TRUE. Thanks for your attention.
//Button of each listview item
public void autorizarDetalleSolicitud(View v) {
LinearLayout layoutboton = (LinearLayout) v.getParent();
checkBoxelemento = (CheckBox) layoutboton.getChildAt(0);
RelativeLayout relativeLayout = (RelativeLayout) layoutboton.getParent();
TableLayout tableLayout = (TableLayout) relativeLayout.getChildAt(1);
TextView tipoelementotextview = (TextView) tableLayout.findViewById(R.id.tipoelem);
TextView unidadelem = (TextView) tableLayout.findViewById(R.id.unidadelem);
TextView idelem = (TextView) tableLayout.findViewById(R.id.idelem);
TextView cantpedida = (TextView) tableLayout.findViewById(R.id.cantidadelem);
cantautorizadatextview = (TextView) tableLayout.findViewById(R.id.cantautorizado);
final String tipoelemento = tipoelementotextview.getText().toString();
cantidadpedida = Double.parseDouble(cantpedida.getText().toString());
cantidadautorizada = Double.parseDouble(cantautorizadatextview.getText().toString());
idelemento = idelem.getText().toString();
// configura el alert dialog
builder = new AlertDialog.Builder(this);
builder.setMessage(unidadelem.getText() + " a autorizar:");
builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
if (tipoelemento.equals("Material")) {
numberPickerCantidad = new NumberPicker(getApplicationContext());
numberPickerCantidad.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
numberPickerCantidad.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
String[] nums = new String[100];
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.toString(i);
}
numberPickerCantidad.setMinValue(0);
numberPickerCantidad.setMaxValue(nums.length - 1);
numberPickerCantidad.setWrapSelectorWheel(false);
numberPickerCantidad.setDisplayedValues(nums);
if(cantidadautorizada==0){
numberPickerCantidad.setValue(cantidadpedida.intValue());
}else{
numberPickerCantidad.setValue(cantidadautorizada.intValue());
}
builder.setPositiveButton(R.string.agregar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int cantidadautorizada = numberPickerCantidad.getValue();
autorizarCantidad((double)cantidadautorizada,tipoelemento);
}
});
builder.setView(numberPickerCantidad);
} else {
cantreactivosoli = new EditText(getApplicationContext());
cantreactivosoli.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
cantreactivosoli.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
cantreactivosoli.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
if(cantidadautorizada==0){
cantreactivosoli.setText(cantidadpedida + "");
}else{
cantreactivosoli.setText(cantidadautorizada + "");
}
cantreactivosoli.setText(cantidadpedida + "");
builder.setView(cantreactivosoli);
builder.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String cantidadedittext = cantreactivosoli.getText().toString();
if (!cantidadedittext.equals("")) {
Double cantidadingresada = Double.parseDouble(cantidadedittext);
autorizarCantidad(cantidadingresada,tipoelemento);
} else {
Toast toast = Toast.makeText(getApplicationContext(), R.string.error_sincantidad, Toast.LENGTH_SHORT);
toast.show();
}
}
});
builder.setView(cantreactivosoli);
}
builder.show();
}
// Method that saves the input value in an arraylist and implements a setCheck(true) of that itemstrong text
public void autorizarCantidad(Double cantidadingresada, String tipoelemento){
if (cantidadingresada <= cantidadpedida) {
int flag = 0;
for (int indice = 0; indice < elementosrevisados.size(); indice++) {
if (elementosrevisados.get(indice).getId().equals(idelemento)) {
elementosrevisados.get(indice).setCantidadAutorizada(cantidadingresada+"");
if (tipoelemento.equals("Material")) {
cantautorizadatextview.setText(cantidadingresada.intValue()+"");
}else{
cantautorizadatextview.setText(cantidadingresada+"");
}
cantidadpedida = cantidadingresada;
flag=1;
break;
}
}
if(flag==0) {
Elemento elem = new Elemento(idelemento, cantidadpedida + "", cantidadingresada + "");
elementosrevisados.add(elem);
checkBoxelemento.setChecked(true);
if (tipoelemento.equals("Material")) {
cantautorizadatextview.setText(cantidadingresada.intValue()+"");
}else{
cantautorizadatextview.setText(cantidadingresada+"");
}
}
for(int i=0;i<elementosrevisados.size();i++){
Log.e("Elemento revisado: ",elementosrevisados.get(i).toString());
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), R.string.error_cantidadautorizada, Toast.LENGTH_SHORT);
toast.show();
}
}
SOLUTION!
To solve my problem, I based on this answer recording an array with positions of the checkboxes verifying if they were checked, I mean, this a boolean array, and each checkbox has a status TRUE or FALSE. Thanks to #AnshulTyagi
public class ElementoAdapter extends BaseAdapter {
private ArrayList<Boolean> status = new ArrayList<Boolean>();
private static LayoutInflater inflater = null;
private ArrayList<HashMap<String, String>> data;
Activity activity;
CompoundButton.OnCheckedChangeListener miCheckedListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton checkBoxView,boolean isChecked){
int posicioncheck = (Integer)checkBoxView.getTag();
if (checkBoxView.isChecked()) {
status.set(posicioncheck,true);
} else {
status.set(posicioncheck,false);
}
}
};
public ElementoAdapter(Activity activity, ArrayList<HashMap<String, String>> data){
this.activity = activity;
this.data = data;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < data.size(); i++) {
status.add(false);
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View vista = convertView;
ViewHolder holder;
if (vista == null) {
vista = inflater.inflate(R.layout.listitem_elemento,null);
holder = new ViewHolder();
holder.labelIdElemento = (TextView) vista.findViewById(R.id.labelIdElemento);
holder.idElemento = (TextView) vista.findViewById(R.id.idelem);
holder.labelTipo = (TextView) vista.findViewById(R.id.labelTipoElemento);
holder.tipoElemento = (TextView) vista.findViewById(R.id.tipoelem);
holder.labelCodigoElemento = (TextView) vista.findViewById(R.id.labelCodigo);
holder.codigoElemento = (TextView) vista.findViewById(R.id.codigoelem);
holder.labelDescripcionElemento= (TextView) vista.findViewById(R.id.labelDescripcion);
holder.descripcionElemento = (TextView) vista.findViewById(R.id.descripcionelem);
holder.labelMarcaElemento = (TextView) vista.findViewById(R.id.labelMarca);
holder.marcaElemento = (TextView) vista.findViewById(R.id.marcaelem);
holder.labelUnidadMedida = (TextView) vista.findViewById(R.id.labelUnidadMedida);
holder.unidadMedida = (TextView) vista.findViewById(R.id.unidadelem);
holder.checkBoxElemento = (CheckBox) vista.findViewById(R.id.checkBox);
holder.botonElemento = (Button) vista.findViewById(R.id.botonsolic);
vista.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// remove the listener so that it does not get attached to other chechboxes.
holder.checkBoxElemento.setOnCheckedChangeListener(null);
holder.checkBoxElemento.setChecked(status.get(position));
Log.e("check "+position,status.get(position)+"");
}
holder.idElemento.setText(data.get(position).get("idelemento"));
holder.tipoElemento.setText(data.get(position).get("tipoelemento"));
holder.codigoElemento.setText(data.get(position).get("codigoelemento"));
holder.descripcionElemento.setText(data.get(position).get("descripcionelemento"));
holder.marcaElemento.setText(data.get(position).get("marcaelemento"));
holder.unidadMedida.setText(data.get(position).get("unidadmedida"));
Log.e("idelemento creado ",data.get(position).get("idelemento"));
holder.checkBoxElemento.setTag(position);
//add a custom listener
holder.checkBoxElemento.setOnCheckedChangeListener(miCheckedListener);
return vista;
}
static class ViewHolder {
TextView labelIdElemento;
TextView idElemento;
TextView labelTipo;
TextView tipoElemento;
TextView labelCodigoElemento;
TextView codigoElemento;
TextView labelDescripcionElemento;
TextView descripcionElemento;
TextView labelMarcaElemento;
TextView marcaElemento;
TextView labelUnidadMedida;
TextView unidadMedida;
CheckBox checkBoxElemento;
Button botonElemento;
}
}
I have a problem that I have been trying to solve for too long but I can't know what causes the problem.
I have a marks list that contains Test objects and subject strings that I use as sections between marks, I use getClass() method to determine if an object is a string or Test, if it is a string, I hide the test's RelativeLayout, if it is a test then I hide the RelativeLayout of the subject. But when scrolling, items get removed and and re-added randomly.
my adapter's class:
public class MarksAdapter extends RecyclerView.Adapter<MarksAdapter.MyHolder>{
public class MyHolder extends RecyclerView.ViewHolder{
RelativeLayout card;
TextView title;
TextView total;
View divider;
int posito;
RelativeLayout group;
TextView groupTitle;
TextView groupMark;
public MyHolder(View itemView) {
super(itemView);
this.card = (RelativeLayout)itemView.findViewById(R.id.card);
this.title = (TextView)itemView.findViewById(R.id.title);
this.total = (TextView)itemView.findViewById(R.id.mark);
this.divider = itemView.findViewById(R.id.item_divider);
this.group = (RelativeLayout)itemView.findViewById(R.id.group);
this.groupTitle = (TextView)itemView.findViewById(R.id.group_title);
this.groupMark = (TextView)itemView.findViewById(R.id.group_mark);
}
}
final ArrayList marks;
Context ctx;
String selectedSem;
TestDatabase db;
public MarksAdapter(Context c, ArrayList marks,String sem,TestDatabase db,ArrayList<Integer> sections){
this.marks = marks;
ctx = c;
selectedSem = sem;
this.db = db;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyHolder(LayoutInflater.from(ctx).inflate(R.layout.mark_child, parent, false));
}
int lastPosition = -1;
int offset = 0;
#Override
public void onBindViewHolder(final MyHolder holder, final int positioner) {
holder.posito = positioner;
if(marks.get(holder.posito).getClass() == Test.class) {
holder.group.setVisibility(View.GONE);
//mark
final Test test = (Test)marks.get(positioner);
holder.title.setText(test.getName());
holder.total.setText(String.format(ctx.getString(R.string.new_m_sum), test.getMarkGot(), test.getMarkOver()));
//add here
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx,addTest.class);
Test mark = (Test)marks.get(holder.posito);
i.putExtra("t_name",mark.getName());
i.putExtra("subject",mark.getSubject());
i.putExtra("mark_got",mark.getMarkGot());
i.putExtra("mark_over",mark.getMarkOver());
i.putExtra("mode","edit");
i.putExtra("oldId", mark.getId());
ctx.startActivity(i);
}
});
holder.card.setLongClickable(true);
holder.card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final Dialog dialo = new Dialog(ctx);
dialo.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialo.setContentView(R.layout.material_dialog);
TextView title = (TextView) dialo.findViewById(R.id.title);
TextView body = (TextView) dialo.findViewById(R.id.body);
Button negative = (Button) dialo.findViewById(R.id.negative);
negative.setText(ctx.getString(R.string.cancel));
Button positive = (Button) dialo.findViewById(R.id.positive);
positive.setText(ctx.getString(R.string.Delete));
title.setText(ctx.getString(R.string.d));
body.setText(ctx.getString(R.string.q_delete) + " " + test.getName() + " " + ctx.getString(R.string.de_comp));
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialo.dismiss();
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vir) {
TestDatabase tb = new TestDatabase(ctx);
SemesterDatabase semesterDatabase = new SemesterDatabase(ctx);
tb.deleteTest(holder.posito, semesterDatabase.getSelected().getName());
MarksAdapter.this.notifyItemRemoved(holder.posito);
marks.remove(holder.posito);
for (int i = 0; i < marks.size(); i++) {
if(!(marks.get(i) instanceof Test)) {
String sub = String.valueOf(marks.get(i));
if(db.isNoValue(sub,selectedSem)){
marks.remove(i);
notifyItemRemoved(i);
}
}
}
dialo.dismiss();
}
});
dialo.show();
return true;
}
});
}else {
holder.group.setVisibility(View.VISIBLE);
holder.card.setVisibility(View.GONE);
//group
if(holder.posito == 0) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)holder.group.getLayoutParams();
params.setMargins(0,0,0,0);
holder.group.setLayoutParams(params);
}
String sub = String.valueOf(marks.get(holder.posito));
holder.groupTitle.setText(sub);
holder.groupMark.setText(db.getTotalSubjectMarks(sub,selectedSem));
}
if(lastPosition < holder.posito) {
if(holder.card.getVisibility() == View.VISIBLE) {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.marks);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 100;
slide.setStartOffset(offset);
holder.card.startAnimation(slide);
} else {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.mark_groups);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 50;
slide.setStartOffset(offset);
holder.group.startAnimation(slide);
}
lastPosition = holder.posito;
}
}
#Override
public int getItemCount() {
return marks.size();
}
}
Note: I already tried the itemViewType method but it didn't work for me
Thanks in advance!
I believe you missed to set holder.card back to visible, like this
if(marks.get(holder.posito).getClass() == Test.class) {
holder.card.setVisibility(View.Visible); //add back this
holder.group.setVisibility(View.GONE);
My project contains listView(homelistView) that contains button(btnList).
When I click on button(btnList) it must go to another Activity. I tried a lot but I didn't find a good example.
Please suggest me a good example regarding this.
Below is my code:
Here is my listview contains button. When on click of button it must go to other activity
--------------------------------A--
button(btnList) B
--------------------------------C---
BUTTON(btnList) D
--------------------------------E--
homempleb.xml Before i used this code in xml. buttonlist worked fine for me as per Mohith verma sample
<ListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</ListView>
homempleb.xml Currently i added scroll index to my listview and changed the code as per below.. Listbutton is not working for me now..Plz help me
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
MainActivity.java
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView listView;
// private IndexableListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
// EfficientAdapter2 objectAdapter1;
int textlength = 0;
private CheckBox checkStat, checkRoutine, checkTat;
private ArrayList<Patient> patientListArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan", " txtScanResult ");
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this,
QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed",
Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE",
Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
// listView = (IndexableListView) findViewById(R.id.homelistView);
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(true);
objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);
Button refreshButton = (Button) findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// objectAdapter1 = new EfficientAdapter2(MainActivity.this);
objectAdapter = new EfficientAdapter(MainActivity.this);// adapter
// with
// new
// data
listView.setAdapter(objectAdapter);
Log.i("notifyDataSetChanged", "data updated");
// objectAdapter1.notifyDataSetChanged();
objectAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.JAVA
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<Patient> patientListArray;
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
String patientListJson = CountriesList.jsonData;
JSONObject jssson;
try {
jssson = new JSONObject(patientListJson);
patientListJson = jssson.getString("PostPatientDetailResult");
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray();
patientListArray = new ArrayList<Patient>();
for (JsonElement obj : Jarray) {
Patient patientList = gson.fromJson(obj, Patient.class);
patientListArray.add(patientList);
Log.i("patientList", patientListJson);
}
}
/**
* sorting the patientListArray data
*/
public void sortMyData() {
// sorting the patientListArray data
Collections.sort(patientListArray, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Patient p1 = (Patient) o1;
Patient p2 = (Patient) o2;
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
}
public int getCount() {
return patientListArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.name);
holder.text2 = (TextView) convertView.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView.findViewById(R.id.date);
holder.text4 = (TextView) convertView.findViewById(R.id.age);
holder.text5 = (TextView) convertView.findViewById(R.id.gender);
holder.text6 = (TextView) convertView.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView.findViewById(R.id.bedno);
holder.btnList = (Button) convertView.findViewById(R.id.listbutton);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(Util.formatN2H(patientListArray.get(position)
.getName()));
holder.text2.setText(patientListArray.get(position).getMrnNumber());
holder.text3.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text4.setText(Util.formatN2H(patientListArray.get(position)
.getAge()));
holder.text5.setText(Util.formatN2H(patientListArray.get(position)
.getGender()));
holder.text6.setText(Util.formatN2H(patientListArray.get(position)
.getWard()));
holder.text7.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text8.setText(Util.formatN2H(patientListArray.get(position)
.getBed()));
**
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { Intent next=new
Intent(context, Home.class); context.startActivity(next);
} });
**
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getPositionForSection(int section) {
// sorting the patientListArray data
sortMyData();
// If there is no item for current section, previous section will be
// selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j)
.getName().charAt(0)),
String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j).getName()
.charAt(0)),
String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
First remove btnList, btnScan from your MainActivity class.
In your EfficientAdapter class add object Context Context
Change your contructor:
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
to:
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
In your ViewHolder class you need to add Button btnList.
Then in getview method find its view using holder.btnList
Then use:
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
in your getview method before return convertView.
try this..
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_layout_ip_addtional_users, null);
}
//Handle TextView and display string from your list
TextView listItemText2 = (TextView)view.findViewById(R.id.list_item_string_name);
listItemText2.setText(list.get(position));
ImageButton button8 = (ImageButton) view.findViewById(R.id.ip_additional_user_edit);
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, IPAdditionalUsersEdit.class);
context.startActivity(intent);
}
});
return view;
}