2011-05-25 76 views
0

我是新來的android,並且出於某種原因使用了ArrayAdapter的add函數時出現異常。嘗試將字符串添加到ListView後引發的異常

我知道這個過程應該是微不足道的,但我找不到我的錯誤。

我試圖將&時間的記錄添加到ListView

這裏是我如何做它:

文件名:ClockTest.java

/* package name here */ 

/* import section here */ 
public class ClockTest extends Activity { 

/** Called when the activity is first created. */ 
public int logButtonState; 
public int logEntriesCount; 
ImageButton logButton; 
ImageButton switchButton; 
ListView entriesList; 

public ArrayAdapter<String> listAdapter; 

public String logEntries[]={ 
     "Entry1", 
     "Entry2", 
     "Entry3", 
     "Entry4", 
     "Entry5"}; 

public String date_info; 
public String time_info; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     // State: 0=login, 1=logout 
     logButtonState = 0; 
     logButton = (ImageButton)findViewById(R.id.log_button); 
     switchButton = (ImageButton)findViewById(R.id.switch_button); 

     // Infrastructure for entries on-screen presentation 
     logEntriesCount = 0; 

     listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,              
              logEntries); 

     entriesList = (ListView)findViewById(R.id.entries_list); 
     entriesList.setAdapter(listAdapter); 

     // add a click listener to the exit button 
     logButton.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      TextView timeCaptured = (TextView)findViewById(R.id.timeCaptured); 
      Calendar c = Calendar.getInstance(); 
      c.setTime(new Date(System.currentTimeMillis())); 

      date_info = String.valueOf(c.get(Calendar.DAY_OF_MONTH)) 
         + "." 
         + String.valueOf(c.get(Calendar.MONTH)) 
         + "." 
         + String.valueOf(c.get(Calendar.YEAR)); 

      time_info = String.valueOf(c.get(Calendar.HOUR_OF_DAY)) 
       + ":" 
       + String.valueOf(c.get(Calendar.MINUTE)) 
       + ":" 
       + String.valueOf(c.get(Calendar.SECOND)); 

      final String currentTime = asignLogString() 
           + " [" 
           + date_info 
          + " " 
          + time_info 
           + "]"; 

      logEntriesCount++; 
      timeCaptured.setText(currentTime); 

      //listAdapter.clear(); 
      // re-arrange on-screen list view 
      listAdapter.add(currentTime); 
      listAdapter.notifyDataSetChanged();    
      entriesList.setAdapter(listAdapter); 
       } 
     });  
    } 
} 
+0

logcat中的錯誤是什麼? – Haphazard 2011-05-25 18:45:06

+0

謝謝@Haphazard花費的時間,我感謝你的努力。布魯斯幫我解決了它。 – 2011-05-27 14:17:35

回答

0

一個ArrayAdapter有一個不可修改的列表。你將無法添加東西,否則你會得到一個UnsupportedOperationException(從我記得)。

不是使用String [],而是使用ArrayList <字符串>。

查看Populate Spinner dynamically in android from edit text尋找解決方案。

+0

**謝謝布魯斯!**你爲我節省了大量的挫折,時間和精力。 – 2011-05-27 14:06:59

+0

布魯斯,來自我來自(以色列)的地方,習慣上保佑有幫助的人。我向你保證,你的一個偉大願望(爲了好)將在今年年底實現。並再次感謝你。 – 2011-05-27 14:14:53

相關問題