2012-03-18 149 views
0

我從數據庫的行中帶來數據,我想在列表視圖中顯示它們。想象一下,我正在帶名字和電話,所以我希望每一行listview都有電話和名字。從數據庫獲取數據到一個列表視圖

到目前爲止,這是我的代碼:(項目正在正常提出,我看到他們使用system.out。ptintln)。所以在info [0]我有名字,並且在info [1]我有電話。

這是我的適配器代碼。

public class FacilitiesAdapter extends ArrayAdapter<String> { 
     private final Context context; 
     private String data[] = null; 

     public FacilitiesAdapter(Context context, String[] data) { 
      super(context, R.layout.expand_row); 
      this.context = context; 
      this.data = data; 

     } 
     public View getView(int position, View convertView, ViewGroup parent) { 
       LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       View rowView = inflater.inflate(R.layout.expand_row, parent, false); 
       TextView textView = (TextView) rowView.findViewById(R.id.name); 
       System.out.println("I am in the adapter "+data[0]); 
       textView.setText(data[0]); 
TextView textView2 = (TextView) rowView.findViewById(R.id.phone); 
textView2.setText(data[1]); 
       return rowView; 
     } 
} 

所以我想用上面的代碼,我必須在每行看到數據0和數據[1](電話)?但我錯了。這是爲什麼?

這是我javacode:

JSONArray jArray = new JSONArray(result); 
     for(int i=0;i<jArray.length();i++){ 
      //each line fetches a line of the table 
       JSONObject json_data = jArray.getJSONObject(i); 
       if (json_data.getString("Name")!=null) info[0]=json_data.getString("Name"); 
       if (json_data.getString("Phone")!=null) info[1]=json_data.getString("Phone"); 

       FacilitiesAdapter adapter = new FacilitiesAdapter(this,info); 
       System.out.println(info[0]); 
       setListAdapter(adapter); 

回答

2

你是在一個循環,這是奇怪的做setListAdapter,我敢打賭這不是你打算做。你只需要用你的數據填充字符串數組,然後用 字符串數組 列出字符串數組並做setListAdapter一次初始化您的FacilitiesAdapter。

編輯:

我想你誤會適配器背後的概念,一個適配器是用於保存數據對於整個AdapterView,這是ListView的父類,而不是用於保存數據的單個項目在AdapterView中。

您需要的String[]一個List您的適配器,類似如下:

public FacilitiesAdapter ... { 
    List<String[]> dataList; 
    public FacilitiesAdapter (List<String[]> dataList) { 
     this.dataList = dataList; 
    } 
    public View getView(int position, View convertView, ViewGroup parent) { 
     String[] data = dataList.get(position); 
     // set your data to the views. 
    } 
} 

編輯2:

List<String[]> listData = new ArrayList<String[]>(); 
for(int i = 0; i < jArray.length(); ++i) { 
    JSONObject json_data = jArray.getJSONObject(i); 
    String name = json_data.getString("Name"); 
    String phone = json_data.getString("Phone"); 
    //... some code to check *nullity* of name and phone 
    listData.add(new String[]{name, phone}); 
}  

上面的代碼將填補listData姓名和電話(存儲在一個數組中)從JSONObject獲得。現在,您可以將此listData作爲參數傳遞給適配器的構造函數。

如果你仍然沒有得到它,你需要一本關於Java編程語言的書,在你使用該語言編程Android之前掌握語言將幫助你更好地學習其他東西。

+0

謝謝。你能告訴我關於java調用中的參數嗎?我的意思是,而不是上面的信息[],我明白我必須傳遞2個數組,一個名字[]和一個電話[],對嗎? – 2012-03-18 12:29:37

+0

你不需要傳遞2個數組,請閱讀我的答案(包括代碼片段)。 – neevek 2012-03-18 12:47:18

+0

好吧,我讀了你的答案,但我不明白這一點。我如何在java中定義我的列表,以及如何用數據「填充」它? – 2012-03-18 12:52:04