首页 文章

getBaseContext()和getApplicationContext()

提问于
浏览
0

在以下代码中, 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());
            }
        }
    }
}

1 回答

  • 1

    使用以下上下文来解决您的问题

    calendar1.this
    

    解释为什么你首先得到这个错误 . 您正在使用

    this.getBaseContext()this.getApplicationContext()showcalendar 内,这是一个 View.OnClickListener 类,从here可以看出,它没有那些方法 .

相关问题