2013-10-02 100 views
1

我已經使用eclipse創建了一個不錯的應用程序,就像字典應用程序 - 基本上是可搜索的術語列表。我想在用戶搜索不存在的術語時創建一個新的活動。目前,當這種情況發生時,列表視圖是空白的,我不認爲這是非常有用的,所以我至少希望有一個彈出窗口或者說「沒有這樣的術語」或「請提交這個新術語」或而不是空白。數據庫查詢在沒有結果時顯示消息

每當我搜索這個挑戰的答案時,我都會遇到與數據庫問題等有關的問題。

如果找不到/ null/zero結果,我可以在下面的代碼中添加一個條件嗎?

public void search(View view) { 
    cursor = db.rawQuery(
     "SELECT _id, term, definition FROM term WHERE term LIKE ?", 
     new String[]{"%" + searchText.getText().toString() + "%"}); 

    adapter = new SimpleCursorAdapter(
     this, 
     R.layout.term_list_layout, 
     cursor, 
     new String[] {"term", "definition"}, 
     new int[] {R.id.term, R.id.definition}); 

    setListAdapter(adapter); 
} 

非常感謝!

回答

1

您需要使用setEmptyView()與任何你想要的列表視圖顯示時,有沒有結果

編輯

檢查光標這樣

if(cursor.moveToFirst()){ 
    //cursor is no empty, set up list 
    adapter = new SimpleCursorAdapter(
    this, 
    R.layout.term_list_layout, 
    cursor, 
    new String[] {"term", "definition"}, 
    new int[] {R.id.term, R.id.definition}); 

    setListAdapter(adapter); 
}else{ 
    //cursor is empty start new activity 
} 
+0

確定設置在XML視圖。這可能是一個很好的解決方案。但是我想更進一步,並在沒有結果的情況下開始活動。我希望有一種方法可以做,如果結果= false - >開始活動... – user2838830

+0

然後只是檢查,看看你的光標是否爲空,然後再做任何事情。如果它的空開始一個新的活動,如果沒有然後顯示您的列表 – tyczj

+0

看到我的編輯如何檢查 – tyczj

0

如果我沒有理解你的問題正確,你想利用你的列表視圖的「空」視圖。只要列表視圖不包含條目,該視圖就會顯示。

mMyListView.setEmptyView(findViewById(R.id.emptyView)); 

也可以通過指定正確的ID是@android:id/empty

<ListView android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 

<TextView android:id="@android:id/empty" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:text="List is empty" 
     android:gravity="center"/> 
+0

是的,您瞭解我的問題很接近。這可能是一個很好的解決方案。但是我想更進一步,並在沒有結果的情況下開始活動。我希望有某種方式來做一個像這樣的陳述;如果結果= false - >開始活動... – user2838830

+0

填充後請檢查您的適配器。如果它包含結果,則開始新的活動 – Kuffs

相關問題