我和日曆應用程序和基本工作思路背後的時候:我在特定日期添加事件的ListView和我想要做的是,當我點擊當天ListView中的特定事件,OnClick方法將採取從數據庫中事件的ID,並開始使用它新的活動。所以我需要將該ID傳遞給onClick方法。我發現類似的問題HERE,但不能完全理解我的情況。從數據庫中獲得物品的ID ListView項被點擊
我有這個createBookings
方法,它進入循環的每一天添加事件並返回當天事件列表。
public List<Booking> createBookings(Date data) {
if(data!=null) {
.....
ArrayList<Booking> events = new ArrayList<>();
if (c.moveToFirst()) {
do {
Integer eventID;
String eventTitle, start_date, start_time, end_date, color;
eventID = c.getInt(0);
eventTitle = c.getString(1);start_time = c.getString(4); color = "•"+c.getString(7);
if(eventTitle.isEmpty())eventTitle="(no title)";
Booking event = new Booking(eventID,color+" "+eventTitle+" "+start_time, data);
events.add(event);
} while (c.moveToNext());
}
return events;
}
我會假設傳遞eventID
這樣就可以了:
Booking event = new Booking(eventID,color+" "+eventTitle+" "+start_time, data);
,但我怎麼得到它後,當onClickListener被稱爲列表視圖?所有我設法做的是選擇的項目的getText值..
final List<String> mutableBookings = new ArrayList<>();
final ListView bookingsListView = (ListView) findViewById(R.id.bookings_listview);
final ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mutableBookings);
bookingsListView.setAdapter(adapter);
bookingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> bookingsListView, View view,
int position, long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getApplicationContext()," "+item, Toast.LENGTH_SHORT).show();
}
});
我的預訂類:
public class Booking {
private Integer id;
private String title;
private Date date;
public Booking(Integer id, String title, Date date) {
this.id = id;
this.title = title;
this.date = date;
}
//lets say I had this method here.. would it return the correct event id
//when called in onClickListener above?
public String getBookingId() {
return ""+id;
}
}
當我在'onItemClick()中放置'Booking booking = mutableBookings.get(position);'時,它給我一個錯誤: '必需:mypackagename .MainActivity.Booking 發現:java.lang.String' – Rimvydas
噢,我明白了,起初我還以爲'mutableBookings'是Booking'類的''一個,但ArrayList'字符串的一個'ArrayList',所以這錯誤 –
在那裏你將數據添加到'mutableBookings'?並且何時調用'createBookings()'方法? –