Question part: 1
I have created an activity which contains product id and product name as list items. Each row contains an edittext which can be used to enter quantity for a particular product. The rows also contain a checkbox to select the particular product.
This is how the list looks like:
When I click on the list items, I can get the id and name of the particular list item, but I also want to get the quantity entered by the user for the list item.
This is the activity responsible for generating the listview:
public class PollStationActivity extends Activity {
// Hashmap for ListView
ArrayList<HashMap<String, String>> PSList = new ArrayList<HashMap<String, String>>();
String status_code_from_prev;
List<HashMap<String, String>> fillMaps=null;
String alert_message;
String quantity_message;
//quantity edittext
EditText quantity_edit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll_station);
//quantity edittext
quantity_edit = (EditText)findViewById(R.id.qty_editText);
//database insertion
DatabaseHelper db = new DatabaseHelper(this);
ContentValues values = new ContentValues();
try {
db.createDataBase();
values.put("_id", "1");
values.put("name", "rose");
db.insert(values);
} catch (IOException e) {
e.printStackTrace();
}
db.close();
ArrayList<TestItem> PSList = new ArrayList<TestItem>();
try {
db.createDataBase();
PSList = db.getAllData();
} catch (IOException e) {
e.printStackTrace();
}
db.close();
fillMaps = new ArrayList<HashMap<String, String>>();
Iterator<TestItem> i = PSList.iterator();
while(i.hasNext())
{
HashMap<String, String> map = new HashMap<String, String>();
TestItem objPSItem = i.next();
map.put("name", objPSItem.NAME);
map.put("Id", objPSItem.ID);
//map.put("quantity", objPSItem.QUANTITY);
fillMaps.add(map);
}
Log.i("Size: ", ""+fillMaps.size());
//populating listview from database
ListView listView1 = (ListView) findViewById(R.id.poll_list_listView);
if (null != listView1 && null != PSList) {
listView1.setAdapter(new ListAdapter(PollStationActivity.this,
R.id.ListViewContainer, new String[fillMaps.size()]));
}
}
//class for the list and on click handler
class ListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.values = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// return super.getView(position, convertView, parent);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.list_layout, parent,
false);
final HashMap<String, String> map = fillMaps.get(position);
TextView textView = (TextView) rowView
.findViewById(R.id.list_label_name);
textView.setText("("+map.get("Id")+") "+map.get("name"));
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rowView.setBackgroundResource(R.drawable.list_bg_pressed);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
rowView.setBackgroundResource(R.drawable.list_bg);
}
};
handler.postDelayed(r, 200);
//alert box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PollStationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Please Note!");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
// Intent intent = new Intent(RegisterFirstActivity.this, RegisterSecondActivity.class);
//
// intent.putExtra("AC_Code", map.get(TAG_CODE));
// RegisterFirstActivity.this.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
return rowView;
}
}
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
This is the TestItem class:
public class TestItem {
public String ID;
public String NAME;
public String QUANTITY;
public boolean selected;
// Empty constructor
public TestItem(){
}
// constructor
public TestItem(String id, String name, String quantity){
this.ID = id;
this.NAME = name;
this.QUANTITY = quantity;
}
// constructor
public TestItem(String name, String quantity){
this.NAME = name;
this.QUANTITY = quantity;
}
// getting ID
public String getID(){
return this.ID;
}
// setting id
public void setID(String id){
this.ID = id;
}
// getting name
public String getName(){
return this.NAME;
}
// setting name
public void setName(String name){
this.NAME = name;
}
// getting phone number
public String getQuantity(){
return this.QUANTITY;
}
// setting quantity
public void setQuantity(String quantity){
this.QUANTITY = quantity;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
This is the activity_poll_station.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_bg">
<RelativeLayout
android:id="#+id/ListViewContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/poll_label_textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp" >
<ListView
android:id="#+id/poll_list_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
</RelativeLayout>
This is the list_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/library_linear_layout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:background="#drawable/list_bg"
android:padding="5dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="44dp"
android:background="#null" >
<TextView
android:id="#+id/list_label_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="17sp" />
<CheckBox
android:id="#+id/item_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
<EditText
android:id="#+id/qty_editText"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:maxLines="1"
android:inputType="number" >
</EditText>
</RelativeLayout>
</LinearLayout>
I want to how to extract text from the edittext which I have created for every list item. If I try to extract the text on
rowView.setOnClickListener(new View.OnClickListener()
like this:
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"Quantity: "+quantity_edit.getText().toString()+"?");
The I am getting a null pointer exception getting generated due to the rowView.setOnClickListener(new View.OnClickListener()
What should I do? What should be the work around?
Thanks in advance!
//------------------------------------------------------------------------------//
Question part: 2
Now I want to do something like, I want to remove a particular row on clicking it. The row will only be deleted from the existing listview and a new list will be shown, how to do that?
Thanks once again!
You first need to get the reference to the EditText object, which you can do by using findViewById
quantity_edit = (EditText) view.findViewById("qty_editText");
you have override getView method of custom adapter. like the following.
public class SimpleAdapter1 extends ArrayAdapter<Data> {
public SimpleAdapter1(Context context, int textViewResourceId,
List<Data> catDesc) {
super(context, textViewResourceId, catDesc);
this.items = (ArrayList<Data>) catDesc;
this.context = context;
itemsid = new ArrayList<Integer>();
System.out.println(items);
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.YourLayout, null);
}
edit = (EditText) v.findViewById(R.id.editText1);
String tx = edit.getText().toString();
return v;
}
}
It will be very simple if you use custom adapter for your listview.
you can see this Custom Adapter for List View
and This one also useful for you how to get EditText value from listview
Related
From this Activity i get text from textField and display it in a ListView.
Now i want to to add check box on every entry in a listView Cell and also like to know how to display more than one text in a single ListView Cell.
Help with code will be appreciated.
Here is my code ....
public class AfterRegister extends AppCompatActivity
{
ListView listView;
EditText editText;
Button insertItemButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
CheckBox checkBox;
StoreRegistrationDataBase storeRegistrationDataBase;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_register);
storeRegistrationDataBase = new StoreRegistrationDataBase(this);
storeRegistrationDataBase = storeRegistrationDataBase.open();
checkBox = (CheckBox) findViewById(R.id.checkbox);
insertItemButton = (Button) findViewById(R.id.button4);
insertItemButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
editText = (EditText) findViewById(R.id.editText2);
listView = (ListView) findViewById(R.id.listView);
String getEditTextString = editText.getText().toString();
if(isAlphaNumeric(getEditTextString))
{
if(!getEditTextString.equals(""))
{
arrayList.add(getEditTextString);
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.text_view_layout, R.id.achView1, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
editText.setText("");
}
else
{
Toast.makeText(AfterRegister.this, "You can not insert empty field", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(AfterRegister.this, "Remove Space", Toast.LENGTH_SHORT).show();
}
}
});
listView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return false;
}
});
}
public boolean isAlphaNumeric(String s)
{
String pattern= "^[a-zA-Z0-9]*$";
if(s.matches(pattern))
{
return true;
}
return false;
}
}
You have to use a BaseAdapter and some Getter/Setter methods to add multiple texts/images/other UI elements in each item of your list view.
You have to implement multiple things to get this result. Here they are --
Create a Custom Layout for each item of your ListView.
listview_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/layout_textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginRight="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/layout_textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginLeft="5dip"
android:textStyle="bold"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkbox"
android:text="Test"/>
</LinearLayout>
Create a custom class and add some Getter/Setter methods.
ListRowItem.java
public class ListRowItem implements Serializable{
String carrier,number;
public String getCarrier(){
return carrier;
}
public String getNumber(){
return number;
}
public void setCarrier(String ba_carrier){
carrier = ba_carrier;
}
public void setNumber(String ba_number){
number = ba_number;
}
}
Create a custom class and extend the BaseAdapter class.
public class MyBaseAdapter extends BaseAdapter {
public Context ba_context;
public ArrayList<ListRowItem> listitem = new ArrayList<>();
public LayoutInflater inflater;
ListRowItem currentlistitem;
public MyBaseAdapter(Context ma_context, ArrayList<ListRowItem> ma_listitem) {
super();
this.ba_context = ma_context;
this.listitem = ma_listitem;
inflater = (LayoutInflater) ba_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.listitem.size();
}
#Override
public Object getItem(int position) {
return this.listitem.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, parent, false);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
currentlistitem = listitem.get(position);
String str_carrier = currentlistitem.getCarrier();
String str_number = currentlistitem.getNumber();
carrier.setText(str_carrier);
number.setText(str_number);
return vi;
}
}
Finally, populate your ArrayList and set the Adapter in your MainActivity.
ArrayList<ListRowItem> listitem = new ArrayList<>();
Context context = TestActivity.this;
MyBaseAdapter baseAdapter;
ListRowItem lr = new ListRowItem();
lr.setNumber(number);
lr.setCarrier(carrier);
listitem.add(lr);
baseAdapter = new MyBaseAdapter(context,listitem);
setContentView(R.layout.activity_test);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
Hope this helps!!
I'm trying to change the FragmentList item background color after click on this item an confirm an AlertDialog that is shown, it works but it's changing others items beside the clicled item....
This is all my code below...
public class RefrigeranteFragment extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public View SelectedView;
String[] refrigerantes = new String[] {
"Coca Cola",
"Coca Cola Zero",
"Fanta Uva",
"Guaraná Antartica",
"Guaraná Antartica Zero",
"Sukita",
"Sukita Laranja",
"Sprite",
"Guaraná Antartica",
"Sukita Uva"
};
// Array of strings to store currencies
String[] precos = new String[]{
"02,50",
"03,00",
"02,00",
"04,50",
"02,50",
"03,45",
"01,50",
"03,90",
"07,00",
"04,50"
};
int[] icones = new int[]{
R.drawable.ic_coca_lata,
R.drawable.ic_coca_zero_lata,
R.drawable.ic_fanta_uva_lata,
R.drawable.ic_guarana_antartica_lata,
R.drawable.ic_guarana_antartica_zero_lata,
R.drawable.ic_sukita_uva_lata,
R.drawable.ic_sukita_laranja_lata,
R.drawable.ic_sprite_lata,
R.drawable.ic_guarana_antartica_pet,
R.drawable.ic_sukita_uva_pet
};
private OnFragmentInteractionListener mListener;
public RefrigeranteFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static RefrigeranteFragment newInstance(String param1, String param2) {
RefrigeranteFragment fragment = new RefrigeranteFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 10; i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("txtNome", refrigerantes[i]);
hm.put("txtPreco", precos[i]);
hm.put("img_refrigerante", Integer.toString(icones[i]));
aList.add(hm);
}
String[] from = {"img_refrigerante", "txtNome", "txtPreco"};
int[] to = {R.id.img_refrigerante, R.id.txtNome, R.id.txtPreco};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_refrigerante_layout, from, to);
setListAdapter(adapter);
// Inflate the layout for this fragment
return super.onCreateView(inflater, container, savedInstanceState);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id){
super.onListItemClick(listView, view, position, id);
final View v = view;
final TextView txt = (TextView)view.findViewById(R.id.txtNome);
final ImageView imageView = (ImageView)view.findViewById(R.id.img_refrigerante);
final TextView tvQuantity = (TextView)view.findViewById(R.id.txtQtde);
final TextView lblQuantity = (TextView)view.findViewById(R.id.lblQtde);
final NumberPicker txtQtde = new NumberPicker(getContext());
txtQtde.setMinValue(1);
txtQtde.setMaxValue(10);
if(tvQuantity.getText() != "")
txtQtde.setValue(Integer.parseInt(tvQuantity.getText().toString()));
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(txt.getText());
builder.setMessage("Informe a quantidade");
builder.setIcon(imageView.getDrawable());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
txtQtde.setLayoutParams(lp);
builder.setView(txtQtde);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvQuantity.setText(String.valueOf(txtQtde.getValue()));
tvQuantity.setVisibility(View.VISIBLE);
lblQuantity.setVisibility(View.VISIBLE);
v.setBackgroundColor(Color.parseColor("#FF9933"));
((TextView)v.findViewById(R.id.lblNome)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.txtNome)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.lblPreco)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.txtPreco)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.lblQtde)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.txtQtde)).setTextColor(Color.WHITE);
}
});
builder.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}
);
builder.show();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ImageView
android:id="#+id/img_refrigerante"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/pizza_fragment"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:src="#drawable/ic_menu_pizza2" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/img_refrigerante" >
<TextView
android:id="#+id/lblNome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refrigerante: "
android:textStyle="bold"
android:textSize="15dp"
android:layout_below="#id/img_pizza" />
<TextView
android:id="#+id/txtNome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_toRightOf="#+id/lblNome" />
<TextView
android:id="#+id/lblPreco"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preço: "
android:textStyle="bold"
android:textSize="15dp"
android:layout_below="#+id/txtNome" />
<TextView
android:id="#+id/txtPreco"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_toRightOf="#+id/lblPreco"
android:layout_below="#+id/txtNome" />
<TextView
android:id="#+id/lblQtde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Qtde.: "
android:textStyle="bold"
android:textSize="15dp"
android:visibility="invisible"
android:layout_below="#+id/txtPreco" />
<TextView
android:id="#+id/txtQtde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/lblQtde"
android:layout_below="#+id/txtPreco" />
</RelativeLayout>
</RelativeLayout>
That is happening because of view recycling within ListView.
In order for this to work, you need three things:
You need variables in your adapter that stores the "clicked" state of the items; for example, a list of booleans.
In your onListItemClick(), you need to call a method on the adapter to change the state of the current item and call notifyDataSetChanged().
In your getView() override, you need to check this state and set the background of the view you are creating accordingly.
Here's code for an adapter (inner class for your activity) that remembers if an item has been clicked (and also the quantity):
public static class MyListAdapter extends BaseAdapter {
private String[] mNames;
private String[] mPrices;
private int[] mIcons;
private int[] mQtys;
private boolean[] mClicked;
public MyListAdapter(String[] names, String[] prices, int[] icons) {
mNames = names;
mPrices = prices;
mIcons = icons;
mQtys = new int[names.length];
mClicked = new boolean[names.length];
}
#Override
public int getCount() {
return mNames.length;
}
#Override
public Object getItem(int position) {
return mNames[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_refrigerante_layout, parent, false);
}
ImageView icon = (ImageView) convertView.findViewById(R.id.img_refrigerante);
icon.setImageResource(mIcons[position]);
TextView name = (TextView) convertView.findViewById(R.id.txtNome);
name.setText(mNames[position]);
TextView price = (TextView) convertView.findViewById(R.id.txtPreco);
price.setText(mPrices[position]);
// hide these if qty == 0
TextView qty = (TextView) convertView.findViewById(R.id.txtQtde);
qty.setText(mQtys[position]);
qty.setVisibility(mQtys[position] == 0 ? View.INVISIBLE : View.VISIBLE);
TextView qtyLbl = (TextView) convertView.findViewById(R.id.lblQtde);
qtyLbl.setVisibility(mQtys[position] == 0 ? View.INVISIBLE : View.VISIBLE);
// here is where we use the clicked flag to determine which colors to set
// TODO put a real color for backgroundColorNormal because I don't know what your normal background color is
int backgroundColor = mClicked[position] ? Color.parseColor("#FF9933") : backgroundColorNormal;
convertView.setBackgroundColor(backgroundColor);
// TODO put a real color for colorNormal because I don't know what your normal text color is
int textColor = mClicked[position] ? Color.WHITE : colorNormal;
((TextView) convertView.findViewById(R.id.lblNome)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.txtNome)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.lblPreco)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.txtPreco)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.lblQtde)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.txtQtde)).setTextColor(textColor);
return convertView;
}
public int getQty(int position) {
return mQtys[position];
}
public void setQty(int position, int qty) {
mQtys[position] = qty;
notifyDataSetChanged();
}
public void setClicked(int position, boolean clicked) {
mClicked[position] = clicked;
notifyDataSetChanged();
}
}
When you change a click flag or quantity, notifyDataSetChanged() is called. This is what tells the ListView to ask the adapter again for item views through getView(), and the item views are updated using the new values.
You need to keep a reference to this adapter in your activity:
private MyListAdapter mAdapter;
and set it up:
mAdapter = new MyListAdapter(refrigerantes, precos, icones);
setListAdapter(mAdapter);
then your item click handler would look like this (I simplified it a bit)
#Override
public void onListItemClick(ListView listView, View view, final int position, long id){
super.onListItemClick(listView, view, position, id);
final NumberPicker txtQtde = new NumberPicker(getContext());
txtQtde.setMinValue(1);
txtQtde.setMaxValue(10);
txtQtde.setValue(Integer.parseInt(mAdapter.getQty(position)));
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(refrigerantes[position]);
builder.setMessage("Informe a quantidade");
builder.setIcon(icones[position]);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
txtQtde.setLayoutParams(lp);
builder.setView(txtQtde);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mAdapter.setQty(position, txtQtde.getValue());
mAdapter.setClicked(position);
}
});
builder.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}
);
builder.show();
}
Please -- do more than just copy/paste this and take the time to go through the code line by line to understand how it works. Looking at sample code is a good way to learn about Android, but you won't learn anything if you copy/paste without understanding.
In this link I showed how to change item background color in AlertDialog. It also shows how to customize the AletDialog. For example, how to change divider colro and etc. Please visit this link:
https://stackoverflow.com/a/33439849/5475941.
I hope it helps.
My getView() method for customized ListViewAdapter is as follows :
public class ListViewAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
ArrayList mArray;
ArrayList<Item> mArray2;
DBHelper mydb;
String dbName;
public ListViewAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
mArray = new ArrayList();
mArray2 = new ArrayList<>();
mydb = new DBHelper(mContext);
}
#Override
public int getCount() {
return mArray.size();
}
#Override
public Object getItem(int position) {
return mArray.get(position);
}
public Item getItem2(int position) { return mArray2.get(position); }
#Override
public long getItemId(int position) {
// your particular data set uses String IDs
// but you have to put something in this method
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
// check if the view already exists
// if so, no need to inflate and findViewById again!
if (convertView == null) {
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.list_item, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.itemNameView = (TextView) convertView.findViewById(R.id.item_name);
holder.itemExpiryView = (TextView) convertView.findViewById(R.id.item_expiry);
// Taking care of the buttons
holder.editButton = (Button) convertView.findViewById(R.id.button_edit);
holder.deleteButton = (Button) convertView.findViewById(R.id.button_delete);
// hang onto this holder for future recycling
convertView.setTag(holder);
} else {
// skip all the expensive inflation/findViewById
// and just get the holder you already made
holder = (ViewHolder) convertView.getTag();
}
// Set listener on the buttons
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Edit Button CLicked", Toast.LENGTH_SHORT).show();
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = getItem(position).toString();
int id = mydb.getID(dbName, name);
mydb.deleteItem(dbName, id);
mArray2 = mydb.getAllItemsAsCollection(dbName);
notifyDataSetChanged();
Toast.makeText(mContext, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
// Doing for 2nd case
Item _item = getItem2(position);
String name2 = _item.name;
System.out.println(name2);
String ex = _item.expiry;
System.out.println(ex);
// For the second case
holder.itemNameView.setText(name2);
holder.itemExpiryView.setText(ex);
return convertView;
}
// this is used so you only ever have to do
// inflation and finding by ID once ever per View
private static class ViewHolder {
public TextView itemNameView;
public TextView itemExpiryView;
public Button editButton;
public Button deleteButton;
}
public void updateData2(ArrayList<Item> arrayPassed) {
// update the adapter's data set
mArray2 = arrayPassed;
notifyDataSetChanged();
}
public void setDbName(String dbName){
this.dbName = dbName;
}
}
The DBHelper class function getAllItemsAsCollection() is defined as below :
public ArrayList<Item> getAllItemsAsCollection(String dbName)
{
ArrayList<Item> array_list = new ArrayList<Item>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from " + dbName, null );
res.moveToFirst();
while(res.isAfterLast() == false){
String n = res.getString(res.getColumnIndex(COLUMN_NAME));
String e = res.getString(res.getColumnIndex(COLUMN_EXPIRY));
String c = dbName;
Item _item = new Item(n, e, c);
array_list.add(_item);
res.moveToNext();
}
return array_list;
}
And also, the insertItem() function inside DBHelper is this :
public boolean insertItem (String dbName, String name, String expiry)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("expiry", expiry);
db.insert(dbName, null, contentValues);
return true;
}
I have added a separate class for customizable object handing :
public class Item {
String name;
String expiry;
String category;
Item(String n, String e, String c){
this.name = n;
this.expiry = e;
this.category = c;
}
}
And the addItem() method inside MainActivity.java works like :
public void addItem(final View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
LinearLayout lila1 = new LinearLayout(this);
lila1.setOrientation(LinearLayout.VERTICAL);
final EditText name = new EditText(this);
name.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
final EditText days = new EditText(this);
days.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
TextView text_ex = new TextView(this);
text_ex.setText("In how many days will it expire..");
alert.setTitle("Hello!");
alert.setMessage("What did you buy today..");
lila1.addView(name);
lila1.addView(text_ex);
lila1.addView(days);
alert.setView(lila1);
// Make an "OK" button to save the name
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Grab the EditText's input
String inputName = name.getText().toString();
String daysToExpiry = days.getText().toString();
System.out.println(daysToExpiry);
mydb.insertItem(currentDB, inputName, daysToExpiry);
System.out.println("Worked");
// For 2nd Case
currentList2 = mydb.getAllItemsAsCollection(currentDB);
System.out.println("Random Musings");
itemAdder2.updateData2(currentList2);
// addItemToList(inputName, v);
dialog.dismiss();
}
});
// Make a "Cancel" button
// that simply dismisses the alert
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
alert.show();
}
I have initiaized every variable correctly. When I try to run my app, and try to add a new item, the Dialog box just vanishes and there is nothing shown in the layout. I tried with a simple ArrayList<Strings> before and it worked perfectly. That is why I believe there should not be any problem with the .xml Layout. And might be with the ListViewAdapter.updateData2() function. Please Help. Appreciate your patience going through these long pieces of code. If any further info is required, please let me know. Thanks a lot. :)
Forgot to attach the .xml for actual view. This worked perfectly with ArrayList<String>. I have already tested. When I tried to pass complex object, in this case, Item-class object, and correspondingly an ArrayList<Item>, my guess is, I could not write the adapter portion code correctly.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/item_expiry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_name" />
<Button
android:id="#+id/button_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/item_expiry"
android:layout_alignParentLeft="true"
android:text="Edit"
android:clickable="true" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/item_expiry"
android:layout_alignParentRight="true"
android:text="Delete"
android:clickable="true" />
</RelativeLayout>
I am trying to create a custom listview with a checkbox and a string list of "observations" retrieved from my sqlite database. The idea is that when I click on the "retrieve" button, all checked items are shown in a toast message.
I can populate the listview through my customadapter just fine, but it doesnt seem to recognise the status of each checkbox, as no toast messages are shown, regardless of whether they are checked.
Please can someone show me where I am going wrong?
Here is my custom listview xm that I have called list_o:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:id="#+id/obsgrid">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chkbx"
android:layout_row="0"
android:layout_column="0" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/obs"
android:layout_row="0"
android:layout_column="1" />
Here is my custom adapter:
class CustomAdObs extends ArrayAdapter<String> {
private String [] observation;
private Boolean [] checked;
private Context context;
public CustomAdObs(Context context, String[] observation) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater siteInflater = LayoutInflater.from(getContext());
View customView = siteInflater.inflate(R.layout.list_o, parent, false);
TextView observationTV = (TextView) customView.findViewById(R.id.obs);
CheckBox checkCB = (CheckBox) customView.findViewById(R.id.chkbx);
checkCB.setTag(Integer.valueOf(position));
observationTV.setText(observation[position]);
checkCB.setChecked(checked[position]);
return customView;
}
}
Finally here is my activity:
public class selobs extends Activity {
List< List<String> > listArray = new ArrayList< List<String> >();
List<String> array1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode. setThreadPolicy(policy);
setContentView(R.layout.activity_selobs);
final Button retrieve= (Button) findViewById(R.id.btnret);
final EditText txtob = (EditText) findViewById(R.id.editText23);
filladapter();
retrieve.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ListView obsListView = (ListView) findViewById(R.id.obsList);
View v;
for (int i = 0; i < obsListView.getCount(); i++) {
v = obsListView.getAdapter().getView(i, null, null);
CheckBox check = (CheckBox) v.findViewById(R.id.chkbx);
TextView obsItem = (TextView) v.findViewById(R.id.obs);
if (check.isChecked()) {
String p = obsItem.getText().toString();
Toast.makeText(selobs.this, p, Toast.LENGTH_LONG).show();
}
}
}
}
);
}
public void filladapter(){
myDBhandler1 dbHandler;
dbHandler = new myDBhandler1(selobs.this, null, null, 1);
listArray = dbHandler.databaseToStringObs();
List array1 = listArray.get(0);
String[] observ = (String[]) array1.toArray(new String[0]);
Boolean[] checked = new Boolean[0];
Arrays.fill(checked, Boolean.FALSE);
final ListAdapter ObsAdapter = new CustomAdObs(this, observ, checked);
final ListView obsListView = (ListView) findViewById(R.id.obsList);
obsListView.setAdapter(ObsAdapter);
obsListView.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(selobs.this, item, Toast.LENGTH_LONG).show();
TextView txtobs = (TextView) findViewById(R.id.editText23);
txtobs.setText(item);
}
}
);
}
}
your constructor
public CustomAdObs(Context context, String[] observation) {//here the Boolean[] checked ->is messing
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
so you replace it with this
public CustomAdObs(Context context, String[] observation, Boolean[] checked) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
why ?
because you call it like this
new CustomAdObs(this, observ, checked);
while you have just the 2 params in your constructor(Context context,String[] observation)
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/mytitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/icon"
android:background="#drawable/textbox1"
android:paddingBottom="10dp"
android:text="Title"
android:textColor="#CC0033"
android:textSize="20dp" />
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/mytitle"
android:layout_marginLeft="20dp"
android:scaleType="fitXY"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/descri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/mytitle"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/icon"
android:layout_marginTop="16dp"
android:background="#drawable/textbox1"
android:text="Description"
android:textColor="#3399FF"
android:textSize="14dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/mytitle"
android:layout_toLeftOf="#+id/mytitle"
android:layout_marginLeft="5dp"
android:background="#drawable/buttontextview"
android:text=" Click To Share"
android:textColor="#android:color/white"
android:textSize="13sp" />
This is my RowItem class
public class RowItem {
private String imagepath;
private String title;
private String desc;
public boolean isclicked;
public RowItem(String imagepath,String title,String desc) {
System.out.println("ImagePath is:---"+imagepath);
this.imagepath = imagepath;
System.out.println("Title is:---"+title);
this.title = title;
System.out.println("Description is:---"+desc);
this.desc = desc;
isclicked = false;
}
public String getImagepath() {
return imagepath;
}
public boolean isIsclicked() {
return isclicked;
}
public void setIsclicked(boolean isclicked) {
this.isclicked = isclicked;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
This is my onCreate() Method from the Activity
{ int k = 0;
if(i>0){
rowItems = new ArrayList<RowItem>();
for (int j = 0;j<i ; j++) {
System.out.println("Loop Value:--"+j);
System.out.println("Location Details:-----"+location.get(j));
System.out.println("Description Details:------"+description.get(j));
System.out.println("Image Details:------"+images.get(j));
RowItem item = new RowItem(images.get(j),location.get(j),description.get(j));
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListViewAdapter(PicActivity.this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
This is my listitem onClicklistner method
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("My List Item Clicked");
mylistid = position;
Button deleteBtn = (Button) findViewById(R.id.delete);
deleteBtn.setOnClickListener(this);
File myimagefile = new File(images.get(position));
lastlistid = mydb.getlastlistid();
int list = Integer.valueOf(lastlistid.get(0));
listno=0 ;
listno = list-position;
SharedPreferences mylistpref = getSharedPreferences(Constants.listiddetails, 0);
Editor edit= mylistpref.edit();
edit.putInt("listid", listno);
edit.commit();
System.out.println("First Position Value:-"+position);
Toast toast = Toast.makeText(getApplicationContext(),
"Title " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent intermediate = new Intent (PicActivity.this,InterMediateActivity.class);
intermediate.putExtra("savenshare", "notshare");
intermediate.putExtra("flag", "false");
startActivity(intermediate);
finish();
}
The Checkbox is coming in the listview but onItemclicklistner is not working.
My deleteButton onClicklistner is like this
case R.id.delete:
System.out.println("My List item:-"+mylistid);
((CustomListViewAdapter)listView.getAdapter()).notifyDataSetChanged();
break;
Here mylistid is a global integer which i am setting while on listitemonclick.
Why my list item onclicklistner not working if i add checkbox in my list and also how can i delete the row and update the listitem.I have followed many tutorials but unable to implement.
Please help !!!!
UPDATE
This is my customListViewAdapter Class
public class CustomListViewAdapter extends BaseAdapter {
private List<RowItem> arr = new ArrayList<RowItem>();
ArrayList<Integer> checks=new ArrayList<Integer>();
private Context context;
Bitmap mybitmap;
private Activity activity;
ViewHolder holder = null;
int mypos=0;
File f;
RowItem rowItem;
public CustomListViewAdapter(Context context,List<RowItem> items) {
//super();
this.arr = items;
this.context=context;
}
private class ViewHolder {
//ImageView imageView;
TextView txtTitle;
TextView txtDesc;
ImageView image;
// CheckBox mychk;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
//mypos=arg0;
return arr.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
rowItem = (RowItem) getItem(position);
f = new File(rowItem.getImagepath());
System.out.println("My list item Position from GetView:--"+position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descri);
holder.txtTitle = (TextView) convertView.findViewById(R.id.mytitle);
// holder.mychk = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.image = (ImageView) convertView.findViewById(R.id.icon);
// holder.mychk.setOnCheckedChangeListener(this);
// holder.mychk.setTag(arr.get(position));
// holder.mychk.setChecked(false);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.mychk.setOnCheckedChangeListener(this);
System.out.println("My Description is:--"+holder.txtDesc.getText());
System.out.println("My Title is:--"+holder.txtTitle.getText());
holder.txtDesc.setText(" "+rowItem.getDesc());
holder.txtTitle.setText(" "+rowItem.getTitle());
if(f.exists())
{
mybitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
Bitmap myeditedbitmap = Bitmap.createScaledBitmap(mybitmap, 180, 150, false);
holder.image.setImageBitmap(myeditedbitmap);
//holder.mychk.setChecked(true);
//setImageResource(rowItem.getImagepath());
}
//holder.txtTitle.setText(rowItem.getTitle());
/* for(int i=0;i<ArrayId.size();i++)
{
rowItem.remove(ArrayId[i]);
}
*/
return convertView;
}
}
}
UPDATE 2
I have updated my ListItem xml to some code and now onItemClick is working..
android:descendantFocusability="blocksDescendants"
Now The other part is..delete row item..which is still not working.and also if i select one checkbox then others are also getting selected.like if i select 1..then 3..5..7 is getting selected..How to avoid this ??
My deleteItem row code..
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
int itemCount = listView.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
// adapter.remove(rowItems.get(i)); This line is giving me error.first i want to delete row temp and give a toast message.then i will update the database later.but as i am using customarrayadapter class.so i dont have the method remove.Can someone help me regarding the remove method ?
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
});
UPDATE 3
case R.id.delete:
SharedPreferences del = getSharedPreferences(Constants.checkedid,0);
int checkmyid = 0;
checkmyid = del.getInt("check", 0);
int mycount = listView.getCount();
System.out.println("My List item COUNT FROM DELETE METHOD:-"+mycount);
System.out.println("My List item FROM DELETE METHOD:-"+checkmyid);
rowItems.remove(checkmyid);
mydb.delete(checkmyid);
((CustomListViewAdapter)listView.getAdapter()).notifyDataSetChanged();
break;
and my Delete method from database is
public void delete(int id){
String sql = "delete from picdetails where id="+id;
Cursor mych;
mych = myDataBase.rawQuery(sql, null);
}
But when i am reopening the database the data is showing once again.How to avoid ? Also When i am selecting one checkbox to delete that particular checkbox is not getting deleted.the bottom row is getting deleted.
UPDATE 4
i have updated the delete button code..now the row item is getting deleted..but for the first selection its not deleted.its getting deleted from bottom.but the checkitemid is perfect
SharedPreferences del = getSharedPreferences(Constants.checkedid,0);
int checkmyid = 0;
checkmyid = del.getInt("check", 0);
int mycount = listView.getCount();
System.out.println("My List item COUNT FROM DELETE METHOD:-"+mycount);
SparseBooleanArray checked = listView.getCheckedItemPositions();
System.out.println("*****My SELECTED List item FROM DELETE METHOD:-*****"+checkmyid);
rowItems.remove(checkmyid);
For ListView onClickListner not working
It happens due to focusability of CheckBoxin listitem layout.
Add below line to root layout of your ListView's Item layout.
android:descendantFocusability="blocksDescendants"
in list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp"
android:descendantFocusability="blocksDescendants">
To delete row (not sure but will work if make some changes)
for(int i=0; i < itemCount; i++){
if(checkedItem.contains(i)){
View rowView=listView.getChildAt(i) OR listView.removeViewAt(i);
listView.removeView(rowView);
//Also Remove data from **rowItems**
}
}
Here checkedItem is arraylist(or something else) where you supposed store position of checked listrow.
onClick...{
rowItems.remove(position);
notifyDataSetChanged();
}
this should work...