parsing xml data from url - android

how can i parse and retrieve the data from the following xml?
<?xml version="1.0" encoding="iso-8859-7"?>
<PRODUCT id='107230' name='WESTERN DIGITAL 2TB WD20EZRX [SATA 3 - 64MB]' price='89.00' photo='http://www.priveshop.gr/products/WD20EZRX_A.jpg'></PRODUCT>
public class MainActivity extends Activity {
// Declare Variables
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String PRODUCT = "PRODUCT";
static String RANK = "id";
static String COUNTRY = "name";
static String POPULATION = "price";
//static String FLAG = "photo";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadXML().execute();
}
// DownloadJSON AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("XtronLabs");
// Set progressdialog message
mProgressDialog.setMessage(" xtron searchin your web.............wait.");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrive nodes from the given website URL in XMLParser.class
String xml = parser.getXmlFromUrl("http://www.priveshop.gr/exte/android/xml_listing.php?key=12121212&id=1072");
// Retrive DOM element
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(PRODUCT);
// try {
// Locate the NodeList name
// Toast.makeText(MainActivity.this,PRODUCT , Toast.LENGTH_SHORT).show();
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(PRODUCT, parser.getValue(e, PRODUCT));
map.put(RANK, parser.getValue(e, RANK));
map.put(COUNTRY, parser.getValue(e, COUNTRY));
map.put(POPULATION, parser.getValue(e, POPULATION));
// map.put(FLAG, parser.getValue(e, FLAG));
// adding HashList to ArrayList
arraylist.add(map);
}
// } catch (Exception e) {
// Log.e("Error", e.getMessage());
//e.printStackTrace();
// }
// Toast.makeText(MainActivity.this, "button" +" "+ PRODUCT, Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
We can only get the length from the XML not the actual data... can anyone tell me what went wrong?

Related

CDATA parsing java file xml

Hi i have this code for parsing :
This is file xml i have need parse whit CDATA:
<[CDATA [!
Ue, via libera alla Missione navale Contro Gli scafisti: Comando all'Italia
]]>
public class MainActivity extends Activity {
// Declare Variables
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "title";
static String COUNTRY = "description";
static String POPULATION = "pubDate";
static String FLAG = "link";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadXML().execute();
}
// DownloadJSON AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android XML Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
String xml = parser
.getXmlFromUrl("http://www.aduc.it/generale/files/feed/avvertenze_rss.xml");
// Retrive DOM element
Document doc = parser.getDomElement(xml);
try {
// Identify the element tag name
NodeList nl = doc.getElementsByTagName("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(RANK, parser.getValue(e, RANK));
map.put(COUNTRY, parser.getValue(e, COUNTRY));
map.put(POPULATION, parser.getValue(e, POPULATION));
map.put(FLAG, parser.getValue(e, FLAG));
// adding HashList to ArrayList
arraylist.add(map);
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
This is file xml i have need parse whit CDATA:
<[CDATA [!
Ue, via libera alla Missione navale Contro Gli scafisti: Comando all'Italia
]]>

parse Xml data like json parse

I am developing android application and I got a error When I parse XML data like Json.I confused how many array has this data? I share code at below. can anyone help me or sharing example code like this xml data?
public class MainActivity extends Activity implements OnRefreshListener,
OnClickListener {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
JSONArray jsonarray2;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
Button btngeri;
static Integer[] imageId = { R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
btngeri = (Button) findViewById(R.id.btn_geri);
btngeri.setOnClickListener(this);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Mail Kutusu");
// Set progressdialog message
mProgressDialog.setMessage("Güncelleme Yapılıyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://78.186.62.169:8210/AnketServis.asmx/Message");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("MessageVO");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
// map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("Konu"));
// map.put("population",
// jsonobject.getString("population"));
// map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist, imageId);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
Yo cannot parse xml file like json. You have to use xml parser. There are two parse method. SAX and Dom. Yo can see the versus about them.
What is the difference between SAX and DOM?
And You can see the an xml parser sample in android.
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

Android Search specific item in Listview

i have implemented a search bar in my listview,but now how can show my result?i get the values from a xml file(hosted on my server) there is a way to search in this file and show the results?My idea is a search from first letter
useful,but my xml file is frequently upgraded i can't use this method,i need that while typing my listview show the result(just like your example,but with action bar)
this is the script:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadXML AsyncTask
new DownloadXML().execute();
}
// DownloadXML AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
//Disable dismiss ultil load end
mProgressDialog.setCanceledOnTouchOutside(false);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
String xml = parser.getXmlFromUrl("http://192.172.11.18/prova/xmlparseimgtxt.xml");
// Retrive DOM element
Document doc = parser.getDomElement(xml);
try {
// Identify the element tag name
NodeList nl = doc.getElementsByTagName("my_elements");
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(zeroElement, parser.getValue(e, zeroElement));
map.put(firstElement, parser.getValue(e, firstElement));
map.put(secondElement, parser.getValue(e, secondElement));
map.put(thirdElement, parser.getValue(e, thirdElement));
map.put(fourthElement, parser.getValue(e, fourthElement));
// adding HashList to ArrayList
arraylist.add(map);
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

Progress Dialog is shown only for a very little time in Async Task and the activity loading is slow

I'm developing my first Android application and i want to show a progress dialog until a xml file is being processed in doInBackground method. This activity is loaded in response to an onclick event. Unexpectedly, activity takes several seconds to show up and the progress dialog is shown for a very little time (several milliseconds).
This is my code. I have used AsyncTask as an inner class. I just can't find where i have gone wrong.
public class WhatToSee extends ListActivity {
ListView whatToSee;
ArrayList<HashMap<String, String>> whatToSeeInfo = new ArrayList<HashMap<String, String>>();
WhatToSeeAdapter adapter;
String cityName;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.whattosee);
cityName = getIntent().getStringExtra("name");
whatToSee = (ListView) findViewById(android.R.id.list);
adapter= new WhatToSeeAdapter(this, whatToSeeInfo);
whatToSee.setAdapter(adapter);
new WhatToSeeLoader().execute();
}
public class WhatToSeeLoader extends AsyncTask<Void, String, String> {
ProgressDialog progress = new ProgressDialog(WhatToSee.this);
String url = "http://wearedesigners.net/clients/clients12/tourism/fetchWhatToSeeList.php";
final String TAG_MAIN = "item";
final String TAG_ID = "itemId";
final String TAG_NAME = "itemName";
final String TAG_DETAIL = "itemDetailText";
final String TAG_MAP = "itemMapData";
final String TAG_ITEM_IMAGE = "itemImages";
final String TAG_MAP_IMAGE = "mapImage";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(TAG_MAIN);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress.setMessage("Loading What To See List");
progress.setIndeterminate(true);
progress.show();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
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(TAG_ID, parser.getValue(e, TAG_ID));
map.put(TAG_NAME, parser.getValue(e, TAG_NAME));
map.put(TAG_DETAIL, parser.getValue(e, TAG_DETAIL));
map.put(TAG_MAP, parser.getValue(e, TAG_MAP));
map.put(TAG_MAP_IMAGE, parser.getValue(e, TAG_MAP_IMAGE));
map.put(TAG_ITEM_IMAGE, parser.getValue(e, TAG_ITEM_IMAGE));
// adding HashList to ArrayList
whatToSeeInfo.add(map);
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notifyDataSetChanged();
progress.dismiss();
}
}
}
Can someone please help me with this?
Thank you in advance.
Most probably call String xml = parser.getXmlFromUrl(url); // getting XML slows down Your code. It get executed in main thread and I expect it (from its name) to do some network related staff which basically should be done not in UI thread (e.g. in Yours doInBackground method).
So, to fix try to move that initialization staff related to xml inside doInBackground().

Categories

Resources