Android: populating listview from arrayadapter / arraylist - android

I am making an app which is polling an XML sheet from a url through AsyncTask, so it does'nt interfere with the mainThread.
I have been able to make the connection, retrieve the xml and parse the values in a loop and add these to an arraylist.
My problem is that when the app is loading on the handset, the arraylist should be transformed to an arrayadapter and then populate the listview in the app.
I've got it to work with an hardcoded xml file, but when I try to use the parsed values from my dynamic xml, then the app fails.
This code is getting the XML sheet and adds it to an arraylist "menuItems" - this works fine
#Override
protected Boolean doInBackground(String... params) {
Log.d("beskeden", "Henter adressen: " + URL);
try{
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>();
map.put(KEY_NAVN, nl.item(i).getChildNodes().item(1).getTextContent());
map.put(KEY_BESKRIVELSE, nl.item(i).getChildNodes().item(1).getTextContent());
map.put(KEY_THETYPE, nl.item(i).getChildNodes().item(1).getTextContent());
map.put(KEY_THETIMER, nl.item(i).getChildNodes().item(1).getTextContent());
map.put(KEY_THEGRADER, nl.item(i).getChildNodes().item(1).getTextContent());
map.put(KEY_THESEMERE, nl.item(i).getChildNodes().item(1).getTextContent());
map.put(KEY_IDP, nl.item(i).getChildNodes().item(1).getTextContent());
Log.e("Beskeden", nl.item(i).getChildNodes().item(1).getNodeName() + ": " + nl.item(i).getChildNodes().item(1).getTextContent());
Log.e("Beskeden", nl.item(i).getChildNodes().item(3).getNodeName() + ": " + nl.item(i).getChildNodes().item(3).getTextContent());
Log.e("Beskeden", nl.item(i).getChildNodes().item(5).getNodeName() + ": " + nl.item(i).getChildNodes().item(5).getTextContent());
Log.e("Beskeden", nl.item(i).getChildNodes().item(7).getNodeName() + ": " + nl.item(i).getChildNodes().item(7).getTextContent());
menuItems.add(map);
}
Log.d("beskeden", "Antal theer: " + nl.getLength());
Log.d("beskeden", "Xml er blevet parset");
return true;
} catch (Exception e){
return false;
}
}
The following code is doing so i can't compile and test it - so frustating :/
//#Override
protected void onPostExecute(final Boolean success) {
//super.onPostExecute(result);
Log.d("Besked", "Post executen");
if (success) {
Log.d("Beskeden", "SUCCES!!");
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item, menuItems);
}else{
Log.d("Beskeden", "FAIL!!");
}
I am a bit stuck, so any help is welcome :)

Related

xml parsing and show the data in a list view

I have a xml file like [this][1] and i need to get the all the "edition name" according to the "group name"
I have to create a list of group name and show the list of editions name on clicking of the group name.
OutPut :
onclick of catalogs :
this xml is present in different languages, is there any way to get all the editions name without comparing with group name.
currently i am using type tag to get all the catalogs
:
if(parser.getValue(ele2, "type").toString().equalsIgnoreCase("catalog"))
But some magazines are also present in catalogs type. so not getting correct results
..
How to get all the editions name where group name is catalogs and so on ...
Or a better way to do so.. I am not sure the code I am using is a good approach.
Kindly suggest.
My code :
final String URL = "http://xml/web/?frg="+lang+"&user="+count+"_"+user;
System.out.println("URL child : " + URL);
parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("groups");
for (int i = 0; i < 1; i++) { //ToDo : worked temp
Element e = (Element) n1.item(0);
NodeList children = e.getChildNodes();
if(item_name.equalsIgnoreCase("Catalogs")||item_name.equalsIgnoreCase("Kataloge")) // there could be other languages
{
NodeList nodeList2 = doc.getElementsByTagName("edition");
for (int k = 0; k < nodeList2.getLength(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
Element ele2 = (Element) nodeList2.item(k);
if(parser.getValue(ele2, "type").toString().equalsIgnoreCase("catalog"))
{
System.out.println(""+parser.getValue(ele2, "name").toString());
System.out.println(""+parser.getValue(ele2, "cat_url").toString());
map.put(ss2, parser.getValue(ele2,ss2 ));
map.put(KEY_THUMB_URL, parser.getValue(ele2, KEY_THUMB_URL));
map.put(CAT_URL, parser.getValue(ele2,"cat_url"));
// adding HashList to ArrayList
songsList.add(map);
}
}
}
if(item_name.equalsIgnoreCase("Magazines")||item_name.equalsIgnoreCase("Magazine"))
{
NodeList nodeList2 = doc.getElementsByTagName("edition");
for (int k = 0; k < nodeList2.getLength(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
Element ele2 = (Element) nodeList2.item(k);
if(parser.getValue(ele2, "type").toString().equalsIgnoreCase("pdf"))
{
System.out.println(""+parser.getValue(ele2, "name").toString());
System.out.println(""+parser.getValue(ele2, "cat_url").toString());
map.put(ss2, parser.getValue(ele2,ss2 ));
map.put(KEY_THUMB_URL, parser.getValue(ele2, KEY_THUMB_URL));
map.put(CAT_URL, parser.getValue(ele2,"cat_url"));
// adding HashList to ArrayList
songsList.add(map);
}
}
}
if(item_name.equalsIgnoreCase("Instructions"))
{
NodeList n2 = doc.getElementsByTagName("groups");
for (int i1 = 0; i1 < 1; i1++) { //ToDo : worked temp
Element e1 = (Element) n2.item(0);
NodeList children1 = e1.getChildNodes();
for (int j = 0; j <children1.getLength(); j++) {
HashMap<String, String> map = new HashMap<String, String>();
child = children1.item(j);
// System.out.println("name node22 inside " + parser.getValue((Element)child, "name"));
if(parser.getValue((Element)child, "name").equals("Instructions"))
{
if (child.getNodeName().equalsIgnoreCase("group")) {
NodeList nl2 = child.getChildNodes();
System.out.println("Nodelist lenght : " + nl2.getLength());
for (int jj = 0; jj <nl2.getLength(); jj++) {
Node nn =nl2.item(jj);
System.out.println("name node22 inside " + parser.getValue((Element)nn, "name"));
}
// map.put(KEY_TITLE, parser.getValue((Element)child,KEY_TITLE ));
//map.put(KEY_THUMB_URL, parser.getValue((Element)child, KEY_THUMB_URL));
// adding HashList to ArrayList
//songsList.add(map);
}
}
}
}
}
Solved :
Changed this :
Element e = (Element) n1.item(0);
NodeList nodeList2 = doc.getElementsByTagName("edition");
to this :
Element e = (Element) n1.item(0);
NodeList nodeList2 = e.getElementsByTagName("edition");
I'd rather suggest you to build your own parser using the pattern matching approach. Coz it gives you the power to customize things according to your need.
Gson like parser will be a good fit.

use placeholder image from drawable if the image url is null or empty

I'm trying to do user an image from drawable folder as placeholder if the image url not found. But I'm getting dead code error when I tried to implement it. And the available image urls loads the images from JSON.
This is my code:
String image_file = new String( Environment.getExternalStorageDirectory()
+ "/images/" + shop.getImage());
String place_holder = "#drawable/placeholder";
if(shop.getId().equals(sales.getShop_id())){
if(image_file != null){
hm.put("shop_image", image_file );
}else{
//here I gets dead code error
hm.put("shop_image", place_holder );
}
}
Please someone help me to solve?
Edit:
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.getCategories1().contains("cat_id1")){
hm.put("sale_id", sales.getId());
hm.put("sale_title", "" + sales.getShort_title());
hm.put("shop_name","Shop : " + sales.getShop_name());
for(Shop shop : this.response.shops){
String image_file = new String( Environment.getExternalStorageDirectory()
+ "/images/" + shop.getImage());
//String place_holder = new String("#drawable/placeholder");
if(shop.getId().equals(sales.getShop_id())){
if(new File(image_file).exists()){
hm.put("shop_image", image_file );
}else{
hm.put("shop_image", String.valueOf(R.drawable.placeholder) );
}
}
}
aList.add(hm);
}
}
// Keys used in Hashmap
String[] from = { "sale_id","shop_image","sale_title","shop_name"};
// Ids of views in listview_layout
int[] to = { R.id.sale_id,R.id.shop_image,R.id.sale_title,R.id.shop_name};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView myList = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
myList.setAdapter(adapter);
In this line
if(image_file != null)
//The string 'image_file' will never be null according to the lines above.
I think you are trying to judge if the image file exists. Try this instead:
if (new File(image_file).exists())

How to get a part of a datastring from clicking a listview-item

I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).

ListView with custom backgroundResource

i need to set a listview with custom text and custom setbackgroundresource when i create the listview
This is my code:
The listView receive the data from URL by JSON encdoe like that:
{"results":[
{"db_id":"6","discount":"active","db_description":"bla bla bla ","db_num":"137","db_num2":"260"},
{"db_id":"14","db_type":"discount","db_description":"blaaaaaaa","db_num":"39","db_num2":"46"},
{"db_id":"18","db_type":"discount","db_description":"blaaaaaaa","db_num":"335","db_num2":"456"},
]}
Adding the data to map
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type",RESULTS_PARAMS));
JSONObject json = jsonParser.makeHttpRequest(RESULTS_URL, "GET",
params);
Log.d("JSON RESULT: ", json.toString());
try {
queues = json.getJSONArray(TAG_RESULTS);
for (int i = 0; i < queues.length(); i++) {
JSONObject c = queues.getJSONObject(i);
String id = c.getString(TAG_ID);
String type = c.getString(TAG_TYPE);
String description = c.getString(TAG_DESCRIPTION);
String num = c.getString(TAG_NUM);
String num2 = c.getString(TAG_NUM2);
int imageint = getResources().getIdentifier(c.getString(TAG_TYPE) , "drawable", getPackageName());
String image = String.valueOf(imageint);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_TYPE, type);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_NUM, num);
map.put(TAG_NUM2, num2);
map.put(TAG_IMAGE, image);
QueueList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
the code the set the DATA into the listview
ListAdapter adapter = new SimpleAdapter(
QueueActivity.this,
QueueList,
R.layout.queue_row,
new String[] { TAG_ID, TAG_DESCRIPTION, TAG_NUM, TAG_NUM2, TAG_IMAGE},
new int[] { R.id.queueid, R.id.description, R.id.num, R.id.num2, R.id.list_image });
setListAdapter(adapter);
now i want to set a setBackgroundResource to R.drawable.customlistviewback
if the db_id (TAG_ID) = int info
For ex, int info = 6;
To do row-level view modifications you will probably need to use a custom Adapter. Typically you override the getView function and make your changes there. See how to customize listview row android for a decent example.

Android: Setting Icon in a list View

Currently, I have json data of several twitter feeds that I parse to fill my list. I have an object, "image" that contains the url of the users icon that I want to set as the ImageView to in the list. I am having trouble trying to figure out how I can take the url and load the image in the Imageview for each row. Here is the code:
public void getTweets(String selection) {
String formatedcat = selection.toLowerCase();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://example.com/tweet.php");
try {
JSONArray category = json.getJSONArray(formatedcat);
for (int i = 0; i < category.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = category.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name",
c.getString("fullName") + "\n(#" + c.getString("name")
+ ") ");
map.put("text",
c.getString("text") + "\n - "
+ c.getString("timestamp"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.list,
new String[] { "name", "text"}, new int[] { R.id.item_title,
R.id.item_subtitle});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
How to display image from URL on Android
See this question. Look very practical to me. Do that showing of the image in the getView() method where you populate the list and instantiate the child views.

Categories

Resources