Listview only filling with first item - android
I have a Listview that gets its contents from an async task, but only the first item is actually getting placed into the Listview.
My xml for the activity is:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:orientation="vertical"
android:background="#drawable/bg_card">
<!-- Card Contents go here -->
<TextView
android:id="#+id/portfolioTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="20sp"
android:textStyle = "bold"
android:text="Your Portfolio"
android:padding="5dip"
>
</TextView>
</LinearLayout >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:orientation="vertical"
android:background="#drawable/bg_card">
<!-- Card Contents go here -->
<TextView
android:id="#+id/sortTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="15sp"
android:textStyle = "bold"
android:text="Sorting Options:"
android:padding="5dip"
>
</TextView>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
>
<Spinner
android:id="#+id/portfolioSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/portfolio_array"
/>
</LinearLayout>
</LinearLayout >
</FrameLayout>
<ListView
android:id="#+id/allYourBeersList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="0px"
android:divider="#null"
>
</ListView>
</LinearLayout>
</ScrollView>
The async task is:
public class PortfolioGetAllBeers extends AsyncTask
<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllBeers (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting beers");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("beer");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
String breweryID = jsonArray.getJSONObject(i).getString("breweryID");
int count = i + 1;
beer = count + ". " + beer;
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID , breweryID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//get beer details from id
Intent myIntent = new Intent(c, BeerPage2.class);
myIntent.putExtra("id", tempID);
myIntent.putExtra("breweryID", tempBrewID);
c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
Why I am confused is because my json is coming back with more then one result:
[{"beer":"#9","rate":"3","id":"hB0QeO","breweryID":"qIqpZc"},{"beer":"120 Minute IPA","rate":"5","id":"EWlB8A","breweryID":"g0jHqt"},{"beer":"2011 Pere Jacques","rate":"4","id":"7EhKvb","breweryID":"APW1BC"},{"beer":"2xIPA","rate":"3","id":"kZsjqY","breweryID":"x8kqVp"},{"beer":"312 Urban Wheat Ale","rate":"3","id":"EaoR0H","breweryID":"APW1BC"},{"beer":"471 Double IPA Small Batch","rate":"4","id":"j9cp5e","breweryID":"IImUD9"},{"beer":"5 Golden Rings","rate":"2","id":"tRFIN3","breweryID":"4MVtcc"},{"beer":"60 Minute IPA","rate":"3","id":"TACnR2","breweryID":"g0jHqt"},{"beer":"75 Minute IPA","rate":"5","id":"ovCoQh","breweryID":"g0jHqt"},{"beer":"90 Minute IPA","rate":"5","id":"qqTzHb","breweryID":"g0jHqt"},{"beer":"\u00a7ucaba (Abacus)","rate":"5","id":"GWY6vH","breweryID":"qghrkC"},{"beer":"Admiral IPA","rate":"3","id":"nHYjdl","breweryID":"OYQA8m"},{"beer":"Agave Wheat","rate":"3","id":"6AcqY6","breweryID":"IImUD9"},{"beer":"Alimony Ale","rate":"0","id":"G7kmvt","breweryID":"P1I1gt"},{"beer":"Allagash Black","rate":"4","id":"z77hjQ","breweryID":"pdLPeS"},{"beer":"Allagash Dubbel","rate":"3","id":"KzHweV","breweryID":"pdLPeS"},{"beer":"Allagash Fluxus 2013","rate":"3","id":"SlMu4Q","breweryID":"pdLPeS"},{"beer":"Allagash Four","rate":"4","id":"0mttNd","breweryID":"pdLPeS"},{"beer":"Allagash Victoria Ale","rate":"4","id":"JLBMnT","breweryID":"pdLPeS"},{"beer":"Allagash White","rate":"4","id":"Q8hjek","breweryID":"pdLPeS"},{"beer":"American Amber Ale","rate":"3","id":"3SvZ4H","breweryID":"X0l98q"},{"beer":"American Pilsner","rate":"3","id":"67Hcxk","breweryID":"xcKkLh"},{"beer":"Anchor Steam","rate":"3","id":"Uiol9p","breweryID":"6PBXvz"},{"beer":"Angels Share","rate":"5","id":"ikoDPe","breweryID":"9x7wNn"},{"beer":"Aprihop","rate":"4","id":"qV0bBx","breweryID":"g0jHqt"},{"beer":"Arrogant Bastard Ale","rate":"3","id":"qlwwem","breweryID":"709vEK"},{"beer":"Aventinus Weizen-Eisbock","rate":"4","id":"avMkil","breweryID":"FQLVgV"},{"beer":"B.O.R.I.S. The Crusher Oatmeal-Imperial Stout","rate":"5","id":"Tzy7eJ","breweryID":"w5OOQ5"},{"beer":"Back in Black","rate":"3","id":"UD5Sm4","breweryID":"EdRcIs"},{"beer":"Balt Altbier","rate":"3","id":"dR7EQg","breweryID":"t6Gyij"},{"beer":"Baltic Thunder","rate":"3","id":"DCwAKJ","breweryID":"VoKbnS"},{"beer":"Bass Pale Ale","rate":"3","id":"r5GwCX","breweryID":"X2Qkw1"},{"beer":"Belgian Abbey Dubbel","rate":"3","id":"YkoqCD","breweryID":"M5zcKb"},{"beer":"Big DIPA","rate":"4","id":"aP9faI","breweryID":"wTFQaf"},{"beer":"Black & Blue","rate":"3","id":"tL3vdf","breweryID":"g0jHqt"},{"beer":"Black Cannon","rate":"3","id":"f9WbNU","breweryID":"wTFQaf"},{"beer":"Blackwing Lager","rate":"3","id":"ISXK3w","breweryID":"t6Gyij"},{"beer":"Blue Moon Belgian White","rate":"3","id":"dDXOEp","breweryID":"avMkil"},{"beer":"Br\u00e4u Weisse","rate":"4","id":"L6f8QM","breweryID":"QKdFk2"},{"beer":"Brawler","rate":"2","id":"czwGMM","breweryID":"jwWiTH"},{"beer":"Breakfast Stout","rate":"4","id":"9na4NR","breweryID":"Idm5Y5"},{"beer":"Bronx Pale Ale","rate":"4","id":"yDHpxQ","breweryID":"V0wvf7"},{"beer":"Bud Light","rate":"2","id":"dimtrs","breweryID":"BznahA"},{"beer":"Burton Baton","rate":"4","id":"em9Lxc","breweryID":"g0jHqt"},{"beer":"Caldera IPA","rate":"3","id":"kMlOin","breweryID":"iL3Juq"},{"beer":"Centennial IPA","rate":"3","id":"rAHla4","breweryID":"Idm5Y5"},{"beer":"Cerveza Sol","rate":"2","id":"4ap3mq","breweryID":"UWBCmm"},{"beer":"Chateau Jiahu","rate":"4","id":"bFOmYH","breweryID":"g0jHqt"},{"beer":"Chocolate Stout","rate":"4","id":"93XbpS","breweryID":"X0l98q"},{"beer":"Circus Boy","rate":"3","id":"JQCCB0","breweryID":"qIqpZc"},{"beer":"Corona Extra","rate":"3","id":"ujPz4L","breweryID":"wadu38"},{"beer":"Corona Light","rate":"3","id":"u7U2Ga","breweryID":"wadu38"},{"beer":"Cr\u00e8me Br\u00fbl\u00e9e Imperial Milk Stout","rate":"4","id":"Kax7jD","breweryID":"x8kqVp"},{"beer":"Cricket Hill Hopnotic","rate":"1","id":"FCGb3K","breweryID":"U0vh9j"},{"beer":"Curieux","rate":"4","id":"T6rZqg","breweryID":"pdLPeS"},{"beer":"Cutlass","rate":"3","id":"1KVlP0","breweryID":"wTFQaf"},{"beer":"Dales Pale Ale","rate":"4","id":"iT9pf4","breweryID":"q6vJUK"},{"beer":"Delirium Tremens","rate":"3","id":"siPwY9","breweryID":"8eyXN7"},{"beer":"Dogtoberfest","rate":"3","id":"IgdWNj","breweryID":"jmGoBA"},{"beer":"Don De Dieu","rate":"3","id":"i6yPHf","breweryID":"llbEuB"},{"beer":"Dos Equis Amber Lager","rate":"2","id":"s5lxSd","breweryID":"UWBCmm"},{"beer":"Double Dog Double Pale Ale","rate":"3","id":"r9nypM","breweryID":"jmGoBA"},{"beer":"Double Jack Imperial IPA","rate":"5","id":"sUL1uy","breweryID":"qghrkC"},{"beer":"Double Stout","rate":"3","id":"uVJmkY","breweryID":"c67gGy"},{"beer":"Double Wide I.P.A.","rate":"4","id":"LKzaHC","breweryID":"VDMEV7"},{"beer":"DreamWeaver Wheat Ale","rate":"3","id":"0aUaXd","breweryID":"n5QFi2"},{"beer":"Drifter Pale Ale","rate":"3","id":"HfAvcD","breweryID":"8wcv7h"},{"beer":"Duck-Rabbit Milk Stout","rate":"4","id":"C6EUeD","breweryID":"rBxNNF"},{"beer":"Duckpin Pale Ale","rate":"3","id":"17OQHF","breweryID":"t6Gyij"},{"beer":"Etrusca","rate":"4","id":"ffEc4d","breweryID":"g0jHqt"},{"beer":"Euforia Toffee Nut","rate":"4","id":"o4ENUL","breweryID":"TVgBWg"},{"beer":"Fat Tire","rate":"2","id":"tuqTtX","breweryID":"Jt43j7"},{"beer":"Festina Peche","rate":"3","id":"Gf9h6p","breweryID":"g0jHqt"},{"beer":"Finestkind IPA","rate":"3","id":"3RFxH6","breweryID":"v0MKXA"},{"beer":"Franziskaner Hefe-Weissbier Hell \/ Franziskaner C","rate":"3","id":"ZhGbaC","breweryID":"o5vGy8"},{"beer":"Furious","rate":"4","id":"qRuupG","breweryID":"cPRfoj"},{"beer":"FV13","rate":"4","id":"xv9fS8","breweryID":"pdLPeS"},{"beer":"Gemini","rate":"3","id":"L8oWyF","breweryID":"7VPQrN"},{"beer":"GKnight","rate":"3","id":"69R1Vd","breweryID":"q6vJUK"},{"beer":"Gold Ale","rate":"3","id":"bIk08d","breweryID":"wTFQaf"},{"beer":"Golden Monkey","rate":"4","id":"UfxKKB","breweryID":"VoKbnS"},{"beer":"Gonzo Imperial Porter","rate":"3","id":"kkcQtN","breweryID":"jmGoBA"},{"beer":"Guinness Draught","rate":"3","id":"StkEiv","breweryID":"HaPdSL"},{"beer":"Hardcore IPA","rate":"3","id":"7RaQWJ","breweryID":"wfAwfx"},{"beer":"Harvest","rate":"3","id":"9Pj2Cr","breweryID":"x8kqVp"},{"beer":"Harvest Moon Pumpkin Ale","rate":"3","id":"Oa5lvx","breweryID":"avMkil"},{"beer":"Heart of Darkness","rate":"3","id":"KvSwJR","breweryID":"qIqpZc"},{"beer":"Hefeweizen","rate":"3","id":"7Xn4wJ","breweryID":"P2xdU4"},{"beer":"Heifer-in-Wheat","rate":"3","id":"4MyOgi","breweryID":"REDaIN"},{"beer":"Heineken","rate":"3","id":"eGtqKZ","breweryID":"robMSl"},{"beer":"Heinnieweisse Weissebeir","rate":"3","id":"RhmCRd","breweryID":"9BPs2d"},{"beer":"Hell or High Watermelon","rate":"4","id":"VNqOKH","breweryID":"EdRcIs"},{"beer":"Helles Lager","rate":"3","id":"MSdXm6","breweryID":"D3A2mu"},{"beer":"Hellhound On My Ale","rate":"4","id":"ALDE5Q","breweryID":"g0jHqt"},{"beer":"Hellrazer","rate":"3","id":"yJ1zJK","breweryID":"TVgBWg"},{"beer":"Hennepin Saison Ale","rate":"4","id":"RsXBB4","breweryID":"tCxPtR"},{"beer":"Hercules Double IPA","rate":"4","id":"xHovlT","breweryID":"I8WZv2"},{"beer":"Honey Weiss","rate":"3","id":"YgHnZO","breweryID":"ZDghkK"},{"beer":"Honker's Ale","rate":"3","id":"TEG3J9","breweryID":"APW1BC"},{"beer":"Hop Heathen Imperial Black Ale","rate":"3","id":"bMXin5","breweryID":"w5OOQ5"},{"beer":"Hop Stoopid","rate":"3","id":"Pni8Jo","breweryID":"nLsoQ9"},{"beer":"Hop Wallop","rate":"3","id":"b58sGA","breweryID":"VoKbnS"},{"beer":"HopDevil","rate":"3","id":"IzTjAm","breweryID":"VoKbnS"},{"beer":"Hopfen-Weisse","rate":"5","id":"wXHOmA","breweryID":"FQLVgV"},{"beer":"Hops Infusion","rate":"3","id":"6nkcOK","breweryID":"a57dkm"},{"beer":"Hopsecutioner","rate":"4","id":"Rfe5aM","breweryID":"DPLTAJ"},{"beer":"Hoptober","rate":"3","id":"n1bFMy","breweryID":"Jt43j7"},{"beer":"Horseshoe Bend Pale Ale","rate":"3","id":"Uvuoay","breweryID":"xcKkLh"},{"beer":"Illinois","rate":"3","id":"PZbw01","breweryID":"APW1BC"},{"beer":"Imperial IPA","rate":"3","id":"WT6hkF","breweryID":"TR98tr"},{"beer":"Imperial Pumpkin Ale","rate":"4","id":"LRCEhC","breweryID":"a57dkm"},{"beer":"Imperial Russian Stout","rate":"0","id":"pD5RiK","breweryID":"709vEK"},{"beer":"Imperial Stout","rate":"4","id":"IqPdv8","breweryID":"Idm5Y5"},{"beer":"India Pale Ale","rate":"3","id":"fu2qgB","breweryID":"APW1BC"},{"beer":"Indian Brown Ale","rate":"3","id":"AZI8ib","breweryID":"g0jHqt"},{"beer":"International Arms Race","rate":"2","id":"aX0e6r","breweryID":"jmGoBA"},{"beer":"IPA","rate":"3","id":"iLlMCb","breweryID":"nLsoQ9"},{"beer":"Italian Strong Ale","rate":"5","id":"9S5ObB","breweryID":"wAdTKf"},{"beer":"Judgement Day","rate":"3","id":"Gwo4rP","breweryID":"9x7wNn"},{"beer":"Just the Tip","rate":"3","id":"ekhzhU","breweryID":"rKXfsB"},{"beer":"Kellerweis","rate":"3","id":"JVv3qI","breweryID":"nHLlnK"},{"beer":"Killian's Irish Red","rate":"3","id":"FXGCOG","breweryID":"avMkil"},{"beer":"La Torpille","rate":"3","id":"gghCq9","breweryID":"6DG1qh"},{"beer":"Lancaster Milk Stout","rate":"3","id":"aZtMd7","breweryID":"VGDfKl"},{"beer":"Little Sumpin' Sumpin'","rate":"4","id":"svXHfu","breweryID":"nLsoQ9"},{"beer":"Local 2","rate":"3","id":"vpdrzj","breweryID":"4OBVPn"},{"beer":"Loose Cannon","rate":"3","id":"Bt79WS","breweryID":"wTFQaf"},{"beer":"Lucky 13","rate":"3","id":"CWwxeR","breweryID":"nLsoQ9"},{"beer":"Lucky 7 Porter","rate":"3","id":"a6XiKI","breweryID":"Ysh6PO"},{"beer":"M\u00e4rzen","rate":"4","id":"zomWCT","breweryID":"P2xdU4"},{"beer":"M\u00fcnchner Sommer","rate":"5","id":"TbP3By","breweryID":"4rlPFf"},{"beer":"Mad Elf Ale","rate":"4","id":"ZRzruY","breweryID":"n5QFi2"},{"beer":"Mad King\u2019s Weiss","rate":"3","id":"5JQA4h","breweryID":"VoKbnS"},{"beer":"Mana Wheat","rate":"3","id":"fem70X","breweryID":"fwCFE4"},{"beer":"Matilda","rate":"5","id":"uKquc0","breweryID":"APW1BC"},{"beer":"Maui Coconut Porter","rate":"3","id":"sNQLDD","breweryID":"fwCFE4"},{"beer":"Merry Monks","rate":"3","id":"gz4uZ6","breweryID":"a57dkm"},{"beer":"Midas Touch","rate":"5","id":"YFZKZA","breweryID":"g0jHqt"},{"beer":"Midshipman Mild","rate":"3","id":"eEjA64","breweryID":"OYQA8m"},{"beer":"Mild Winter","rate":"3","id":"hrhfc1","breweryID":"APW1BC"},{"beer":"Milk Stout Nitro","rate":"3","id":"gtaIQr","breweryID":"Ro08YF"},{"beer":"Miller Lite","rate":"1","id":"KJIjyd","breweryID":"MWi5Kp"},{"beer":"Mischief","rate":"3","id":"5A7pI0","breweryID":"4MVtcc"},{"beer":"Misery Bay IPA","rate":"2","id":"uSxQME","breweryID":"LHQ79n"},{"beer":"Mongo Double IPA","rate":"4","id":"9tIw2j","breweryID":"ayEBYP"},{"beer":"Monumental IPA","rate":"3","id":"kckAgC","breweryID":"9FwufS"},{"beer":"Moo Thunder Stout","rate":"3","id":"D4Ka8l","breweryID":"9BPs2d"},{"beer":"Moonglow Weizenbock","rate":"4","id":"DOrgPb","breweryID":"VoKbnS"},{"beer":"My Antonia","rate":"3","id":"OyeqOI","breweryID":"g0jHqt"},{"beer":"Namaste","rate":"3","id":"1INeXj","breweryID":"g0jHqt"},{"beer":"Narragansett Lager","rate":"2","id":"lBKttb","breweryID":"mGqkXE"},{"beer":"National Bohemian","rate":"2","id":"ssQJcb","breweryID":"AKyyYN"},{"beer":"Newcastle Werewolf","rate":"2","id":"xzED0r","breweryID":"Qutakc"},{"beer":"Noble Rot","rate":"4","id":"tEpzX3","breweryID":"g0jHqt"},{"beer":"Nommo Dubbel","rate":"3","id":"WzJmsi","breweryID":"VDMEV7"},{"beer":"Nugget Nectar","rate":"3","id":"x8H3l7","breweryID":"n5QFi2"},{"beer":"Oak Barrel Stout","rate":"3","id":"JdJXIl","breweryID":"xG9JyI"},{"beer":"Oat Imperial Oatmeal Stout","rate":"4","id":"1UmxNj","breweryID":"x8kqVp"},{"beer":"Old Chub","rate":"3","id":"KmsdoV","breweryID":"q6vJUK"},{"beer":"Old Guardian Oak-Smoked","rate":"4","id":"Pwkvsq","breweryID":"709vEK"},{"beer":"Old Man Winter","rate":"3","id":"X60E3Q","breweryID":"x8kqVp"},{"beer":"Old Pro","rate":"4","id":"SS2uWf","breweryID":"t6Gyij"},{"beer":"Old Rasputin","rate":"4","id":"CfJ0cK","breweryID":"yLBNrD"},{"beer":"Old Ruffian","rate":"3","id":"AqEUBQ","breweryID":"I8WZv2"},{"beer":"Old Scratch Amber Lager","rate":"4","id":"N4LF2o","breweryID":"jmGoBA"},{"beer":"Olde School Barleywine","rate":"5","id":"YDBgUE","breweryID":"g0jHqt"},{"beer":"Ommegang Abbey Ale","rate":"4","id":"jYBtXz","breweryID":"tCxPtR"},{"beer":"Ommegang BPA","rate":"3","id":"N101SS","breweryID":"tCxPtR"},{"beer":"Otis","rate":"2","id":"uTPvQK","breweryID":"7VPQrN"},{"beer":"Ozzy","rate":"4","id":"3te24V","breweryID":"YytkpO"},{"beer":"Pabst Blue Ribbon","rate":"2","id":"pDKyvz","breweryID":"AKyyYN"},{"beer":"Pale Ale","rate":"3","id":"cdkpyx","breweryID":"nHLlnK"},{"beer":"Palo Santo Marron","rate":"5","id":"7LrYr1","breweryID":"g0jHqt"},{"beer":"Pangaea","rate":"4","id":"Oq4XtM","breweryID":"g0jHqt"},{"beer":"Pearl Jam Twenty Faithful Ale","rate":"3","id":"6IjMIK","breweryID":"g0jHqt"},{"beer":"Peeper","rate":"3","id":"KdKlo9","breweryID":"xgrmyW"},{"beer":"Phin ","rate":"3","id":"cWMMWU","breweryID":"x8kqVp"},{"beer":"Porter","rate":"3","id":"bZub8V","breweryID":"9FwufS"},{"beer":"Porter Pounder","rate":"3","id":"h5zbGr","breweryID":"pqSkmD"},{"beer":"Positive Contact","rate":"3","id":"eAvRRc","breweryID":"g0jHqt"},{"beer":"Powder Monkey","rate":"2","id":"PbHXnC","breweryID":"OYQA8m"},{"beer":"Pumkin Ale","rate":"4","id":"zpyLEw","breweryID":"tNDKBY"},{"beer":"Pumking","rate":"4","id":"iHEJZm","breweryID":"x8kqVp"},{"beer":"Pumpkin Ale","rate":"3","id":"yu0Mbf","breweryID":"v0MKXA"},{"beer":"Pumpkinhead Ale","rate":"3","id":"TlBAjN","breweryID":"5N0usi"},{"beer":"Punkin Ale","rate":"4","id":"hGjIJg","breweryID":"g0jHqt"},{"beer":"Racer 5 IPA","rate":"3","id":"o1OELJ","breweryID":"5tw2Iw"},{"beer":"Raging Bitch Belgian IPA","rate":"4","id":"P203ye","breweryID":"jmGoBA"},{"beer":"Raison DEtre","rate":"3","id":"Q4Ah1v","breweryID":"g0jHqt"},{"beer":"Ranger","rate":"3","id":"iaYJ7X","breweryID":"Jt43j7"},{"beer":"Rare Vos","rate":"3","id":"OMyQoC","breweryID":"tCxPtR"},{"beer":"Rayon Vert","rate":"4","id":"vMm0Rc","breweryID":"Nj8cgD"},{"beer":"Red Sky at Night","rate":"3","id":"QWYlpK","breweryID":"wTFQaf"},{"beer":"Reds Rye PA","rate":"3","id":"FOC78c","breweryID":"Idm5Y5"},{"beer":"Robust Porter","rate":"4","id":"fkylQX","breweryID":"v0MKXA"},{"beer":"Ruination IPA","rate":"4","id":"7cnuJq","breweryID":"709vEK"},{"beer":"Sah'tea","rate":"4","id":"dc6ShA","breweryID":"g0jHqt"},{"beer":"Saison du BUFF","rate":"3","id":"CTbk45","breweryID":"g0jHqt"},{"beer":"Saison Rue","rate":"4","id":"V0T8uP","breweryID":"4MVtcc"},{"beer":"Samuel Adams Boston Lager","rate":"3","id":"z4k3eU","breweryID":"1wSztN"},{"beer":"Samuel Adams Octoberfest","rate":"3","id":"Hyyhug","breweryID":"1wSztN"},{"beer":"Samuel Adams Summer Ale","rate":"3","id":"DiBfxM","breweryID":"1wSztN"},{"beer":"Samuel Adams Winter Lager","rate":"2","id":"4fM6Pf","breweryID":"1wSztN"},{"beer":"Sapporo Premium Beer","rate":"2","id":"TOHi4D","breweryID":"D61TcY"},{"beer":"Schwartz Bier","rate":"3","id":"y4THvR","breweryID":"iw1hDB"},{"beer":"Shock Top","rate":"2","id":"v7H1Ev","breweryID":"BznahA"},{"beer":"Sixty-One","rate":"4","id":"L1eJ2p","breweryID":"g0jHqt"},{"beer":"Small Craft Warning","rate":"3","id":"2qHZyl","breweryID":"wTFQaf"},{"beer":"Smoking Wood","rate":"5","id":"8NX7Sy","breweryID":"4MVtcc"},{"beer":"Snake Dog","rate":"3","id":"Blig3z","breweryID":"jmGoBA"},{"beer":"Snow Pants","rate":"4","id":"g8oVuV","breweryID":"t6Gyij"},{"beer":"Sofie","rate":"4","id":"KBQTlS","breweryID":"APW1BC"},{"beer":"Son of a Peach","rate":"4","id":"94Fe7D","breweryID":"bWL816"},{"beer":"Squall IPA","rate":"4","id":"LZmXC8","breweryID":"g0jHqt"},{"beer":"Stella Artois","rate":"3","id":"Jc7iGI","breweryID":"mIWMKP"},{"beer":"Stone IPA","rate":"3","id":"PAM6wX","breweryID":"709vEK"},{"beer":"Stone Levitation Ale","rate":"4","id":"OaZYgf","breweryID":"709vEK"},{"beer":"Storm King Imperial Stout","rate":"4","id":"4M26ru","breweryID":"VoKbnS"},{"beer":"Sublimely Self-Righteous Ale","rate":"4","id":"SAtbDP","breweryID":"709vEK"},{"beer":"Summer Love Ale","rate":"3","id":"SzhLvG","breweryID":"VoKbnS"},{"beer":"Summer Shandy","rate":"2","id":"nJjPsG","breweryID":"ZDghkK"},{"beer":"Summertime","rate":"3","id":"tXTETf","breweryID":"APW1BC"},{"beer":"Sunset Amber Ale","rate":"4","id":"scC0RX","breweryID":"xcKkLh"},{"beer":"Sweet Baby Jesus!","rate":"4","id":"opSf4n","breweryID":"TVgBWg"},{"beer":"Sweet Child of Vine","rate":"3","id":"xrLwng","breweryID":"5GoGSi"},{"beer":"ta henket","rate":"4","id":"icSARl","breweryID":"g0jHqt"},{"beer":"Tank 7 Farmhouse Ale","rate":"3","id":"lDiXyX","breweryID":"VDMEV7"},{"beer":"Ten Fidy","rate":"5","id":"x6bRxw","breweryID":"q6vJUK"},{"beer":"The Cask","rate":"3","id":"NgxwRi","breweryID":"dwroV3"},{"beer":"The Fear","rate":"2","id":"0ZX12D","breweryID":"jmGoBA"},{"beer":"The Libertine","rate":"4","id":"irF7Mh","breweryID":"5GoGSi"},{"beer":"The Sixth Glass","rate":"4","id":"zrAAHP","breweryID":"VDMEV7"},{"beer":"The Truth","rate":"3","id":"o9TSOv","breweryID":"jmGoBA"},{"beer":"The Vermonster","rate":"2","id":"UJI7C4","breweryID":"LpX3cU"},{"beer":"Theobroma","rate":"0","id":"H1L7UE","breweryID":"g0jHqt"},{"beer":"Third Shift","rate":"3","id":"g284jn","breweryID":"avMkil"},{"beer":"Thomas Jefferson's Tavern Ale","rate":"3","id":"xDzvQP","breweryID":"jwWiTH"},{"beer":"Three Philosophers","rate":"4","id":"TOzkLy","breweryID":"tCxPtR"},{"beer":"Torpedo Extra IPA","rate":"3","id":"JaS6T7","breweryID":"nHLlnK"},{"beer":"Trade Winds Tripel","rate":"4","id":"jdulDH","breweryID":"4MVtcc"},{"beer":"Tribute Tripel","rate":"5","id":"FdRZ7e","breweryID":"UbQHhM"},{"beer":"Troegenator Double Bock","rate":"3","id":"OGlmOC","breweryID":"n5QFi2"},{"beer":"Tweasonale","rate":"3","id":"Qx1hbt","breweryID":"g0jHqt"},{"beer":"UFO White","rate":"3","id":"cG83LQ","breweryID":"RzvedX"},{"beer":"Unfiltered Wheat Beer","rate":"3","id":"lgaPWe","breweryID":"VDMEV7"},{"beer":"Unibroue 17","rate":"4","id":"VfyYpZ","breweryID":"llbEuB"},{"beer":"Urkontinent","rate":"3","id":"XQyXhk","breweryID":"g0jHqt"},{"beer":"Vanilla Porter","rate":"3","id":"Bk34Go","breweryID":"IImUD9"},{"beer":"Vanilla Stout","rate":"4","id":"NRhCm4","breweryID":"oBe8dQ"},{"beer":"Walkers Reserve","rate":"3","id":"JgdTCV","breweryID":"qghrkC"},{"beer":"Wells Banana Bread Beer","rate":"4","id":"hQzCbn","breweryID":"6oEP92"},{"beer":"West Coast IPA","rate":"4","id":"RC4BkU","breweryID":"Nj8cgD"},{"beer":"Western Rider","rate":"2","id":"ymabSa","breweryID":"bRKIdZ"},{"beer":"Winter Storm - Category 5 Ale","rate":"3","id":"fA0O8C","breweryID":"wTFQaf"},{"beer":"Wookey Jack","rate":"3","id":"f5DoHi","breweryID":"qghrkC"},{"beer":"World Wide Stout","rate":"4","id":"H5sA73","breweryID":"g0jHqt"},{"beer":"Yakima Glory Ale","rate":"3","id":"q7dLm5","breweryID":"VoKbnS"},{"beer":"Yeti Imperial Stout","rate":"5","id":"oz1oll","breweryID":"I8WZv2"},{"beer":"Yuengling Traditional Lager","rate":"3","id":"wd1Y84","breweryID":"pX8lES"}]
Adapter code:
public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo>{
Context context;
int layoutResourceId;
List<ShortBeerInfo> data = null;
public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBeer = (TextView)row.findViewById(R.id.breweryName);
holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
ShortBeerInfo beer = data.get(position);
holder.txtBeer.setText(beer.beer);
holder.txtRate.setText(beer.rate + " out of 5.00 Stars");
holder.numHolder= Float.parseFloat(beer.rate);
holder.txtBar.setNumStars(5);
holder.txtBar.setRating(holder.numHolder);
return row;
}
static class beerHolder
{
TextView txtBeer;
TextView txtRate;
RatingBar txtBar;
Float numHolder;
}
}
I think you can't see the list properly because your ListVew is within a ScrollView. ListView itself is scrollable , so it doesn't show properly in a ScrollView , you can at most see a ListView with very small height that fits one or two elements. Try using your ListView outside of ScrollView to test whether your code is correct or not. Hope it helps.
The short answer is that your doing it wrong.
You should be asynchronously loading the data into a sqlite db table and using a Loader with a cursor adapter.
Also, even using the code you have (and its hard to read from my phone here) it looks like your only adding one element to the list before you add the list adapter to the list view, which would be why you are only seeing a single item.
Another thing that may be causing you trouble is that you're asynchronously loading the data into a list view that has been created but you don't seem signal that the adapter has new data as the task finishes.
Move your code for the adapter so that it is outside and below your for loop. You are creating a new adapter for every iteration and it is probably running really slow because of it. Also you are setting your onitemclicklistener for every iteration too. It only needs to be done one time.
Do that and then see what happens. Also put a breakpoint after the for loop and see how many items are in your tasteList. If there is more than one then your adapter is most likely the problem.
If you can post your code for your adapter.
I guess my answer is that you probably aren't returning back more than one item. Since the adapter is posting data to the list it should be ok. Once you can debug the app and see how many items are returning then we can know for sure.
Related
ImageView not updated in ItemList
I am trying to update the image inside ItemList, I am using the below method This is how I am getting ImageView 'imgView' Object using the below methods - 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(JSONParsingMainActivity.this, contactList, R.layout.list_item, new String[]{"name", "email", "mobile"}, new int[]{R.id.name, R.id.email, R.id.mobile}); lv.setAdapter(adapter); if(markedQuestion != null){ try { JSONObject jsonObj = new JSONObject(markedQuestion); JSONArray contacts = jsonObj.getJSONArray("data"); for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String questionid = c.getString("questionid"); System.out.println("Question No :" + i + "Question Id is :" + questionid); Long itemId = lv.getItemIdAtPosition(Integer.parseInt(questionid)); System.out.println("Item Id xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxasdasd" + itemId); changedView = (CardView) getViewByPosition(Integer.parseInt(questionid),lv); imgView = (ImageView) changedView.findViewById(R.id.imageViewstickId); imgView.setImageResource(R.drawable.cancel); } } catch (JSONException e) { e.printStackTrace(); } } lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mp.start(); position++; Intent intent = new Intent(context, DetailsActivity.class); intent.putExtra("position", Integer.toString(position)); context.startActivity(intent); } }); } public View getViewByPosition(int pos, ListView listView) { final int firstListItemPosition = listView.getFirstVisiblePosition(); final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1; if (pos < firstListItemPosition || pos > lastListItemPosition ) { return listView.getAdapter().getView(pos, null, listView); } else { final int childIndex = pos - firstListItemPosition; return listView.getChildAt(childIndex); } } This code is not updating the cancel image in the list item, when I debug I am getting correct id (i.e. 'imageViewstickId' as shown in XML), but the image is not updating, nor giving any error imgView.setImageResource(R.drawable.cancel); My XML code also - <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView android:id="#+id/cardViewQuestionId" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:card_view="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" app:cardCornerRadius="15dp" card_view:cardElevation="2dp" card_view:cardCornerRadius="5dp"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="#+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="2dp" android:paddingTop="6dp" android:text="test" android:textColor="#color/gradientStart" android:textSize="16sp" android:textStyle="bold" /> <ImageView android:id="#+id/imageViewstickId" android:layout_width="30dp" android:layout_height="30dp" android:layout_gravity="center" /> </LinearLayout> <TextView android:id="#+id/email" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#color/gradientStop" /> <TextView android:id="#+id/mobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#5d5d5d" android:textStyle="bold" /> </LinearLayout> </android.support.v7.widget.CardView> I have tried everything modifying the code, etc. but nothing works for me Any help shall be appreciated, thanks Edits - (Added Debug screen Shot) Please check in debug window, CardViewId is same as XML ImageView id... Still not updating
Solution: Instead of this: imgView.setImageResource(R.drawable.cancel); write: imgView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.cancel)); Try it. Let's hope it works.
You can simply use this: If you are in Activity then use this int id = getResources().getIdentifier("cancel","drawable", getPackageName()); Or in Fragment int id = context.getResources().getIdentifier("cancel","drawable", context.getPackageName()); // "cancel" drawable resource name // "drawable" drawable directory This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following imgView.setImageResource(id); hope this will work.
There are two best solutions for that:- 1) Instead of using this imgView.setImageResource(R.drawable.cancel); Use This Method:- imgView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.cancel)); 2)Using Glide Library https://bumptech.github.io/glide/doc/download-setup.html
Your id is correct still it is not updating then it might be a problem that your Resource file (R.java) is not updating try cleaning your project and then check. If this not works you can also try following code:- Resources resources = getResources(); imgView.setImageDrawable(resources.getDrawable(R.drawable.cancel));
May be helpful for others to think this way - I got Clue from this post - how to know when listview is finished loading data on android My data may be getting updated, but the list was not fully loaded and thats why the data is over writing. I used the following code , thanks for the actual user who posted the above answer lv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { #Override public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) { Log.d(TAG, "list got updated, do what ever u want"); if(markedQuestion != null){ try { JSONObject jsonObj = new JSONObject(markedQuestion); JSONArray contacts = jsonObj.getJSONArray("data"); for (int x = 0; x < contacts.length(); x++) { JSONObject c = contacts.getJSONObject(x); String questionid = c.getString("questionid"); System.out.println("Question No :" + x + "Question Id is :" + questionid); System.out.println(getResources()); changedView = (CardView) getViewByPosition(Integer.parseInt(questionid),lv); imgView = (ImageView) changedView.findViewById(R.id.imageViewstickId); // imgView.setImageResource(R.drawable.cancel); imgView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.cancel)); } } catch (JSONException e) { e.printStackTrace(); } } } });
Android: ListView not displaying as intended?
In the following code I intend to produce both an ouput on the item line and the subitem line but the code is just bringing me up an empty listview. How can I rectify this? The game is a multiplication times tables game with the intention that when the user enters answers (on prev activity) the answer they entered are shown in the item (i.e. 12 items) and the correct answer for each is shown in each sub-item. .Java code: public class Results extends Activity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.results); ListView itemList = (ListView) findViewById(R.id.lvresults); //gets array from prev act int[] results = getIntent().getIntArrayExtra("results"); int numberPassed = getIntent().getIntExtra("numberPassed", 0); ArrayList < HashMap <String, String> > list = new ArrayList < HashMap <String, String> > (); // loop to give list view for (int i = 1; i <= 12; ++i) { int userAnswer = results[i - 1]; int expectedAnswer = numberPassed * i; String userString = numberPassed + "x" + i + "=" + userAnswer; String expectedString = "" + expectedAnswer; HashMap <String, String> map = new HashMap <String, String> (); map.put("user", userString); map.put("expected", expectedString); list.add(map); } String[] keys = {"user", "expected"}; int[] ids = {R.id.user_answer, R.id.expected_answer}; SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, keys, ids); itemList.setAdapter(adapter); } } XML code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="#+id/lvresults" android:layout_width="wrap_content" android:layout_height="wrap_content" > </ListView> <TextView android:id="#+id/user_answer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15dp" /> <TextView android:id="#+id/expected_answer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15dp" /> </LinearLayout>
int[] ids={android.R.id.text1,android.R.id.text2} and remove the two TextView from the layout
ListView item background changes depending on scroll position
I'm running into a very strange ListView behaviour. I have a simple chat application which uses a ListView and a custom implementation of BaseAdapter to show messages. The idea I had was to shade messages from the "local" user grey and have messages from the "remote" user white, to help the user distinguish between the two. The two screenshots below show what's happening. The second is the exact same activity, xml etc etc, simply scrolled down a bit. Scrolled up: Scrolled down: Look at the message sent by "Me" # 23:05. When at the top it has no contrast to its neighbours, but when it is scrolled to the bottom, the difference is clear to see. This occurs on a nexus 4 and 7 on 4.2.2, and a GS3 running 4.1.2. Here is the XML for one of the ListView items: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/activity_view_conversation_message_list_item_wrapper" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dp" android:paddingLeft="5dp" android:paddingRight="10dp" > <ImageView android:id="#+id/activity_view_conversation_message_list_item_user_image" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:layout_marginTop="5dp" android:src="#drawable/default_user_image" /> <TextView android:id="#+id/activity_view_conversation_message_list_item_heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="1dp" android:layout_toRightOf="#+id/activity_view_conversation_message_list_item_user_image" android:text="Martyn" android:textColor="#000000" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="#+id/activity_view_conversation_message_list_item_contents" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="#+id/activity_view_conversation_message_list_item_heading" android:layout_marginLeft="10dp" android:layout_marginRight="5dp" android:layout_marginTop="2dp" android:layout_toLeftOf="#+id/activity_view_conversation_message_list_item_ack" android:layout_toRightOf="#+id/activity_view_conversation_message_list_item_user_image" android:text="Hello this is some text" android:textColor="#333333" android:textIsSelectable="true" android:textSize="18sp" /> <TextView android:id="#+id/activity_view_conversation_message_list_item_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginTop="2dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:paddingTop="2dp" android:text="12:08" android:textSize="14sp" /> <ImageView android:id="#+id/activity_view_conversation_message_list_item_ack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="#+id/activity_view_conversation_message_list_item_time" android:layout_marginRight="2dp" android:layout_marginTop="8dp" android:layout_toLeftOf="#+id/activity_view_conversation_message_list_item_time" android:src="#drawable/red_dot_8dp" /> </RelativeLayout> And here is where I set the colour of the RelativeLayout: if(localUserId.equals(remoteUserId)){ itemLayout.setBackgroundColor(Color.parseColor("#F9F9F9")); } That code runs inside the getView() method of my Adapter. I've Googled this a fair bit and turned up nothing, there are a lot of SO questions regarding the android:cacheColorHint issue but I don't think that is what is going on here. Has anyone run into this before? I'm stumped! EDIT: Here's the baseadapter code: public class MessageListAdapter extends BaseAdapter { private ArrayList<Message> messageList; Context context; /** * Constructor * #param newConversationsList An ArrayList of Conversation objects that this adapter will use * #param newContext The context of the activity that instantiated this adapter */ MessageListAdapter(ArrayList<Message> newMessageList, Context newContext){ messageList = newMessageList; //reload(); context = newContext; } public int getCount() { return messageList.size(); } public Object getItem(int position) { return messageList.get(position); } public long getItemId(int position) { return position; } /** * Adds a message to the chat list * #param message A Message object containing all the message's information */ public void add(Message message){ //nMessagesToShow++; //A new message has been added, so increase the number to show by one Log.d(TAG, "COUNT: "+getCount()); //refresh(); } public void refresh(){ this.notifyDataSetChanged(); } public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if(view!=null){ //return view; } LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Get the Message object from the list Message message = messageList.get(position); //Get the data from the message String senderId = message.getFromUser(); int messageType = message.getType(); String senderFirstName; ImageView userImage, messageImage; TextView messageHeading, messageBody; switch(messageType){ case Message.MESSAGE_TYPE_TEXT: //Standard text message //The layout we inflate for this list item will vary depending on whether this message has the same sender as the previous if(position>0 && senderId.equals(messageList.get(position-1).getFromUser())){ //True if this is not the first message AND the sender id matches that of the previous message view = vi.inflate(R.layout.activity_view_conversation_message_list_item_alternate, null); //Inflate an alternate version of the list item which has no heading or user image } else{ //This is the first message OR the sender id is different to the previous view = vi.inflate(R.layout.activity_view_conversation_message_list_item, null); //Inflate the standard version of the layout userImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_user_image); messageHeading = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_heading); //Use the sender's ID to get the sender's image and first name Contact contact = database.getContact(senderId); if(senderId.equals(localUserId)){ //True if the local user sent this message senderFirstName = "Me"; } else{ senderFirstName = contact.getFirstName(); } userImage.setImageBitmap(contact.getImageBitmap(100, 100, 6)); messageHeading.setText(senderFirstName); } messageBody = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_contents); messageBody.setText(message.getContents(null)); break; case Message.MESSAGE_TYPE_IMAGE: //Image message view = vi.inflate(R.layout.activity_view_conversation_message_list_item_image, null); //Inflate a list item template for displaying an image userImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_user_image); //Sender's first name messageHeading = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_heading); Contact contact = database.getContact(senderId); if(senderId.equals(localUserId)){ //True if the local user sent this message senderFirstName = "Me"; } else{ senderFirstName = contact.getFirstName(); } messageHeading.setText(senderFirstName); messageImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_image); String imageResourceId = null; //The message is a JSON object containing several fields, one of which is the file name which we will use to get the image try { JSONObject messageJSON = new JSONObject(message.getContents(null)); String imagePath = Environment.getExternalStorageDirectory()+"/epicChat/resources/"+messageJSON.getString("fileName"); int imageWidth = messageJSON.getInt("width"); //We want the dimensions in order to calculate the aspect ratio of the image int imageHeight = messageJSON.getInt("height"); if(messageJSON.has("resourceId")){ imageResourceId = messageJSON.getString("resourceId"); //This is used when opening the image gallery } int displayWidth = 300; int displayHeight = (int) ((float) imageHeight / (float) imageWidth * (float) displayWidth); String imagePathFull = imagePath+displayWidth+displayHeight; //For the caching Bitmap originalImage = null; //Check the bitmap cache exists. If not, reinstantiate it if(MainActivity.bitmapCache==null){ //Cache is null MainActivity.loadBitmapCache(); } else{ //Cache is not null, so check it to see if this image is in it originalImage = MainActivity.bitmapCache.get(imagePathFull); } if(originalImage==null){ //True if the bitmap was not in the cache. So we must load from disk instead new Utils.LoadBitmapAsync(imagePath, messageImage, displayWidth, displayHeight, MainActivity.bitmapCache).execute(); messageImage.getLayoutParams().height = displayHeight; } else{ messageImage.setImageBitmap(originalImage); } } catch (JSONException e) { Log.e(TAG, "Error reading image JSON: "+e.toString()); } if(imageResourceId!=null){ //Only attach the listener if we got a valid resource ID final String recourceIdFinal = imageResourceId; final String conversationIdFinal = message.getUserList(); messageImage.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { Intent showConversationImageGalleryIntent = new Intent(context, ViewConversationImageGalleryActivity.class); showConversationImageGalleryIntent.putExtra("conversationId", conversationIdFinal); showConversationImageGalleryIntent.putExtra("resourceId", recourceIdFinal); startActivityForResult(showConversationImageGalleryIntent, ACTION_SHOW_CONVERSATION_IMAGE_GALLERY); } }); } userImage.setImageBitmap(contact.getImageBitmap(100, 100, 6)); break; case Message.MESSAGE_TYPE_INVALID: default: break; } //Some layout items are present in all layouts. Typically these are the status indicator and the message time RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.activity_view_conversation_message_list_item_wrapper); //If the message is from the local user, give it a subtle grey background if(localUserId.equals(message.getFromUser())){ itemLayout.setBackgroundColor(Color.parseColor("#E9E9E9")); } else{ itemLayout.setBackgroundColor(Color.parseColor("#FFFFFF")); } TextView messageTimeText = (TextView) view.findViewById(R.id.activity_view_conversation_message_list_item_time); messageTimeText.setText(message.getFormattedTime()); ImageView messageStatusImage = (ImageView) view.findViewById(R.id.activity_view_conversation_message_list_item_ack); //Set the status image according to the status of the message switch(message.getStatus()){ case Message.MESSAGE_STATUS_PENDING: //Pending messages should have a red dot messageStatusImage.setImageResource(R.drawable.red_dot_8dp); messageStatusImage.setVisibility(View.VISIBLE); break; case Message.MESSAGE_STATUS_ACK_SERVER: //Messages that reached the server should have an orange dot messageStatusImage.setImageResource(R.drawable.orange_dot_8dp); messageStatusImage.setVisibility(View.VISIBLE); break; case Message.MESSAGE_STATUS_ACK_RECIPIENT: //Messages that reached the recipient should have an green dot messageStatusImage.setImageResource(R.drawable.green_dot_8dp); messageStatusImage.setVisibility(View.VISIBLE); break; case Message.MESSAGE_STATUS_NOT_SET: //Not set typically means the message came from another user, in which case the status image should be hidden default: //Also default here messageStatusImage.setVisibility(View.INVISIBLE); break; } return view; } }
Since there's no else statement matching your if, this is probably due to view recycling. When an item from a ListView scrolls off the screen, the operating system removes it and hands it back to the adapter in the same state it was removed. This means you need to set the background color when it's not the local user's message as well.
ArrayAdapter in Android Project [duplicate]
This question already has answers here: Closed 10 years ago. Possible Duplicate: Adapter for a custom layout of listview ArrayAdapter<String> adapter = null; JSONArray productsList = null; try { productsList = obj5.getJSONArray("Content"); } catch (JSONException e2) { e2.printStackTrace(); } if(productsList != null){ ListView lv = (ListView) findViewById(android.R.id.list); for (int i=0; i<productsList.length(); i++) { final String[] items = new String[productsList.length()]; String product = null; try { product = productsList.getJSONObject(i).getString("Quantity")+" X "+ productsList.getJSONObject(i).getString("Name") +" "+ Currency.britishPound+productsList.getJSONObject(i).getString("MinCost"); } catch (JSONException e) { e.printStackTrace(); } if(product!=null){ items[i]=product; } adapter = new ArrayAdapter<String>(APIQuickCheckout.this, R.layout.product_item, R.id.label, items); lv.setAdapter(adapter); } Here is my list view: <ListView android:id="#android:id/list" android:layout_width="match_parent" android:layout_height="0dp" android:layout_margin="5dip" android:layout_weight="30"> </ListView> And here is how I pass each product seperately. <?xml version="1.0" encoding="utf-8"?> <!-- Single List Item Design --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/label" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dip" android:textSize="16sp" android:textStyle="bold" > </TextView> Now and according to the the aforementioned code I'm passing to each line just a simple string. However, I was wondering how could I pass three different Strings. The reason that I want to pass three different Strings is that I want them to be in the following format: Quantity X Number Price(this should be at the end of the line)
You have to derive from adapter, and provide properly filled views. Like here: https://github.com/ko5tik/camerawatch/blob/master/src/de/pribluda/android/camerawatch/CameraAdapter.java For better performance consider: reusing views supplied to getView() method# utilise viewHolder patern to save getViewById() resolution
Android Feeding images from a Json Feed into a list
Hi i have a list i have it filling in a title from a Json Feed and now i want to add an image to it heres my single_list layout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="6dip"> <ImageView android:id="#+id/icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentBottom="true" android:layout_alignParentTop="true" /> <TextView android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#drawable/ic_gr_arrow" android:id="#+id/textView1" android:textColor="#color/blue" android:padding="20dp" android:textSize="10dp" /> </RelativeLayout> heres the an example of one news story from the JSON Feed i think it image_small i need {"code":200,"error":null,"data":{"news":[{"news_id":"8086","title":"Tickets for Player of the Year award on general sale","tagline":"Event to be held Sunday 25th March at Holiday Inn, Barnsley","content":"Tickets for the inaugural Evo-Stik NPL Player of the Year event are now on sale to the general public.\r\n\r\nPriced at \u00a335, tickets include a three course meal, plus entertainment from renowned tenor Martin Toal and guest speaker Fred Eyre.\r\n\r\nAwards at the event include the Player and Young Player of the Year for each division, as well as divisional teams of the year, the Fans\u2019 Player of the Year and a League Merit award.\r\n\r\nTo purchase your ticket, send a cheque for \u00a335 payable to \u201cNorthern Premier League\u201d to Alan Ogley, 21 Ibberson Avenue, Mapplewell, Barnsley, S75 6BJ. Please include a return address for the tickets to be sent to, and the names of those attending. \r\n\r\nFor more information, e-mail Tom Snee or contact Event organiser Alan Ogley on 07747 576 415\r\n\r\nNote: Clubs can still order tickets by e-mailing Angie Firth - simply state how many tickets you require and you will be invoiced accordingly.\r\n\r\nAddress of venue: Barnsley Road, Dodworth, Barnsley S75 3JT (just off Junction 37 of M1)","created":"2012-02-29 12:00:00","category_id":"1","img":"4539337","category":"General","fullname":"Tom Snee","user_id":"170458","image_user_id":"170458","image_file":"1330519210_0.jpg","image_width":"600","image_height":"848","sticky":"1","tagged_division_id":null,"tagged_team_id":null,"tagged_division":null,"tagged_team":null,"full_image":"http:\/\/images.pitchero.com\/up\/league-news-default-full.png","image_primary":"http:\/\/images.pitchero.com\/ui\/170458\/lnl_1330519210_0.jpg","image_secondary":"http:\/\/images.pitchero.com\/ui\/170458\/lns_1330519210_0.jpg","image_original":"http:\/\/images.pitchero.com\/ui\/170458\/1330519210_0.jpg","image_small":"http:\/\/images.pitchero.com\/ui\/170458\/sm_1330519210_0.jpg"} and heres my code so far String json = reader.readLine(); // Instantiate a JSON object from the request response JSONObject obj = new JSONObject(json); List<String> items = new ArrayList<String>(); JSONObject objData = obj.getJSONObject("data"); JSONArray jArray = objData.getJSONArray("news"); for (int i=0; i < jArray.length(); i++) { JSONObject oneObject = jArray.getJSONObject(i); items.add(oneObject.getString("title")); Log.i("items", "items"); } setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items)); ListView list = getListView(); list.setTextFilterEnabled(true); list.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show(); } }); } catch(Exception e){ // In your production code handle any errors and catch the individual exceptions e.printStackTrace(); }
I assume you want to load Image for every items in your listview, if this is the case then you can implement any solution from below: Lazy load of images in ListView Android Universal Image Loader by Nostra.