2011-06-13 71 views
1

我不知道我是這樣做的,因爲我對這種編程語言的知識有限......或者對於這個問題。讓我們看看我是否能夠做到這一點,以便我可以得到一些幫助。數據庫查詢到ListActivity

我運行一個查詢針對我的數據庫撤出所有條目的數據庫

DBAdapter.java的部分:

//***RETRIEVES ALL THE FINALSCORES***// 
public Cursor getAllFinalscores() 
{ 
    return db.query(DATABASE_TABLE, new String[] { 
      KEY_ROWID, 
      KEY_DATE, 
      KEY_FINALSCORE, 
      KEY_HOLESPLAYED}, 
      null, null, null, null, null); 
} 

我已經然後創建延伸ListActivity一個單獨的類(因爲我希望所有的內容顯示在列表視圖。

PastGames.java

import android.app.ListActivity; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.widget.ArrayAdapter; 

public class PastGames extends ListActivity { 

@Override 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.pastgames); 



    DBAdapter db = new DBAdapter(this); 

    db.open(); 
    Cursor c = db.getAllFinalscores(); 
    if (c.moveToFirst()) 
    { 
     do { 
      String[] listData = new String [] {c.getString(1), 
        c.getString(2), c.getString(3)}; 
      this.setListAdapter(new ArrayAdapter<String>(this, 
        R.layout.pastgames, listData)); 
     } 
     while (c.moveToNext()); 
    } 
    db.close(); 


} 

}

,然後我打電話,從我的主要活動(這只是要注意,不擴展ListActivity

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    switch (item.getItemId()) { 
case R.id.past_games: 
      Intent intentListGames = new Intent().setClass(this, PastGames.class); 
      this.startActivityForResult(intentListGames, 0); 
      return true; 
    } 
     return true; 
    } 

所以,如果我理解這個正確的,我打電話PastGames。從我的主要活動(然後啓動PastGames.java),並在PastGames.java內的java - onCreate我打開數據庫,運行我的查詢,關閉並希望進入列表視圖

我在LogCat中獲得以下內容選項ulator:

06-13 22:10:36.581: ERROR/AndroidRuntime(204): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deckert/com.deckert.PastGames}: java.lang.ClassCastException: android.widget.TextView 
06-13 22:10:36.581: ERROR/AndroidRuntime(204):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 
06-13 22:10:36.581: ERROR/AndroidRuntime(204):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 
06-13 22:10:36.581: ERROR/AndroidRuntime(204):  at android.app.ActivityThread.access$2200(ActivityThread.java:119) 

有人能幫我理解爲什麼這個工作不正常嗎?

預先感謝您,我爲這個巨大的帖子道歉!

回答

1

您在ArrayAdapter和您的PastGames Activity根視圖中使用相同的佈局。我想象你不想爲你的活動佈局使用ListView的佈局。我認爲這是導致ClassCastException的原因,因爲你的ListView的佈局可能被定義爲只使用一個簡單的TextView,並且該活動吹起來說它不能將ListView投射到TextView

+0

因此,我刪除了創建setContentView,並且我的XML文件是線性佈局中的TextView。 我現在正在獲取ArrayAdapter需要的資源ID是一個TextView 我該怎麼改變呢? – Rob 2011-06-13 23:02:33

+0

GOT IT!我需要從xml中刪除線性佈局,並且只能使用textview! – Rob 2011-06-13 23:25:28

1

您沒有正確創建要傳遞給listView的適配器。如果你看看適配器的構造函數,正在等待TextView。它沒有任何意義,你有主要佈局和這個textView相同的資源。我認爲你需要創建Textview並將其傳遞給構造函數;)