2015-07-20 17 views
-2

嗨,我正在關注此站點上的tutorial以創建數據庫。但是,我無法將自己的想法包含在如何查詢所有行並將其綁定到列表視圖中。這裏是我的代碼,以找到一個特定進入Android SQLite查詢所有行並將其綁定到列表視圖

public Entry findEntry(String entryName) { 
    String query = "SELECT * FROM " + TABLE_ENTRY + " WHERE " + ENTRY_NAME + " = \"" + entryName + "\""; 

    SQLiteDatabase db = this.getWritableDatabase(); 

    Cursor cursor = db.rawQuery(query, null); 

    Entry entry = new Entry(); 

    if(cursor.moveToFirst()) { 
     cursor.moveToFirst(); 
     entry.setId(Integer.parseInt(cursor.getString(0))); 
     entry.setEntryName(cursor.getString(1)); 
     entry.setEntryDesc(cursor.getString(2)); 
     entry.setEntryTime(cursor.getString(3)); 
     entry.setEntryDate(cursor.getString(4)); 
     entry.setEntryLocation(cursor.getString(5)); 
     entry.setImgUrI(cursor.getString(6)); 
    } else{ 
     entry = null; 
    } 
    db.close(); 
    return entry; 
} 

但是我想SELECT * FROM TABLE_ENTRY並返回條目名稱的列表,並將其加載到一個列表視圖,但我不知道怎麼樣。

+1

檢查'定義適配器'用'listview' – Rustam

回答

1

首先爲ListView的每一行創建一個xml文件。儘可能多地使用TextView,您希望從Entry類中顯示許多實例變量信息。

entry_list_row.xml:

<?xml version="1.0" encoding="utf-8"?> 
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
    android:padding="5dp" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TextView 
     android:id="@+id/entryListEntryIDTextView" 
     android:textSize="@dimen/page_entry_size" 
     android:padding="5dp" 
     android:layout_weight="1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"/> 

</TableRow> 

然後創建自定義適配器:

public class EntryListAdapter extends ArrayAdapter<Entry> { 

    Context ctx; 
    List<Entry> entryList; 
    LayoutInflater inflater; 

    public AccountListAdapter(Context context, ArrayList<Entry> entryList) { 
     super(context, R.layout.entry_list_row, entryList); 
     ctx = context; 
     accountList = accList; 
     inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     if(convertView == null) { 
      Account account = accountList.get(position); 
      convertView = inflater.inflate(R.layout.account_list_row, parent, false); 

      TextView entryListEntryIDTextView = (TextView) convertView.findViewById(R.id.entryListEntryIDTextView); 
      entryListEntryIDTextView.setText(entry.getID()); 
      //Do this for all other TextViews. For all the information you want to show up 
     } 
     return convertView; 
    } 
} 

然後在活動/片段:

ArrayList<Entry> entryList = database.getAllEntries(); //Use the object reference name to your data access class, and the appropriate method name. 

ListView entryListView = (ListView) findViewById(R.id.entryListView); //Or whatever you have named the ListView in the xml file of the activity 

entryListView.setAdapter(new EntryListAdapter(getActivity(), entryList)); 
相關問題