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.
Related
I have this code that will eventually be populated from a database but to get it working first I have used the below code
ListView mListView = (ListView) getActivity().findViewById(R.id.listView);
ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>( );
HashMap<String, Object> listItem;
listItem = new HashMap<String, Object>();
for (int i = 0;i<=10;i++) {
listItem.put("item", "orderTitles" + i);
listItem.put("subitem", "orderDescriptions" + i);
items.add(listItem);
}
SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.list_item_format, new String[]{"item", "subitem"}, new int[]{R.id.itemTitle, R.id.itemDescription});
mListView.setAdapter(adapter);
The problem is that the output to the list is saying only OrderTitles10 and OrderDescriptions10 (listed 10 times) instead of counting incrementally. What am I doing wrong
change your code to this:
ListView mListView = (ListView) getActivity().findViewById(R.id.listView);
ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>( );
HashMap<String, Object> listItem;
for (int i = 0;i<=10;i++) {
listItem = new HashMap<String, Object>();
listItem.put("item", "orderTitles" + i);
listItem.put("subitem", "orderDescriptions" + i);
items.add(listItem);
}
SimpleAdapter adapter = new SimpleAdapter(getActivity(), items, R.layout.list_item_format, new String[]{"item", "subitem"}, new int[]{R.id.itemTitle, R.id.itemDescription});
mListView.setAdapter(adapter);
Initialize listItem inside for loop to create and add new HashMap with both values in ArrayList :
for (int i = 0;i<=10;i++) {
listItem = new HashMap<String, Object>();
listItem.put("item", "orderTitles" + i);
listItem.put("subitem", "orderDescriptions" + i);
items.add(listItem);
}
initialize listitem inside the loop and change the for loop condition like below
for (int i = 0;i<10;i++) {
listItem = new HashMap<String, Object>();
listItem.put("item", "orderTitles" + i);
listItem.put("subitem", "orderDescriptions" + i);
items.add(listItem);
}
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 :)
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).
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.
I have an arraylist with multiple hashmaps that contains information that comes from a sql database
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
This arraylist will eventually fill my listview with items (names of people).
When I click on one item I want to send all of the content of that hashmap to another page.
For example:
John <
Now I want to send the hashmap with all the information of John to another android page.
How do I get that information out of the hashmap?
This is my code:
public class Contactenlijst extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactview);
ListView lv;
lv = (ListView) findViewById(R.id.list);
lv.setTextFilterEnabled(true);
String[] from = new String[] {"naam"};
int[] to = new int[]{R.id.naam};
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// Get the data (see above)
JSONObject json = Database
.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try {
JSONArray contactinfo = json.getJSONArray("contactlijst");
// Loop the Array
for (int i = 0; i < contactinfo.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
//array for view
ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < mylist.size(); i++){
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("naam", (mylist.get(i).get("voornaam")+" "+(mylist.get(i).get("achternaam"))));
mylist2.add(map2);
}
try{
lv.setAdapter(new SimpleAdapter(this, mylist2, R.layout.list_item, from, to));
}catch (Exception e){Log.d("test1","test2");}
//onclick stuur array naar contactinfo
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String text = ((TextView) view).getText().toString();
Intent i = new Intent(Contactenlijst.this, Contactinfo.class);
String uittekst[] = text.split(" ");
String voornaam = uittekst[0].toString();
String achternaam = uittekst[1].toString();
startActivity(i);
}
});
}
}
So it all has to happen under "String achternaam = uittekst[1].toString();"
for(Hashmap<String, String> map: mylist) {
for(Entry<String, String> mapEntry: map) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
}
}