2011-05-25 67 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

相关问题