How to update Activity UI based on ListView item selection? - android

I am creating a sample application containing an Activity [having ListView and Button] in layout file. ListView is custom containing [Label/Name and CheckBox]. I want to write some code which will change text of the Button from adapter class of ListView based on List Item CheckBox check [T/F].

listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// When clicked, show a toast with the TextView text
AppListOfAllApps Selecteditems = (AppListOfAllApps) parent.getItemAtPosition(position);
if (view != null)
{
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1);
Selecteditems = (AppListOfAllApps) checkBox.getTag();
//here you will get the selected item you may also get the text from it accordingly and then using using button variable just set text
button.settext("whatever");
}
}
});

In Activity :
public class Your_Activity extends Activity implements OnCheckListener// Implement your listener here
#Override
public void OnCheck(int position) {
// TODO Auto-generated method stub
// notify your activity component here
}
In Adapter class :
private OnCheckListener listener;
public interface OnCheckListener {
public void OnCheck(int position);
}
public Your_adapter_constructor(OnCheckListener listener) {
// TODO Auto-generated constructor stub
this.listener = listener;
}
// On your getView()
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listener.OnCheck(position);// If you want to pass some value add it here
}
});

Related

how to get checked multiple values using custom adapter in android

I have listview with custom adapter. Every element of this listview has checkbox. Standart function .isChecked() does not work.
someActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<Boolean> listCheck;
listCheck = new ArrayList<Boolean>();
for (int i = 0; i < CA_main_trx.editModelArrayList.size(); i++){
Boolean stat = CA_main_trx.editModelArrayList.get(i).getCheckShare();
String nilaiPcs = CA_main_trx.editModelArrayList.get(i).getTextView_main_trx2();
Log.d(TAG, "onClick: --a" + nilaiPcs);
Log.d(TAG, "onClick: --a" + stat);
}
}
});
CustomeAdapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final String TAG = "CA_Main_Trx : ";
...
holder.checkShare.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
String id = editModelArrayList.get(position).getTextView_main_trx0();
Log.d(TAG, "onCheckedChanged: True"+id);
}
else
Log.d(TAG, "onCheckedChanged: False");
}
});
...
model
package com.m.t;
public class EM_main_trx {
private boolean checkShare;
public Boolean getCheckShare() {return checkShare;}
public void setCheckShare(Boolean checkShare) {
this.checkShare = checkShare;
}
}
When checked in custome Adapter i get the checked status. But when i get the data using button in my mainactivity i got stuck. just got null.
Some my reference :
Android: Get checked checkbox values
Finding the Checked state of checkbox in a custom listview
how to get the the multiple checkbox values using custom adapter in android
Android List View Custom Adapter with Checkbox multiple selection and Search Listview
Checked values of CheckBox with Custom Listview android
Just update part of custome adapter to this :
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
editModelArrayList.get(position).setCheckShare(b);
}

How to delete a row from a ListView with a CursorAdapter

I started a small Android project to re-learn a bit of Android development, and I'm already stuck...
I do not know how to implement the deletetion of an element of my ListView!
Here is the project: https://github.com/gdurelle/Listify
Right now it aims at showing a list of lists of elements.
I use a custom CursorAdapter to show my list of elements, and I already have a (ugly) destroy button, but I do not know how to make it delete an actual element from the list (and the database).
I use ActiveAndroid to manage the database in the ActiveRecord way.
Plus: I'm not sure wether or not to use getView(), bindView(), and/or newView()...
I created an issue to remember this and reference this question here: https://github.com/gdurelle/Listify/issues/1
public class ListifyCursorAdapter extends CursorAdapter {
public String content;
public ListifyCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it, you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.element_line, parent, false);
}
// The bindView method is used to bind all data to a given view such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
}
And in my MainActivity :
Cursor cursor = ListifyElement.fetchResultCursor();
adapter = new ListifyCursorAdapter(this, cursor);
listView.setAdapter(adapter);
I was thinking maybe about a:
Button delete_button = (Button) listView.findViewById(R.id.delete_button);
with something like ListifyElement.load(ListifyElement.class, the_id_of_the_element).delete(); where the_id_of_the_element would be the DB's id of the element retrieived somehow from the click on it's delete_button in the UI...
UPDATE:
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(cursor.getColumnName(0)); // Id
System.out.println(cursor.getColumnName(1)); // ListifyContainer
System.out.println(cursor.getColumnName(2)); // content
System.out.println(cursor.getColumnIndexOrThrow("Id")); // 0
ListifyElement.load(ListifyElement.class, cursor.getColumnIndexOrThrow("Id")).delete();
notifyDataSetChanged();
}
});
I get this error when I click the delete button:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gdurelle.listify.models.ListifyElement.delete()' on a null object reference
If you want a Button in each row, you should add it to your xml which you inflate in the newView(). After that, you should set OnClickListener to your Button inside bindView(). Something like that:
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//As you're using ActiveAndroid
new Delete().from(ListfyElement.class).where("yourCondition=?",yourCondition).execute();
notifyDataSetChanged();
}
});
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
Use below code to perform this--
ListView lv;
ArrayList<String> arr = new ArrayList<String>();
ArrayAdapter adapter;
int position;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.extra);
for(int i=0;i<5;i++)arr.add("Hi # "+i);
lv = (ListView) findViewById(R.id.listViewBirthday);
lv.setOnItemLongClickListener(this);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, arr);
lv.setAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuItem it1=menu.add("Delete");
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int p, long arg3)
{
position = p;
registerForContextMenu(lv);
return false;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getTitle().equals("Delete"))
{
arr.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "deleted", Toast.LENGTH_SHORT).show();
}
return true;
}
The context menu is relatively simple to implement on a listview. It (context menu) is activated on a long press of the item. My tip is to add an intent to the menu item so you can preserve the item id from your custom adapter and use it to perform whatever you want.
public class MainActionBarTabListFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
registerForContextMenu(getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String name = adapter2.getItem(info.position).get_name();
menu.setHeaderTitle(name);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menulistitem, menu);
MenuItem mi = menu.findItem(R.id.action_context_delete);
Intent i = new Intent();
i.putExtra("id", adapter2.getItem(info.position).get_id());
mi.setIntent(i);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_context_delete:
Intent i = item.getIntent();
if (i != null) {
Bundle b = i.getExtras();
if (b != null) {
int id = b.getInt("id");
Uri deleteIdUri = ContentUris.withAppendedId(
RidesDatabaseProvider.CONTENT_URI, id);
context.getContentResolver()
.delete(deleteIdUri, null, null);
return true;
}
}
}
return super.onContextItemSelected(item);
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_context_delete"
android:icon="#drawable/action_about"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:title="delete"
yourapp:showAsAction="ifRoom"/>
</menu>
lets start from the beginning, why do you need to use ActiveAndroid? I suggest to avoid such things, IMHO. You've mixed your logic, adapter should not change your database. Set a listener to adapter (i.e. IDeleteListener with single method onDeleteRequested(long rowId)). Next you need to pass rowId, something like:
delete_button.setTag(cursor.getLong(0));
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
listener.onDeleteRequested((Long)v.getTag());
}
});
In your fragment/activity class you should set a listener to adapter and work with your database. I suggest you to use LoaderManager this will automatically re-query your db on delete and handle life cycle of activity.
Hope that helps!
I would suggest you to use an ArrayAdapter instead. Then you are just using an ArrayList (or any other array) and edit it, and call adapter.notifyDataSetChanged();, and the content of the ListView will update.
Declare the ArrayAdapter like this:
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
where the variable called yourStringArray is just an ArrayListof Strings.
Then, add the adapter to the ListView, like this:
yourListView.setAdapter(adapter);
Then, you can modify the contents of the list, by editing the yourStringArray list, and calling adapter.notifyDataSetChanged();. Here is a simple example:
list.add("Hello!");
adapter.notifyDataSetChanged();
Finally, to remove the selected item when the button is clicked, you can do something like this:
int selectedItemIndex = 0;
yourArrayList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
The whole onCreate method would look something like this:
// Called when the activity is created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> yourStringArray = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
int selectedItemIndex = 0;
ListView yourListView = (ListView) findViewById(R.layout.yourListViewID);
yourListView.setAdapter(adapter);
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
}

Android: ListView Trouble with textview.isChecked() and textview.setChecked()

I have a listview which uses this layout:
android.R.layout.simple_list_item_checked
I have an OnItemClickListener that gets the check status of the clicked item and either checks or unchecks that item but it does not work. There are NO errors in logcat. When I click on an item in the listview simply nothing happens.
The OnItemClickListener looks like this:
//------------------- OnItemClickListener -----------------------------
lvCheckList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
CheckedTextView textview = (CheckedTextView)view;
if (!textview.isChecked()){
textview.setChecked(true);
}else {
textview.setChecked(false);
}
}
});
Try with this...
//sample code
TextView TxtName = (TextView) findViewById(R.id.NameControlId);
TxtName.setOnClickListener(this);
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.NameControlId:
Toast.makeText(getApplicationContext(),"click",Toast.LENGTH_SHORT).show();
break;
}
}

How to get selected list items from a Listview with checkBox and Custom Adapter?

I have a ListView with CheckBox on it. and i am using Custom Adapter to populate the ListView.
In my xml file i have a Button at bottom. what i want is let user select number of rows in ListView and when he/she clicked on the Button get the position of the selected items so that i could get the object for particular row for further calculations.
In the customadapter's getview method, do
//use the actual id of your checkbox of course
Checkbox checkbox = (CheckBox)findViewById(R.id.checkbox);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
now the checkbox is clickable as is the listitem.
To solve this problem you will have to create a custom Item class which will represent your individual checkboxes on the list. The array of these items will then be used by the adapter class to display your check boxes.
This Item class will have a boolean variable isSelected which will determine if the checkbox is selected or not. You will have to set the value of this variable in your OnClick Method of your custom adapter class
For Example
class CheckBoxItem{
boolean isSelected;
public void setSelected(boolean val) {
this.isSelected = val;
}
boolean isSelected(){
return isSelected;
}
}
For your CustomAdapter Class which look like following:
public class ItemsAdapter extends ArrayAdapter implements OnClickListener {
// you will have to initialize below in the constructor
CheckBoxItem items[];
// You will have to create your check boxes here and set the position of your check box
/// with help of setTag method of View as defined in below method, you will use this later // in your onClick method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
CheckBox cBox = null;
if (v == null) {
LayoutInflater vi = (LayoutInflater) apUI.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.attachphoto, null);
}
CheckBoxItemItem it = items[position];
cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
cBox.setOnClickListener(this);
cBox.setTag(""+position);
Log.d(TAG, " CHECK BOX IS: "+cBox+ " Check Box selected Value: "+cBox.isChecked()+" Selection: "+it.isSelected());
if(cBox != null){
cBox.setText("");
cBox.setChecked(it.isSelected());
}
return v;
}
public void onClick(View v) {
CheckBox cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
int position = Integer.parseInt((String) v.getTag());
Log.d(TAG, "CLicked ..."+cBox.isChecked());
items[position].setSelected(cBox.isChecked());
}
}
Later you will will declare and array of your CheckBoxItem class which will be contained by your Adapter class in this case it will be ItemsAdapter class.
Then when the user presses the button you can iterate through all the items in the array and check which one is selected by using the isSelected() method of CheckBoxItem class.
In your activity you will have:
ArrayList getSelectedItems(){
ArrayList selectedItems = new ArrayList();
int size = items.length;
for(int i = 0; i<size; i++){
CheckBoxItem cItem = items[i];
if(cItem.isSelected()){
selectedItems.add(cItem);
}
}
return selectedItems;
}
I had the exact same problem. I solved it in this way
public class myActivity extends Activity {
//ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
public ListView listview;
private ArrayList<Object> itemlist=new ArrayList<Object>();
Button button;
private myAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView)findViewById(R.id.listview1);
button=(Button)findViewById(R.id.button1);
/*add some data to ur list*/ itemlist.add(something);
adapter=new Adapter(myActivity.this, 0, itemlist);
listview.setAdapter(adapter);
**listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setItemsCanFocus(false);**
button.setOnClickListner(new OnClickListner()
{
#Override
public void OnClick(View v)
{
/* this returns the checked item positions in the listview*/
**ArrayList<Integer> itempositions=adapter.getcheckeditemcount();**
for(int i:itempositions)
{
/* This is the main part...u can retrieve the object in the listview which is checked and do further calculations with it*/
**Object info=adapter.getItem(i);**
Log.d(TAG,"checked object info= ",info.something);
}
}
});
}
private class myAdapter extends ArrayAdapter<Object> {
private Context context;
private ArrayList<Object> list;
**private ArrayList<Integer> checkedpositions;**
public myAdapter(Context localContext,int textViewResourceId, ArrayList<Object> objects) {
super(localContext,textViewResourceId,objects);
context = localContext;
this.list=objects;
this.checkedpositions=new ArrayList<Integer>();
//Log.d("adapter","list size= "+objects.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
View v = convertView;
TextView Mainitem;
final CheckBox check;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.albumview, null);
Object item=list.get(position);
if(item!=null)
{
check = (CheckBox)v.findViewById(R.id.checkBox1);
/* set a tag for chekbox with the current view position */
**check.setTag(position);**
/*set a onchecked change listner for listning to state of checkbox toggle */
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
/*get the tag of the checkbox...in this case this will give the (position of view)*/
Object tag=check.getTag();
if ( isChecked )
{
// perform logic
count++;
Log.d("Checkbox","added "+tag);
checkedpositions.add((Integer) tag);
}
else
{
count--;
checkedpositions.remove(tag);
Log.d("Checkbox","removed "+(Integer)tag);
}
/* if u dont have a textview in ur listview then ignore this part */
Mainitem = (TextView) v.findViewById(R.id.textView1);
Mainitem.setText(item.Album_name);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("error", "wall");
}
}
}
return v;
}
/* Finally create a method which return the checkeditem postions in the listview */
**public ArrayList<Integer> getcheckeditemcount()
{
return this.checkedpositions;
}**
}
}
I hope this helps.

2 ListViews in the same activity

If I have 2 or more listviews in one activity,then how do I use a onclicklistener? I mean How do I know on which one of them the user click?
public void onItemClick(AdapterView parent, View v, int position, long id) {
}
The above code is what I used,however when I try to use another listview,I just can't find a way to detect which listview is clicked.
Any ideeas to solve this?
In this case, the parent is the listView from which the itemClick originated. So what you can do is keep a member variable for each ListView and compare the parent to those members to see which list triggered the click.
So here's a simple class with what I mean:
public class MyTest extends Activity{
private ListView list1;
private ListView list2;
public void onCreate(Bundle b){
super.onCreate(b);
list1 = new ListView();
list2 = new ListView(); //or findViewById if you declared them in your layout
//the rest of your creation code here
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
if(list1 == parent){
//handle list1 click
}else{
//handle list 2 click
}
}
}
There are two ways you can do it.
Implement OnItemClickListener
public class ListViewTest extends Activity implements OnItemClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
if(view ==myListView)1{
}
if(view ==myListView){
}
}
}
Set your own listener
myListView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on second listview
}
});
You can do it as this:
listView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on first listview
}
});
listView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on second listview
}
});
its pretty simple ,
only one list can act as the official list under a ListActivity and this list (and only this list) should have the special list id (#android:list i think) so just set the id of the other list to some other id and set its setOnItemClickListener to do whatever you want. I currently work on an app with 2 listViews and an additional list Fragment.

Categories

Resources