Get selected checklist item expanding ListView Android - android

I've been following this logic: A multiple choice list view using expansible list
and managed to create a set of checkboxes in an expandinglistview.
So it looks something like:
catList = new ArrayList<GroupHead>();
countries = new ArrayList<Country>();
//Read the XML string
//Break down the XML into parts
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builders = factory.newDocumentBuilder();
Document document = builders.parse(new InputSource(new StringReader(XMLResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
NodeList nList = document.getElementsByTagName("Result");
System.out.println("----------------------------");
GroupHead cat1 = null;
List<GroupSession> result = new ArrayList<GroupSession>();
for (int temp = 0; temp < nList.getLength(); temp++)
{
NodeList TaskTopic = null;
Element day = (Element) nList.item(temp);
String Days = day.getAttribute("Day");
//Add one header (being the PracticalTopic)
cat1 = createCategory(Days);
TaskTopic = day.getElementsByTagName("Session");
for (int j = 0; j < TaskTopic.getLength(); ++j)
{
Element option = (Element) TaskTopic.item(j);
String optionText = option.getFirstChild().getNodeValue();
//Add multiple items and set them to that list
String[] results = optionText.split(", ");
String StartTimes = results[0];
String Lab = results[1];
sessions = new ArrayList<String>
(Arrays.asList(optionText));
ArrayList<String> citiesAustralia = new ArrayList<String>(
Arrays.asList(optionText));
countries.add(new Country(Days, citiesAustralia));
GroupSession item = new GroupSession(StartTimes, Lab);
result.add(item);
cat1.setItemList(result);
}
//Add them to the arrayList
catList.add(cat1);
}
}
}
catch (Exception e)
{
e.getMessage();
}
}
else
{
Toast.makeText(MainActivity.this, "There are no group sessions available for you", Toast.LENGTH_LONG).show();
}
adapter = new CountryAdapter(this, countries);
expListView.setAdapter(adapter);
// The choice mode has been moved from list view to adapter in order
// to not extend the class ExpansibleListView
adapter.setChoiceMode(CountryAdapter.CHOICE_MODE_MULTIPLE);
// Handle the click when the user clicks an any child
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener()
{
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id)
{
adapter.setClicked(groupPosition, childPosition);
return false;
}
});
Now what I'd like to do is click a button and return all the selected item values. I have something like this:
for (int i = 0; i < checked.size(); i++)
{
int position = checked.keyAt(i);
if (checked.valueAt(i) != null)
selectedItems.add(checked.valueAt(i));
}
but it's not allowing me to add the checked.valueAt(i). I just want to be able to read all the values from the checked list, but not finding anything that can help.
My adapter is the adapter taken from the example (way too long to add in here)
Please help!

int key = 0;
for(int i = 0; i < checked.size(); i++) {
key = checked.keyAt(i);
selectedItems.add(checked.valueAt(key));
}
Source: https://stackoverflow.com/a/8006994/4193263

Related

Error when selecting an item in my spinner

I am getting an error java.lang.String cannot be cast to java.util.HashMap when i select a data on my spinner. I retrieve my data in my spinner from my database. Im am trying to have just only 1 class, when i select a item on my spinner it checks the id in my database to show filter and show only the selected id
Here is my spinner select
ArrayList<HashMap<String,String>> list1 = new ArrayList<>();
try
{
JSONArray JA = new JSONArray(result);
JSONObject json;
s_name = new String[JA.length()];
s_gender = new String[JA.length()];
for(int i = 0; i<JA.length(); i++)
{
json = JA.getJSONObject(i);
s_gender[i] = json.getString("s_gender");
s_name[i] = json.getString("s_name");
}
list1.add("All");
for(int i = 0; i<s_name.length; i++)
{
list1.add(s_name[i] + " "+s_gender[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner_fn();
ArrayList<HashMap<String,String>> spinner = new ArrayList<Object>(Games.this, layout.simple_spinner_dropdown_item, s_name);
spinner1.setAdapter((SpinnerAdapter) spinner);
spinner1.setSelection(0);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Intent intent = null;
switch (position) {
case 1:
intent = new Intent(getApplication(), Basketball.class);
HashMap<Object, Object> map = (HashMap)parent.getItemAtPosition(position);
String news_id = map.get(Config.TAG_news_id).toString();
String title = map.get(Config.TAG_title).toString();
String content = map.get(Config.TAG_content).toString();
String n_date = map.get(Config.TAG_n_date).toString();
intent.putExtra(Config.News_id,news_id);
intent.putExtra(Config.Title,title);
intent.putExtra(Config.Content,content);
intent.putExtra(Config.N_date,n_date);
startActivity(intent);
break;
I am getting the error here saying in arraylist cannot be applied to java.lang.string
(Games.this, layout.simple_spinner_dropdown_item, s_name);
list1.add("All");
for(int i = 0; i<s_name.length; i++)
{
list1.add(s_name[i] + " "+s_gender[i]);
}
list1.add(s_name[i] + " "+s_gender[i]);
here is an error, as list1 is ArrayList of HASHMAP (you have a lot of hashmaps in one arraylist), and you've tried to add usual String to this list. May be you wanted the next:
for(int i = 0; i<s_name.length; i++)
{
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(s_name[i], s_gender[i]);
list1.add(hashMap);
}
//Remove this line
list1.add("All");
use this.
HashMap<String,String> stringHashMap=new HashMap<>();
for(int i = 0; i<s_name.length; i++)
{
stringHashMap.put(s_name[i],s_gender[i]);
list1.add(stringHashMap);
}
ArrayList<String> spinnerArray=new ArrayList<>();
Map<String, String> map = stringHashMap;
for (Map.Entry<String, String> entry : map.entrySet()) {
spinnerArray.add(entry.getKey());
}
ArrayAdapter<String> spinner = new ArrayAdapter<String>(Games.this, layout.simple_spinner_dropdown_item, spinnerArray);
spinner1.setAdapter(spinner);
spinner1.setSelection(0);

how to get all values of particular TextView of listView? -Android

i have made ListView with three columns 'item','qty','rate' i get this entries from the user and i have made the listview work perfectly but i want to get all the values of the 'rate' column and add them for the net amount.
Here is my android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
populateList();
adapter = new listviewAdapter(List.this, list);
lview.setAdapter(adapter);
}
private void populateList() {
HashMap temp = new HashMap();
list = new ArrayList<HashMap>();
item = etItem.getText().toString();
qty = etQty.getText().toString();
rate = etRate.getText().toString();
temp.put(FIRST_COLUMN, "1");
temp.put(SECOND_COLUMN, item);
temp.put(THIRD_COLUMN, qty);
temp.put(FOURTH_COLUMN, rate);
list.add(temp);
}
I tried out this method below but it only toast the first value.But i want to get all the values under the rate column and add them up for the net-amount.
public void get() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<adapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.FourthText)).getText().toString();
adapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
}
text = sb.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I think this might help you.
private int GrandTotal(ListView list) {
int sum=0;
for (int i = 0; i < list.getCount(); i++) {
View v = list.getChildAt(i);
TextView rate = (TextView) v.findViewById(R.id.rate);
sum = sum + Integer.parseInt(rate.getText().toString() )
}
return sum;
}
:)
public void getTotalRate() {
int totalRate = 0;
for (int i = 0; i < list.size(); i++) {
HashMap temp = list.get(i);
/// here fourth column is rate
int rate = (int) temp.get(FOURTH_COLUMN);
totalRate = totalRate + rate;
}
Toast.makeText(getApplicationContext(), "total rate=" + totalRate, Toast.LENGTH_LONG).show();
}

Why does variables changes depending on android version?

I got ListView with simpleAdapter. If I click on some item in my List view it show me 2 diferent variables.
Some code:
// Listview Data
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(Invoice_numberArr.length);
Map<String, Object> m;
for(int i = 0; i<Invoice_numberArr.length; i++){
int str = Integer.parseInt(Invoice_numberArr[i]);
int str2 = Integer.parseInt(InvoiceNumberForDetails);
if(str == str2){
m = new HashMap<String, Object>();
m.put(ATT_INU, Invoice_numberArr[i]);
m.put(ATT_ANU, Article_numberArr[i]);
m.put(ATT_AMO, AmountArr[i]);
m.put(ATT_PRE, PriceArr[i]);
m.put(ATT_TPR, Total_priceArr[i]);
m.put(ATT_SDE, Sale_designationArr[i]);
data.add(m);
}
}
String[] from = {ATT_INU, ATT_ANU, ATT_AMO, ATT_PRE, ATT_TPR, ATT_SDE};
int[] till = {R.id.txtInvoice_number, R.id.txtArticle_number, R.id.txtAmount, R.id.txtPrice, R.id.txtTotalPrice, R.id.txtSale_designation};
//activities elements
invoices_list_details_view = (ListView)findViewById(R.id.invoices_list_details_view);
invoicesDetailsSAdapter = new SimpleAdapter(InvoicesDetails.this, data, R.layout.invoices_list_item_details_view, from , till);
invoices_list_details_view.setAdapter(invoicesDetailsSAdapter);
Utility Utility = new Utility();
Utility.setListViewHeightBasedOnChildren(invoices_list_details_view);
//if item clicked
invoices_list_details_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String positions = parent.getAdapter().getItem(position).toString();
//int positions = parent.getAdapter().;
parent.getAdapter();
int indexPos = -1; // if doesnt exist
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
//some int to transfer it to position class
int integerr = indexPos;
Intent invoices_details_position = new Intent(InvoicesDetails.this, InvoicesDetailsPosition.class);
invoices_details_position.putExtra("saleDesignationForPosition", Sale_designationArr[indexPos]);
invoices_details_position.putExtra("articleNumberForPosition", Article_numberArr[indexPos]);
invoices_details_position.putExtra("sequenceNumberForPosition", Sequence_numberArr[indexPos]);
invoices_details_position.putExtra("amountForPosition", AmountArr[indexPos]);
invoices_details_position.putExtra("warehouseForPosition", WarehouseArr[indexPos]);
invoices_details_position.putExtra("containerDescriptionForPosition", Container_descriptionArr[indexPos]);
invoices_details_position.putExtra("priceForPosition", PriceArr[indexPos]);
invoices_details_position.putExtra("discountForPosition", DiscountArr[indexPos]);
invoices_details_position.putExtra("totalPriceForPosition", Total_priceArr[indexPos]);
startActivity(invoices_details_position);
}
});
So if clicked on my item from ListView under android 4.3 till 5.0 varible
String positions = parent.getAdapter().getItem(position).toString();
shows me
string " {prices=10.8, article_numbers=0736, amounts=1, sale_designations=Pfirsichlikör, invoice_numbers=1, total_prices=10.8} "
And if I clicked under Android version 5.1 its shows me
string " {article_numbers=0736, sale_designations=Pfirsichlikör, amounts=1, invoice_numbers=1, prices=10.8, total_prices=10.8} "
Because that I need to check it twice with that
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
So my question now why does it changes depending on Android version ?
Thx for help.
Thank #Mike M. LinkedHashMap s instead HashMap s works for all Android

SparseBooleanArray giving true for unchecked items in listview

My listview is from a layout where its id is #android:id/list. It is part of the android.R.id.list. I used a SimpleCursorAdapter to setAdapter to listview. The listview contains checkboxes with contact names such as Emily Andrews, Susan John... I wanted to know the names of the contacts which were selected by the user. When using the code below, for some reason, it gives me random contact names in my unchecked list. For instance though I have Emily checked, and Matt Jones unchecked. It has both of them in the unchecked list. Also, no matter what i check and uncheck in the listview, it always gives me the first two contacts in my unchecked list and doesn't print anything for my checked list. Is there any way I can solve this?
public void blockCheckedItems(View view) {
// int cntChoice = lv.getCount();
checked = new ArrayList<String>();
unchecked = new ArrayList<String>();
int itempositions=adapter.getCount();
SparseBooleanArray sparseBooleanArray = lv.getCheckedItemPositions();
int countChoice = lv.getChildCount();
Log.d("" + countChoice, "CountChoice===============================");
Log.d("" + sparseBooleanArray,"sparseBooleanArray -------------------------");
for(int i = 0; i < countChoice; i++)
{
if(sparseBooleanArray.valueAt(i) == true)
{
Cursor cursor = (Cursor) lv.getItemAtPosition(i);
String name = cursor.getString(1);
checked.add(name);
}
else if(sparseBooleanArray.valueAt(i) == false)
{
Cursor cursor = (Cursor) lv.getItemAtPosition(i);
String name = cursor.getString(1);
unchecked.add(name);
}
}
for(int i = 0; i < checked.size(); i++){
Log.d("checked list&&&&&&&&&&&&&&&&&&&", "" + checked.get(i));
}
for(int i = 0; i < unchecked.size(); i++){
Log.d("in unchecked list&&&&&&&&&&&&&&&&&&&", "" + unchecked.get(i));
}
}
try this and let me know if i am wrong
public void blockCheckedItems(View view) {
ArrayList<String> checked = new ArrayList<String>();
ArrayList<String> unchecked = new ArrayList<String>();
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for (int i = 0; i < listView.getCount(); i++) {
Cursor cursor = (Cursor) listView.getItemAtPosition(i);
String name = cursor.getString(1);
if (sparseBooleanArray.get(i)) {
checked.add(name);
} else {
unchecked.add(name);
}
}
for (int i = 0; i < checked.size(); i++) {
Log.d("checked list&&&&&&&&&&&&&&&&&&&", "" + checked.get(i));
}
for (int i = 0; i < unchecked.size(); i++) {
Log.d("in unchecked list&&&&&&&&&&&&&&&&&&&", "" + unchecked.get(i));
}
}

removing selected item in listview in android

Can somebody please give me an example code of removing a selected item in a listview ?.
i am using simple adapter to store the data.
My code is..
static final String KEY_ITEM = "finance"; // parent node
static final String KEY_ID = "finance";
static final String KEY_NAME = "company";
static final String KEY_COST = "high";
static final String KEY_DESC = "volume";
static final String KEY_SYMBOL="symbol";
static final String KEY = "low";
private String selectedItem;
private ListAdapter adapter;
Context context;
ListView lv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView titleBar = (TextView)getWindow().findViewById(android.R.id.title);
titleBar.setTextColor(Color.GREEN);
final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
Node theAttribute;
Element e = (Element) nl.item(i);
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
HashMap<String, String> map = new HashMap<String, String>();
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
// lblName.setTypeface(hindiFont);
//s = s.replaceAll("[-;#39&amp:,]","");
map.put(KEY_NAME,s);
}
}
NodeList n4 = e1.getElementsByTagName(KEY_SYMBOL);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n4.getLength(); k++) {
Element e2 = (Element) n4.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
for (int a = 0; a < attributes2.getLength(); a++)
{
// HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
map.put(KEY_SYMBOL,s);
// menuItems.add(map);
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
//HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
map.put(KEY_COST,theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
for (int a = 0; a < attributes2.getLength(); a++)
{
// HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
map.put(KEY_DESC,s);
// menuItems.add(map);
}
} NodeList n3 = e1.getElementsByTagName(KEY);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n3.getLength(); k++) {
Element e2 = (Element) n3.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
for (int a = 0; a < attributes2.getLength(); a++)
{
// HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
map.put(KEY,s);
// menuItems.add(map);
}
}
menuItems.add(map);
}
}
// Adding menuItems to ListView
adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST,KEY,KEY_SYMBOL }, new int[] {
R.id.name, R.id.desciption, R.id.cost,R.id.low,R.id.symbol }){
};
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
/* String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
*/
// Starting new intent
/*Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);*/
Toast.makeText(getApplicationContext(), "on clicked",Toast.LENGTH_LONG).show();
}
});
// Create the listener for long item clicks
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long rowid) {
final View view=v;
// Store selected item in global variable
selectedItem = parent.getItemAtPosition(position).toString();
// Toast.makeText(getApplicationContext(), "select item"+selectedItem,Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidXMLParsingActivity.this);
builder.setMessage("Do you want to remove " + "?");
final int positionToRemove = position;
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
adapter.remove(selectedItem);
adapter.notifyDataSetChanged();
Toast.makeText(
getApplicationContext(),
selectedItem + " has been removed.",
Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
// Signal OK to avoid further processing of the long click
return true;
}
};
getListView().setOnItemLongClickListener(itemLongListener);
}
}
it show the error in these line
adapter.remove(selectedItem);
adapter.notifyDataSetChanged();
it show
The method remove(String) is undefined for the type ListAdapter
add to cast adapter
please help me with example code!!!!
thanks in advance!!!!!!!!
Change from ListAdapter SimpleAdapter.
private SimpleAdapter adapter;
Make menuItems global.
And then you can do
menuItems.remove(selectedItem);
adapter.notifyDataSetChanged();

Categories

Resources