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&:,]","");
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();
Related
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);
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
I am trying to display data from xml file in to grid view in android, but this page is showing one error,can any one please make me clear.....
GridviewSample.java
public class GridviewSample extends Activity
{
// All static variables
static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders";
// XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_CUST = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
static final String KEY_STATION1 = "Station_Name";
static final String KEY_STATION2 = "Station_Name1";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView)findViewById(R.id.gridView1);
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_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_CUST, parser.getValue(e, KEY_CUST));
map.put(KEY_ORDER, parser.getValue(e, KEY_ORDER));
map.put(KEY_FREIGHT, parser.getValue(e, KEY_FREIGHT));
map.put(KEY_STATION1, parser.getValue(e, KEY_STATION1));
map.put(KEY_STATION2, parser.getValue(e, KEY_STATION2));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
SimpleAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.grid_item,
new String[] { KEY_CUST, KEY_ORDER, KEY_FREIGHT,KEY_STATION1,KEY_STATION2 }, new int[]
{
R.id.cust, R.id.order, R.id.freight,R.id.statio1,R.id.station2 });
gv.setAdapter(adapter);
gv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> Table, View v,int position, long id)
{
// getting values from selected GridItem
String cust = ((TextView) v.findViewById(R.id.cust)).getText().toString();
String order = ((TextView) v.findViewById(R.id.order)).getText().toString();
String freight = ((TextView) v.findViewById(R.id.freight)).getText().toString();
String station1 = ((TextView) v.findViewById(R.id.statio1)).getText().toString();
String station2 = ((TextView) v.findViewById(R.id.station2)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), Single_gridview_item.class);
in.putExtra(KEY_CUST, cust);
in.putExtra(KEY_ORDER, order);
in.putExtra(KEY_FREIGHT, freight);
in.putExtra(KEY_STATION1, station1);
in.putExtra(KEY_STATION2, station2);
startActivity(in);
}
});
}}
Thanks for you time!..
You should use an AsyncTask to perform the connection because otherwise the main thread can get stuck and Android will exit your application.
this is my xml structure :
<menu>
<item_category>
<category_name>ICECREAM</category_name>
<item>
<item_name>SOFTY</item_name>
<item_price>7.00</item_price>
</item>
<item>
<item_name>STICK</item_name>
<item_price>15.00</item_price>
</item>
<item>
<item_name>CONE</item_name>
<item_price>25.00</item_price>
</item>
</item_category>
<item_category>
<category_name>PIZZA</category_name>
<item>
<item_name>PIZZA-HOT</item_name>
<item_price>35.00</item_price>
</item>
<item>
<item_name>PIZZA-CRISPY</item_name>
<item_price>29.00</item_price>
</item>
</item_category>
</menu>
this is my code where i am parsing into list view
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://192.168.1.112/dine/index.php/dineout/mob_view";
//static final String URL = "http://192.168.1.112/dineout/index.php/dineout/view";
// XML node keys
static final String KEY_MENU= "menu"; // parent node
//static final String KEY_ID = "foodjoint_id";
static final String KEY_CATEGORY= "category_name";
static final String KEY_ITEM= "item";
static final String KEY_ITEM_NAME= "item_name";
static final String KEY_PRICE= "item_price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_CATEGORY, parser.getValue(e,KEY_CATEGORY));
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] {KEY_CATEGORY,KEY_ITEM_NAME,KEY_PRICE}, new int[] {R.id.category,R.id.name,R.id.costlab });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String category = ((TextView) view.findViewById(R.id.category)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//in.putExtra(KEY_ITEM, name);
in.putExtra(KEY_CATEGORY, category);
in.putExtra(KEY_ITEM_NAME,name);
in.putExtra(KEY_PRICE, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
My problem is i am not getting the value of category_name. I tried with nested loop but its all the same. please help me . what should i change in the code.
This is my xmlParser
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
try this way
NodeList n,ncategories;
Element e;
static final String KEY_ITEMCATEGORY= "item_category";
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
ncategories = doc.getElementsByTagName(KEY_MENU);
for(int i=0;i<ncategories.getLength();i++){
e=(Element)ncategories.item(i);
n=e.getElementsByTagName(KEY_ITEMCATEGORY);
for(int c=0;c<n.getLength();c++){
HashMap<String, String> map = new HashMap<String, String>();
e=(Element)n.item(c);
String category= parser.getValue(e, KEY_CATEGORY).toString();
Log.e("catname", parser.getValue(e, KEY_CATEGORY).toString());
map.put(KEY_CATEGORY, category);
NodeList ns=e.getElementsByTagName(KEY_ITEM);
for(int j=0;j<ns.getLength();j++){
e=(Element)ns.item(j);
Log.e("itemname", parser.getValue(e,KEY_ITEM_NAME).toString());
Log.e("itemprice", parser.getValue(e, KEY_PRICE).toString()+"\n");
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
}
menuItems.add(map);
}
Try something like this:
NodeList nl_Cat = doc.getElementsByTagName(KEY_ITEM_CATEGORY);
for (int i = 0; i < nl_Cat.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element cat = (Element) nl_Cat(i);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int j = 0; j < nl.getLength(); j++)
{
Element e = (Element) nl.item(j);
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
}
menuItems.add(map);
}
Hope this works!
You are retrieving list of item elements and trying to find category_name in item element. However, looking at your xml, category_name is sibling of item element, not child. So you will not get category name in that way.
You might want to retrieve list of item_category and then populate items from it.
NodeList nl_categories = doc.getElementsByTagName(KEY_ITEM_CATEGORY);
for(int i = 0; i < nl_categories; i++)
{
Element e = (Element) nl.item(i);
String category = parser.getValue(e,KEY_CATEGORY);
NodeList nl = e.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int j = 0; j < nl.getLength(); j++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(j);
map.put(KEY_CATEGORY, category);
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
menuItems.add(map);
}
}
I make listview from xml file http://view-source:http://www.macetlagi.com/maps/st/canvaser/3/tb/tb123.I will get element from "segment" tag.When i run and debug my code,i get this error java.lang.NullPointerException.Please correct my code if i do my stupid coding.This is my java code in android :
public class ListSegment extends ListActivity {
String URL_XML = "http://www.macetlagi.com/maps/st/canvaser/3/tb/tb123";
static final String KEY_SEGMENT = "segment";
static final String KEY_SEGMENT_ID = "segment_id";
static final String KEY_MAIN_SEGMENT = "main_segment_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listsegment_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL_XML);
Document doc = parser.getDomElement(xml);
NodeList nL = doc.getElementsByTagName(KEY_SEGMENT);
for (int i = 0; i < nL.getLength(); i++) {
Node node = nL.item(i);
if(node.hasAttributes()) {
NamedNodeMap attr_id = node.getAttributes();
attr_id.getNamedItem(KEY_SEGMENT);
}
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nL.item(i);
map.put(KEY_SEGMENT_ID, parser.getValue(e, KEY_SEGMENT_ID));
map.put(KEY_MAIN_SEGMENT, parser.getValue(e, KEY_MAIN_SEGMENT));
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[] {KEY_SEGMENT_ID, KEY_MAIN_SEGMENT}, new int[] {
R.id.segmentid, R.id.segmentname
});
setListAdapter(adapter);
}
}