Common
Common

Reputation: 443

list results from mysql on a listview in android

I'm working on this tutorial, it's about querying the mysql database by using Json and a php script, and everything is just fine, but I'm working on listing these results you see here in a ListView and not as a TextView as you see below. Thats seems easy, but I can't make it work by replacing TextView with ListView. image:

Here is the tutorial (code inside) : http://blog.erlem.fr/fr/applications-mobiles/android/27-android-blog/applications-mobiles/android/59-android-connexion-a-mysql-a-laide-de-php.html

Upvotes: 0

Views: 891

Answers (1)

h4rpur
h4rpur

Reputation: 341

All of the below assumes you have already parsed the JSON out into an array. See this for parsing help.

ListViews use adapters to grab the elements to fill the list rows up with. You'll have to feed the JSON results into a SimpleListAdapter via a List or array (ArrayList, what have you.).

from this page about listviews:

SimpleAdapter nommes = new SimpleAdapter( 
this, 
list,
R.layout.main_item_two_line_row,
new String[] { "line1","line2" },
new int[] { R.id.text1, R.id.text2 } );

(in your case you could show/hide the id/name by using a one-line layout or a two-line layout like in this example)

Then apply the adapter

listView.setAdapter(nommes);

EDIT:

jObject = new JSONObject("<your JSON string from provider>");

// in my case: 

res = jObject.getJSONObject("results");

**dataAdapter = new ArrayAdapter<String>(this, R.layout.item, R.id.itemName);**

try {
  for (int r = 0; r < rslt.length(); r++){
    JSONArray jA = rslt.getJSONArray(Integer.toString(r));
    schoolLocString = jA.getString(0) +"|"+ jA.getString(1) +"[" + jA.optString(2);
    **dataAdapter.add(schoolLocString);**

  }
  **myListView.setListAdapter(dataAdapter);**
} catch (JSONException e) {
Log.v(TAG, "Exception " + e);
} catch (NullPointerException e){
Log.v(TAG, "NPE, no rslt");
}

This is a really lazy way to do it and probably bad practice, but you can get the idea.

Upvotes: 1

Related Questions