I have a list view that displays records from a database. Each row in the listview has a checkbox. How do I...
Create a toast message displaying the value of the selected item?
Identify the records selected by the user in the listview?
Iterate through each selected item and delete only the rows selected in the listview from the database?
I've been following this helpful tutorial here: //http://www.vogella.com/articles/AndroidSQLite/article.html
public class PhoneNumberDataBaseListView extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
String number = "123";
datasource.createNumber(number);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
}
public void deleteNumber() {
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
ListView LV = (ListView) findViewById(android.R.id.list);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
SparseBooleanArray checkedItems = LV.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
Number item = adapter.getItem(i);
Toast t = Toast.makeText(this, item.getNumber().toString(), Toast.LENGTH_LONG);
t.show();
}
}
}
Method getCheckedItemPositions() returns SparseBooleanArray that indicates which items are checked (if item on specific position is checked, method valueAt(position) invoked on that array returns true). Class DBAdapter from tutorial you are following provides you with deleteTitle(long rowId) method which you should use to acheive what you want.Therefore your code should look more or less like this:
SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
db.deleteTitle(adapter.getItemId(i));
}
}
Of course SimpleCursorAdapter and DBAdapter should be stored in object attributes so that you have access to them from both methods (onCreate and deleteRecord). By the way, View parameter passed to deleteRecord method is not needed.
Related
I need some help guys.
The problem is that I have a spinner that has commodities in it, such as chemicals,biscuits etc. but these commodities are stored in the database. I have written a web service that retrieves the commodities and the corresponding commodity code from database the web service works fine. I am getting the data in my android code. So I have stored the commodity in one array list say ar1, and the commodity code in one more array list say ar2. Now I want these commodity, what I have stored in ar1 to be displayed as spinner items and when user selects one of the spinner items, I must be able to retrieve the corresponding commodity code of that commodity.
Can some body help me??
I am using the below code but i am not able to get the desired result
String[] arr_Commodities = new String[ar2.size()];
spinnerMap = new HashMap<String, String>();
for (int i = 0; i < ar2.size(); i++)
{
spinnerMap.put(ar2.get(i),ar1.get(i));
arr_Commodities[i] = ar2.get(i);
System.out.println(arr_Commodities[i]);
}
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
spin_commodity.setAdapter(adapter);
I find nothing is wrong with this code but i am still not able to pop[ulate the spinner some one please modify the above code..thank you
you can try this and improvise the loop on populating items:
final ArrayList<String[]> items = new ArrayList<String[]>();
for(int i= 0; i <10 ; i++){//sample loop populating items
String[] item = new String[2];
item[0] = "id";
item[1] = "commodities";
items.add(item);
}
Spinner s = new Spinner(context);//sample spinner
ArrayAdapter<String[]> adapter = new ArrayAdapter<String[]>(context , android.R.layout.simple_list_item_1, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
String[] selected = items.get(position);
//commodity id
String comId = selected[0];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
String[] ar1={"chemicals","biscuits"};
String[] ar2={"1","2"};
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar1); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
your_spinner.setAdapter(adapter);
//to get the selected item position
int x=your_spinner.getSelectedItemPosition();
Your required code is
String code=ar2[x];
I am attempting to pass selected items on a list to a new activity.
I declared an ArrayAdapter
ArrayAdapter madapter
Before OnCreate; in OnResume, I collect the data; and assign it to mAdapter
//variable mAdapter
//new ArrayAdapter string
madapter = new ArrayAdapter<String>(
SearchingMidwife.this,
android.R.layout.simple_list_item_checked,
locations);
//set List to display mAdapter
And then I have this, that should allow for, when a listItem is clicked, to get selected items into a variable, and pass it to a new activity
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//in checked, in listview get Item positions for checked items
SparseBooleanArray checked = l.getCheckedItemPositions();
//assign selected items to new String ArrayList
ArrayList<String> selectedItems = new ArrayList<String>();
//determine size of items checked (number)
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
position = checked.keyAt(i);
// Add location if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
//add selected items to madapter
selectedItems.add(madapter.getItem(position));
}
//create string output array, store new string array with selected items
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(getApplicationContext(),
MidwifeResultList.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
I have a result activity that is designed to collect the selected item and display it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_midwife_result_list);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("SelectedItems");
ListView lv = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
When I run the program, I can see the listItem results, but when I select one the program stops, and there is this error:
Unable to start activity ComponentInfo{android.bignerdranch.com.mobilemidwife/android.bignerdranch.com.mobilemidwife.MidwifeResultList}: java.lang.NullPointerException: storage == null
pointing to this line of code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultArr);
The code seems to be right...why would there be a null value on resultArr?
b.putStringArray("selectedItems", outputStrArr);
...
String[] resultArr = b.getStringArray("SelectedItems");
You have a typo, in one place you write "selectedItems" and in another you write "SelectedItems". Notice the first letter is capitalized in one but not the other. You should change them to be the same.
Hi am using multiple choice list
can any one tell me how should i select all
item on any button click event
or how unselect all item on button click event
my code is here
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_list);
findViewsById();
PhoneContacts pc = new PhoneContacts(ContactList.this);
pc.readContacts();
for (int i = 0; i < pc.allPhoneNumbers.size(); i++) {
_allNumberAndNameMergeList.add(pc.allContactName.get(i) + "\n"
+ pc.allPhoneNumbers.get(i));
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
_allNumberAndNameMergeList);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
button.setOnClickListener(this);
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.list);
button = (Button) findViewById(R.id.testbutton);
}
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
}
}
Hi am using multiple choice list
can any one tell me how should i select all
item on any button click event
or how unselect all item on button click event
I would create custom adapter that extends ArrayAdapter and ListView item that would contain e.g. CheckBox. Than inside adapter class getView() method handle selected items position to get objects on current position and you can do anything you wish. You can have a look at this tutorial - 12. Selecting multiple items in the ListView
http://www.vogella.com/articles/AndroidListView/article.html
I have a ListView with multiple checkboxes (one for each list item). What would be the best way to create an array containing information from the selected checkboxes.
For Example, here's a list.
Item 1 "Ham" Checked
Item 2 "Turkey" NotChecked
Item 3 "Bread" Checked
I would like to create an array containing "ham" and "turkey"
If you used ListView's built-in checkbox method with setChoiceMode() then you only need to call getCheckedItemIds() or getCheckedItemPositions().
public class Example extends Activity implements OnClickListener {
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.list);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Log.v("Example", "Checked: " + array[positions.keyAt(index)]);
}
}
}
If the Adapter is bound to a Cursor, then this becomes much more practical.
I create checkboxes dynamically & i want to bind that checkboxes to listview.
How can I do that?
Here i give my code--
public class HomeActivity extends ListActivity{
CheckBox[] chk;
ListView lv1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.listTasks);
tv1=(TextView) findViewById(R.id.tvMsg);
The database section:
db = new DBAdapter(HomeActivity.this);
db.open();//int[] id=new int[]{Integer.parseInt(DBAdapter.ID)};
Cursor cr=db.getUncompletedTask();//my database function to retrieve values to create checkboxes
if (cr.moveToFirst()) {
do {
String[] str=new String[2];
str[0]=cr.getString(0);
str[1]=cr.getString(1);
al.add(str);
} while (cr.moveToNext());
}
startManagingCursor(cr);
String[] tasks = new String[] { DBAdapter.KEY_TODO };
Creation of checkbox:
int[] idchk=new int[al.size()];//here i am creating checkbox dynamicaly
if (al.size() != 0) {
chk = new CheckBox[al.size()];
System.out.println(al.size());
for (int i = 0; i < al.size(); i++) {
String[] s = (String[]) al.get(i);
System.out.println("ID: "+s[0]);
Task_Id = Integer.parseInt(s[0]);
Task_Nm = s[1];
chk[i] = new CheckBox(HomeActivity.this);
System.out.println(i +"task id"+Task_Id +"parseint"+Integer.parseInt(s[0]+chk[i].getText().toString()));
chk[i].setId(Task_Id);
idchk[i]=Task_Id;
chk[i].setText(Task_Nm);
//lv1.addView(chk[i]);
//setContentView(lv1);
}}}
Here what can i write here so that this dynamically created checkboxes will be bind to listview
What if you use the default listview of android with checkbox.
By using :
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, COUNTRIES));
where COUNTRIES is static final string array that contains the item to show..
You can use customized ListView whose rows contains CheckBox. Create your own adapter extending ArrayAdapter and it's overridden method getView create your checkboxes.