Android : Show loading image while check & download xml file - android

This is my code to check Internet and download XMl and show in a ListView
What I want is, while XML loads , show my custom layout or show a loading picture .
If I should Use AsynceTask please explain how . Thanks.
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, 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_COST,KEY_NAME,KEY_DESC,KEY_ID}, new int
[] {
R.id.cost,R.id.name,R.id.desciption,R.id.linke});
setListAdapter(adapter);

Yes, an AsyncTask would be good for this.
Show whatever image/layout you want while loading in onPreExecute(). You can use a ProgressDialog/ProgressBar if you want or show something else here.
Do your parsing in doInBackground()
Then dismiss your ProgressDialog/ProgressBar, image, or whatever you decide to use in onPostExecute(). Also, update your Adapter in this method.
You can make the AsyncTask an inner class of your Activity if you don't need it anywhere else to make it easier.
Be sure you read through the AsyncTask Docs a couple times to understand how they work.
Here is an example of setting up an AsyncTask

#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(activity, activity.getString(R.string.spinner_title), activity.getString(R.string.spinner_message_retrieving), true);}
#Override
protected void doInBackground() {
super.onPreExecute();
// do here network stuff
}
protected void onPostExecute(Void result) {
progress.dismiss();}
this is a part of your asynktask methode

Related

Get values from a XML contained in a String

I have a String variable containing an XML:
String xml = "<?xml version="1.0" encoding="utf-8" standalone="yes"?><CourtactSioux><ListeContact><IdContactClient>212</IdContactClient><DateContact>25/06/2012 08:09</DateContact><TypeForm>STANDARD</TypeForm><Foyer>2</Foyer><Civilite>M</Civilite><Nom>TEST</Nom><Prenom>JULIEN</Prenom><NomJeuneFille></NomJeuneFille></ListeContact></CourtactSioux>"
And I want to take values from this XML, how to do ?
For exemple: get "Civilite" value.
I tried this:
String xml = cn.getXml();
Integer demandeId = cn.getID();
XMLParser parser = new XMLParser();
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++) {
Element e = (Element) nl.item(i);
idApplication = parser.getValue(e, IdApplication);
idContactClient = parser.getValue(e, IdContactClient);
logement = parser.getValue(e, Logement);
typeForm = parser.getValue(e, TypeForm);
}
id = idApplication + idContactClient;
Product product = new Product()
.setId(id)
.setName(logement)
.setCategory(typeForm)
.setPrice(1)
.setQuantity(1);
ProductAction productAction = new ProductAction(ProductAction.ACTION_PURCHASE)
.setTransactionId(id)
.setTransactionAffiliation("Solutis")
.setTransactionRevenue(1);
HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
.addProduct(product)
.setProductAction(productAction);
Tracker t = ((App) getApplication()).getTracker();
t.setScreenName("transaction");
t.send(builder.build());
}
It's work, get attention on the aprent node of your xml
There are several ways of parsing XML in android. You could use XMLReader.parse(InputSource) by wrapping the string in a reader, as shown here
Check the Parsing XML Data part of Android Developers site for more information.

multiple item xml parsin in android

My XML is like this:
<?xml version="1.0" encoding="UTF-8"?>
<menu>
<item>
<id>1</id>
<name>Margherita</name>
<cost>
<p>155</p>
<p>255</p>
<p>355</p>
<p>455</p>
</cost>
<description>Single cheese topping</description>
</item>
<item>
<id>2</id>
<name>Double Cheese Margherita</name>
<cost>
<p>900</p>
<p>155</p>
</cost>
<description>Loaded with Extra Cheese</description>
</item>
<item>
<id>3</id>
<name>Fresh Veggie</name>
<cost>
<p>335</p>
</cost>
<description>Oninon and Crisp capsicum</description>
</item>
in cost tag I have other tags
I'm trying to parsing the xml with this:
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_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
I want to access to the child nodes, which here is and add another loop to access to all values
How to get access to childern nodes ?!
Your items are already stored in that list, you can get an element like this:
HashMap item = menuItems.get(0); // get the first item
Or you can loop through all elements in your list:
for (HashMap item: menuItems) {
// do something
}
Now you might wonder how you would access it's properties, you can use a HashMap like this:
String name = item.get(KEY_NAME);

Search the values in Arraylist of HashMap

I am trying to search, track name from arraylist of hashmap. I have searched lots of sites on this, but couldn't get any solution.
Here is the code for creating Arraylist of hash maps:
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
searchText = (EditText) findViewById(R.id.searchText);
//Count from the server
int count = dataCount();
for (int i = 0; i < dataCount; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
// adding data to HashMap key => value
map.put(KEY_ID, trackNumber);
map.put(KEY_TITLE, trackTitle);
map.put(KEY_ARTIST, trackArtist);
map.put(KEY_DURATION, trackDuration);
map.put(KEY_THUMB_URL, trackAlbumArt);
// adding HashList to ArrayList
songsList.add(map);
}
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
On TextChanged I am trying to get the search results and update the adapter with new results.
I was trying out similar logic that was given in
HashMap Searching For A Specific Value in Multiple Keys
Is it there a better way to Search HashMap from ArrayList
But couldn't get any results.
Thanks!
Option 1: Iterate the list items and search for a match:
// this code wasn't tested - but I'm sure you'll get the idea
Map getSong(String title) {
for(Map song : songsList) {
if(song.get(KEY_TITLE).equals(title)) {
return song;
}
}
return Collections.emptyMap();
}
Option 2 (preferred): save the songs into another Map (instead of a list) and use the title as the "key":
Map<String, HashMap<String, String>> songsList = new HashMap<String, HashMap<String, String>>();
// add a song:
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, trackNumber);
map.put(KEY_TITLE, trackTitle);
map.put(KEY_ARTIST, trackArtist);
map.put(KEY_DURATION, trackDuration);
map.put(KEY_THUMB_URL, trackAlbumArt);
// adding HashList to Map
songsList.put(trackTitle, map);
then you don't have to iterate a list to find your song, but simply do:
Map getSong(String title) {
return songsList.get(title);
}

Android parse a very simple XML Array

This might sound dumb, but I just need the help with the logic,
I have this very simple XML array:
<plist version="1.0">
<array>
<string>Lisa Jackson</string>
<string>Elisabeth Hartmann</string>
<string>C. J. Sansom</string>
<string>Irmengard Gabler</string>
<string>Oliver Pötzsch</string>
<string>Ulla Illerhaus</string>
<string>Christopher J. Sansom</string>
<string>Nina Blazon</string>
<string>Nicholas Lessing</string>
<string>Johannes Steck</string>
<string>Peter Kaempfe</string>
<string>Dimeter Inkiow</string>
<string>Barbara Sher</string>
<string>Ulrike Hübschmann</string>
<string>Otfried Preußler</string>
<string>Ulla Illerhaus</string>
<string>Annette Kurth</string>
</array>
</plist>
but when I try to parse it this way:
static final String KEY_ITEM = "string";
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>();
Element e = (Element) nl.item(i);
map.put(KEY_ITEM, parser.getValue(e, KEY_ITEM));
menuItems.add(map);
}
It displays the list based on the number of the given (17 list items) on the XML file, but it doesn't display any of the content, like 'Lisa Jackson', 'Elisabeth Hartmann', etc.
How can I resolve this?
element.getTextContent();
This will get the text value needed.
OR
for (int in = 0; in < numberOfChildren; in++) {
Node node = nl.item(in);
Log.d("skt",node.getNodeName() + " = " + node.getTextContent());
//node.getTextContent() has the text. Add it to map
}

How to parse XML (especific structure) in Android?

I need to parse a specific part of an XML obtained from a http request but I do not know how to do it!
I have the following XML structure being returned:
<categorias type="array">
<categoria>
<nome>
Alimentação
</nome>
<idcategoria>
5
</idcategoria>
<subcategorias>
<subcategoria>
<nome>
Todos
</nome>
<id>
5
</id>
</subcategoria>
</subcategorias>
</categoria>
</categorias>
I need to parse the data inside the subcategorias
tag because with the code I have now, I get only the upper tags, like
nome and idcategoria from the root tag categoria.
I've created a NodeList inside the for loop but it return all the subcategoria tags in the Document. And I need to get only the ones inside a unique categoria tag.
Here's the code I have now:
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));
// adding HashList to ArrayList
menuItems.add(map);
}
Can someone help me on this!?
Thanks in advance!
Have a look at this official document of Android which describe XMLPullParser.
You have to implement your logic according to your XML structure.
Aside from XMLPullParser, another option for parsing XML is to use the Simple XML library. It will allow you to easily deserialize that XML into an object which you can manipulate however you wish. It would be possible for you to ignore all other child elements in categoria and just capture subcategorias by using loose object mapping. Check the Simple Framework documentation for more information.
#Android Coader is right, "You have to implement your logic according to your XML structure"
Why do you have a KEY_ITEM, when there are no "item" tags in your XML? You need to specify in the code which tags you want to retrieve. For example, if you define a KEY_SUBCATEGORIA = "subcategoria", then to get all subcategory nodes you can do
NodeList nl = doc.getElementsByTagName(KEY_SUBCATEGORIA);
Then you should navigate through each node, pulling out the name and id's as you are doing now.
I got it!
I used only the same kind of structure I had before!
I added this code inside the for loop I had:
NodeList nlSubcategorias = e.getElementsByTagName("subcategoria");
ArrayList<HashMap<String, String>> subcategorias = new ArrayList<HashMap<String, String>>();
for (int j = 0; j < nlSubcategorias.getLength(); j++) {
HashMap<String, String> mapSub = new HashMap<String, String>();
Element eSub = (Element)nlSubcategorias.item(j);
mapSub.put(KEY_ID_SUB, parser.getValue(eSub, KEY_ID_SUB));
mapSub.put(KEY_NAME_SUB, parser.getValue(eSub, KEY_NAME_SUB));
subcategorias.add(mapSub);
System.out.println("subcategorias: " + subcategorias.get(j).get(KEY_NAME_SUB));
}
subcategoriasItems.add(subcategorias);

Categories

Resources