Reputation: 1194
I am connecting to a server from an android device and querying the database and displaying the result on the screen. However I want to display my result in a ListView. How can I get my code to display in a ListView? At the moment it just parses the data and displays it on the screen. How can I give each value of ContactName a reference value? Below is my code:
public class DbConnectActivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://10.0.2.2/dbconnect.php"; //i use my real ip here
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
// ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("EngID","1"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//return result;
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","Name: "+json_data.getString("ContactName")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Upvotes: 1
Views: 2177
Reputation: 592
public class JsonExampleActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL("your url here");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONObject ja = new JSONObject(line);
/*
//for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject("_api_error");
listItems.add(jo.getString("name"));*/
JSONArray jobj=ja.getJSONArray("artists");
//JSONArray ja = new JSONArray(line);
for (int i = 0; i < jobj.length(); i++) {
JSONObject jo = jobj.getJSONObject(i);
listItems.add(jo.getString("artist_name"));
}
// }
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
Upvotes: 4
Reputation: 1036
I'd make sure you are making your requests in a background thread(eg async task or intent service) or your app may crash if it takes to long.
As for the list activity
http://www.vogella.de/articles/AndroidListView/article.html
This tutorial will show you how to create a custom model and populate it into a list view with custom xml.
Upvotes: 0
Reputation: 13541
Learn the Basics of an Custom Adapter then...
Whenever you want to do processing with the views in a ListView you need to create a custom adapter that will handle your logic implementation and pass that information to the views as necessary.
Upvotes: 0
Reputation: 29199
You can add all json objects into a list, and then load list from there on, but as you have prepared a method which returns a single string. you can use following:
Use
String[] tokens=returnString.split("\n\r");
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, tokens);
listView.setAdapter(adapter);
Upvotes: 0
Reputation: 4445
Simplest thing that I would do is to put JSONArray in some ArrayList and use it in arrayadapter
Upvotes: 0