ListView onClickListner not working and Delete row from ListView - android

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...

Related

How to display checkbox on every entry in a listView

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

ListView not showing data from custom Adapter

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>

Get text from edittext inside a listview

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

Custom Dialog with Checkbox in the Title

I am trying to create a Custom dialog via DialogFragment.
i want to have a Title and a Checkbox.
I am doing this by using a Custom Title as follows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp" >
<TextView
android:id="#+id/textView1"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="15dp"
android:text="Categories"
android:textColor="#ffffff"
android:textSize="22sp" />
<TextView
android:id="#+id/all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="All"
android:textColor="#ffffff" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:paddingRight="10dp"/>
</LinearLayout>
Now i want to reference this this Check box and add a listener to the Checkbox.
I want to achieve something like this
What i have tried ?
public class CategoriesDialogFragment extends SherlockDialogFragment {
ListView dialog_ListView;
static CheckBox chk_all;
static SelectViewHolder viewHolder;
private static ArrayAdapter<mItems> listAdapter;
static ArrayList<String> checked = new ArrayList<String>();
protected static CharSequence[] _categories = { "Amusement Park",
"Bird Sanctuary", "Wild Life", "River", "Hill Station", "Temple",
"Rafting", "Fishing", "Hiking", "Museums" };
protected static boolean[] _selections = new boolean[_categories.length];
PlacesListAdapter adapter;
ListView listView;
Button dialog_ok;
static int TAG = 0;
static mItems categories;
static mItems orig;
public static CategoriesDialogFragment newInstance(int title) {
CategoriesDialogFragment frag = new CategoriesDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(MainActivity.context);
//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setTitle("Categories");
dialog.setContentView(R.layout.dialog);
dialog_ok = (Button) dialog.findViewById(R.id.button_category_ok);
dialog_ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.listViewDialog);
dialog_ListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
categories = listAdapter.getItem(position);
orig = listAdapter.getItem(position);
categories.toggleChecked();
viewHolder = (SelectViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(
categories.isChecked());
if (!viewHolder.getCheckBox().isChecked()) {
TAG = 1;
chk_all.setChecked(false);
}
TAG = 0;
/*
* if (viewHolder.getCheckBox().isChecked()) {
*
* TAG = 0; }
*/
for (int i = 0; i < _categories.length; i++) {
categories = listAdapter.getItem(i);
if (!categories.isChecked()) {
break;
}
if (i == _categories.length - 1) {
TAG = 1;
chk_all.setChecked(true);
TAG = 0;
}
}
}
});
chk_all = (CheckBox) dialog.findViewById(R.id.checkBoxAll);
chk_all.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (TAG != 1) {
if (isChecked) {
for (int i = 0; i < listAdapter.getCount(); i++) {
categories = listAdapter.getItem(i);
categories.setChecked(true);
}
listAdapter.notifyDataSetChanged();
} else {
for (int i = 0; i < listAdapter.getCount(); i++) {
categories = listAdapter.getItem(i);
categories.setChecked(false);
}
listAdapter.notifyDataSetChanged();
}
}
if (TAG == 1) {
TAG = 0;
}
}
});
// itemss = (mItems[]) onRetainNonConfigurationInstance();
ArrayList<mItems> CategoryList = new ArrayList<mItems>();
CategoryList.add(new mItems("Amusement Park"));
CategoryList.add(new mItems("Bird Sanctuary"));
CategoryList.add(new mItems("Wild Life"));
CategoryList.add(new mItems("River"));
CategoryList.add(new mItems("Hill Station"));
CategoryList.add(new mItems("Temple"));
CategoryList.add(new mItems("Rafting"));
CategoryList.add(new mItems("Fishing"));
CategoryList.add(new mItems("Hiking"));
CategoryList.add(new mItems("Museums"));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new SelectArralAdapter(MainActivity.context, CategoryList);
dialog_ListView.setAdapter(listAdapter);
return dialog;
}
private static class SelectArralAdapter extends ArrayAdapter<mItems> {
private LayoutInflater inflater;
public SelectArralAdapter(Context context, List<mItems> planetList) {
super(context, R.layout.dialog_row, R.id.rowTextView, planetList);
// Cache the LayoutInflate to avoid asking for a new one each
// time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Planet to display
mItems planet = (mItems) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.dialog_row, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we
// don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new SelectViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged
// with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("uffff");
CheckBox cb = (CheckBox) v;
mItems row_view = (mItems) cb.getTag();
row_view.setChecked(cb.isChecked());
TAG = 1;
chk_all.setChecked(false);
TAG = 0;
for (int i = 0; i < _categories.length; i++) {
row_view = listAdapter.getItem(i);
if (!row_view.isChecked()) {
break;
}
if (i == _categories.length - 1) {
TAG = 1;
chk_all.setChecked(true);
TAG = 0;
}
}
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
SelectViewHolder viewHolder = (SelectViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Planet it is displaying, so that we
// can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display planet data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
}
I am not sure how we can include a setCustomTitle layout for the Custom Dialog
Now i want to reference this this Check box and add a listener to the
Checkbox.
I'm assuming that you show the dialog using the DialogFragment's onCreateDialog method, so in the onCreateDialog method you would do:
// inflate the layout title
View customTitle = inflater.inflate(R.layout.custom_title, null);
// find the CheckBox and set the listener
CheckBox ckb = (CheckBox) customTitle.findViewById(R.id.checkBox1);
ckb.setOnCheckedChangeListener(new ...);
// set the title view on the dialog etc

Custom list View with edit text and check boxes

I'm new to programming and having problem with using getCheckedItemPositions() for check boxes and getting edit values from edit text in custom list view. Can anyone help me with an example to create custom list view which has above functionality. Thanks.
*this is custom listview xml code
<CheckBox android:id="#+id/checkBox" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="CheckBox"
android:onClick="clickHandler"
></CheckBox>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="TextView"
android:id="#+id/textView1"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true" android:layout_marginBottom="14dp"
android:layout_toLeftOf="#+id/checkBox">
*This is code for set up listview
lv1 = (ListView)dialog.findViewById(R.id.l1);
adapter2 = new SimpleCursorAdapter(
this,
R.layout.custom,
cursor2,
new String[] {"ItemName"},
new int[] {R.id.textView1});
lv1.setItemsCanFocus(false);
lv1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv1.setAdapter(adapter2);
*this what I tried to do when checked
public void onClick(View v) {
int len = lv1.getCount();
SparseBooleanArray checked = lv1.getCheckedItemPositions();
for (int i = 0 ; i < len; i++)
if (checked.get(i)) {
String item = mArrayList.get(i);
mItems.add(mArrayList.get(i));
System.out.println(item);
/* do whatever you want with the checked item */
}
But this is not working. And also I want to use edit text in this manner for getting values.when I checked and click the button app terminate.
The following code will solve your problem.
public class SimpleCursorAdapter extends ArrayAdapter {
private Context mcontext;
private View rowview;
LayoutInflater inflater;
public static ArrayList<Boolean > itemchecked=new ArrayList<Boolean>();
public SimpleCursorAdapter(Context context,ArrayList<String> mylist)
{
super(context,your layout id);
mcontext=context;
//this is the important step
for (int i = 0; i < this.getCount(); i++)
{
itemchecked.add(i,false); // initializes all items value with false
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
rowview=convertView;
if(convertView==null)
{
rowview = inflater.inflate(R.yourlayout, parent, false);
}
TextView textView_heading = (TextView) rowview.findViewById(R.id.textView1);
CheckBox checkbox_detail=(CheckBox) rowview.findViewById(R.id.checkBox1);
checkbox_detail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
if (cb.isChecked()) {
itemchecked.set(position, true);
// do some operations here
} else if (!cb.isChecked()) {
itemchecked.set(position, false);
// do some operations here
}
}
});
checkbox_detail.setChecked(itemchecked.get(position));
textView_heading.setText(userheading_list.get(position));
return rowview;
}
}
//now the custom list part finish
Now, to get all the information from list and also watch which checkbox is checked:
for(int i=0;i<yourlistadapterobject.getCount();i++)
{
View content_view=msg_adapter.getView(i,null , user_detail_list);
System.out.println("the list count"+user_detail_list.getCount());
if(MyContactAdapter.itemchecked.get(i))
{
System.out.println("is checked true");
TextView tv_heading= (TextView) content_view.findViewById(R.id.textView1);
String text=tv_heading.getText();
}
}
By doing this, you can get all the information against checkbox which is checked.

Categories

Resources