0
希望有人能夠幫助我理解這一點,我完全迷失了方向,似乎無法擺脫這種困擾。如何將Json字符串轉換爲Android中的ListView
我有一個信息是直接從數據庫中,此刻的應用程序,Android的連接到PHP頁面,結果被打印上的應用,如:
{"offer":"Half Price Drinks", "Day":"Monday"}
{"offer":"Half Price Drinks", "Day":"Tuesday"}
我需要將其轉換爲列表視圖,任何人都可以建議我如何做到這一點?
我已經把在連接到PHP頁面,並在拉該信息的頁面。
public class BarsActivity extends Activity {
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/SocialCrawler/content.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("day","Monday"));
//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);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}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","day: "+json_data.getString("day")+
", offer: "+json_data.getString("offer")
);
//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;
}
}
老實說。在互聯網上有像噸和大量的例子。 http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/和http://mobile.dzone.com/news/android-tutorial如何解析和大量的在這個網站 – 2012-02-23 01:29:10
數據如何映射到ListView?一個View會顯示今日優惠,還是ListView會顯示今日優惠和即將推出的優惠? – 2012-02-23 01:34:58
它只顯示那天的優惠清單,我有它,所以用戶選擇了一天,然後當天傳遞給PHP文件,該文件返回當天的優惠。 – niallian 2012-02-23 08:50:15