在以下代码中,getBaseContext()
和getApplicationContext()
出错,
两者都是红色的。
有谁知道如何解决它们?而且,我也想知道何时使用这两种方法。我在网上搜索过,但我不明白。任何人都可以简单地解释一下这两种方法吗?我是java的新手。
public class calendar1 extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_menu);
Button button1 = (Button) findViewById(R.id.addevent);
button1.setOnClickListener(new addevent());
Button button2 = (Button) findViewById(R.id.showcalendar);
button2.setOnClickListener(new showcalendar());
}
private class addevent implements View.OnClickListener {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
}
}
private class showcalendar implements View.OnClickListener{
public void onClick(View v){
String[] projection = new String[] { CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.ALL_DAY, CalendarContract.Events.EVENT_LOCATION };
// 0 = January, 1 = February, ...
Calendar startTime = Calendar.getInstance();
startTime.set(2014,00,01,00,00);
Calendar endTime= Calendar.getInstance();
endTime.set(2015,00,01,00,00);
// the range is all data from 2014
String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + startTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ))";
Cursor cursor = this.getBaseContext().getContentResolver().query( CalendarContract.Events.CONTENT_URI, projection, selection, null, null );
// output the events
if (cursor.moveToFirst()) {
do {
Toast.makeText(this.getApplicationContext(), "Title: " + cursor.getString(1) + " Start-Time: " + (new Date(cursor.getLong(3))).toString(), Toast.LENGTH_LONG).show();
} while ( cursor.moveToNext());
}
}
}
}
答案 0 :(得分:1)
使用以下上下文解决您的问题
calendar1.this
首先解释为什么会出现这个错误。您正在使用
this.getBaseContext()
中的this.getApplicationContext()
和showcalendar
View.OnClickListener
,这是一个schedule
类,您可以从here看到,它没有这些方法。