showing xml data into gridview in android - android

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.

Related

Filter ListView data

I am working on an App where data is read from XML, then based on the data, It creates an ListView and clicking on any item in ListView it opens another activity with details. I am trying to implement search functionality in the ListView, below is my code, I don't know how ti implement Search, I tried many ways but none of them worked. Any help is highly appreciated. Thanks in advance.
public class BrowseActors extends Activity {
private static final String TAG = "QuizListActivity";
private ImageView bannerImageView; // displays a Image
// Search EditText
private EditText inputSearch;
// XML node keys
static final String KEY_TAG = "ActorData"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_ICON = "icon";
String position;
String sourceFile;
// List items
ListView list;
//BinderActorData adapter = null;
List<HashMap<String, String>> actorDataCollection;
ArrayAdapter<HashMap<String, String>> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Remove title
setContentView(R.layout.browse_actor);
bannerImageView = (ImageView) findViewById(R.id.topImageView);
try {
// Get Category to filter
Intent in = getIntent();
this.position = in.getStringExtra("position");
sourceFile="BaseData.xml"
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(getAssets().open(sourceFile));
actorDataCollection = new ArrayList<HashMap<String, String>>();
// normalize text representation
doc.getDocumentElement().normalize();
NodeList quizList = doc.getElementsByTagName("ActorData");
HashMap<String, String> map = null;
for (int i = 0; i < quizList.getLength(); i++) {
map = new HashMap<String, String>();
Node firstQuestionNode = quizList.item(i);
if (firstQuestionNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstAircraftElement = (Element) firstQuestionNode;
// 1.-------
NodeList idList = firstAircraftElement
.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element) idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
// --id
map.put(KEY_ID, textIdList.item(0).getNodeValue()
.trim());
// 2.-------
NodeList nameList = firstAircraftElement
.getElementsByTagName(KEY_NAME);
Element firstNameElement = (Element) nameList.item(0);
NodeList textNameList = firstNameElement
.getChildNodes();
// --name
map.put(KEY_NAME, textNameList.item(0).getNodeValue()
.trim());
// 3.-------
NodeList iconList = firstAircraftElement
.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element) iconList.item(0);
NodeList textIconList = firstIconElement
.getChildNodes();
// -- Image Icon
map.put(KEY_ICON, textIconList.item(0).getNodeValue()
.trim());
// Add to the Arraylist
actorDataCollection.add(map);
}
}
BinderActorData bindingData = new BinderActorData(this,
actorDataCollection);
// Adding items to listview
list = (ListView) findViewById(R.id.list);
// Adding items to listview
inputSearch = (EditText) findViewById(R.id.inputSearch);
list.setAdapter(bindingData);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
//BrowseActors.this.bindingData.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(BrowseActors.this, ViewActor.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/*
* selected item parameters
*/
i.putExtra("name",
actorDataCollection.get(position).get(KEY_NAME));
i.putExtra("icon",
actorDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
} catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
}
Search will be implemented on original data source, it could be XML/JSON/database or anything else.
You're using "position" parameter for search, I think you can use the View view parameter.
Just keep a hidden field in the ListView row, and map it with some sort of primary key.
When OnClick event occurs, you can then get the row layout from view and do a findViewByID() call to get your hidden control. From the value of that control, you can call a back-end web service or run an x-path query or anything you want.

Android listview header

i have an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}

get the data from the webservice IOException

`the next code should pars data from the baseurl(web service) to textView
Problem:
*it gives IOException .. I'm sure from the webservice but the program still gives error any one help to get the data from the webservice??*
public class NewParsActivity extends Activity {
/** Called when the activity is first created. */
static final String baseUrl="http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml";
TextView tv;
EditText ed,ed2;
Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text);
ed=(EditText)findViewById(R.id.edt);
b=(Button) findViewById(R.id.button1);
ed2=(EditText) findViewById(R.id.editText1);
try{
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
XMLReader xr=sp.getXMLReader();
URL link=new URL(baseUrl);
handlXml doingWork=new handlXml();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(link.openStream()));
String information=doingWork.getInformation();
tv.setText(information);
}catch(Exception e){
tv.setText("Error");
}
//
public class handlXml extends DefaultHandler {
One item=new One();
public String getInformation(){
return item.DataToString();
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("website")){
String uniN=attributes.getValue("category");
item.setName(uniN);
}
}
}
//
<i>
public class One {
String UName;
public void setName(String n){
UName=n;
}
public String DataToString()
{
return "In"+UName;
}
}
<i>
Same example with API working fine for me.
XMLParsingExample.java
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getName().size()];
category = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
XMLParsing Sample Project
Here's my output Window -
have a look at this tutorial there is a good guide about xml parsing in android.i hope this will solve ur query
here i am putting that tutrial content
say we need to parse this xml file
http://api.androidhive.info/pizza/?format=xml
and here is a class for parsing this xml
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#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++) {
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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);
}
});
}
}
and complete guide about this can be found from this link
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

cannot in parsing nested xml structure

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);
}
}

android get nodelist attribute from xml file

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);
}
}

Categories

Resources