android - 上下文和日历

标签 android calendar android-context

我正在使用一种方法将事件添加到手机的内部日历中。语境一直让我感到困惑,这次也不异常(exception)。方法契约需要应用程序上下文。方法调用是:

addToCalendar(Context context, String title, long dtstart, long dtend);

这是我在按下按钮时调用方法的代码:

public class DateAdder extends Activity {
String shiftType;
Date d = new Date();


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 




    Button AShift = (Button) findViewById(R.id.AShift);
    AShift.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            TextView BtmTxt = (TextView) findViewById(R.id.BtmTxt);
            shiftType="A Shift";
            addToCalendar(DateAdder.this.getApplicationContext(), shiftType, d.getDate(), d.getDate()+1000);                
            BtmTxt.setText("Done");
        }});
} //END of onCreate



/**
 * Adds the event to a calendar. It lets the user choose the calendar
 * @param ctx Context ( Please use the application context )
 * @param title title of the event
 * @param dtstart Start time: The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
 * @param dtend End time: The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
 */
private static void addToCalendar(Context ctx, final String title, final long dtstart, final long dtend) {
    final ContentResolver cr = ctx.getContentResolver();
    Cursor cursor ;
    if (Integer.parseInt(Build.VERSION.SDK) == 8 )
        cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
    else
        cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
    if ( cursor.moveToFirst() ) {
        final String[] calNames = new String[cursor.getCount()];
        final int[] calIds = new int[cursor.getCount()];
        for (int i = 0; i < calNames.length; i++) {
            calIds[i] = cursor.getInt(0);
            calNames[i] = cursor.getString(1);
            cursor.moveToNext();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setSingleChoiceItems(calNames, -1, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                ContentValues cv = new ContentValues();
                cv.put("calendar_id", calIds[which]);
                cv.put("title", title);
                cv.put("dtstart", dtstart );
                cv.put("dtend", dtend);
                cv.put("allday", 1);
                cv.put("hasAlarm", 0);

                Uri newEvent ;
                if (Integer.parseInt(Build.VERSION.SDK) == 8 )
                    newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
                else
                    newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);

                if (newEvent != null) {
                    long id = Long.parseLong( newEvent.getLastPathSegment() );
                    ContentValues values = new ContentValues();
                    values.put( "event_id", id );
                    values.put( "method", 1 );
                    values.put( "minutes", 15 ); // 15 minuti
                    if (Integer.parseInt(Build.VERSION.SDK) == 8 )
                        cr.insert( Uri.parse( "content://com.android.calendar/reminders" ), values );
                    else
                        cr.insert( Uri.parse( "content://calendar/reminders" ), values );

                }
                dialog.cancel();
            }

        });

        builder.create().show();
    }
    cursor.close();
}

当我从我的代码中调用它时,我得到了强制关闭。 logcat 显示:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

最佳答案

您的问题是您正在创建一个附加到应用程序上下文的对话框,它是非可视的。正如我所见,您无论如何都不需要应用程序上下文,因为您所做的只是访问内容解析器。

你只需要改变这一行:

addToCalendar(DateAdder.this.getApplicationContext(), 
    shiftType, d.getDate(), d.getDate()+1000);

为此:

addToCalendar(DateAdder.this, 
    shiftType, d.getDate(), d.getDate()+1000);

错误消失了。 (我测试过)。

附录:

同时更改 addToCalendar() 的第一行以使用应用程序上下文,从而满足评论的要求,但我不相信它会有所作为。即:

final ContentResolver cr = ctx.getApplicationContext().getContentResolver();

关于android - 上下文和日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4300198/

相关文章:

java - 带开关( boolean 值)Android 的 ListView

java - 使用 GridView 启动应用程序时窗口已满

android - Dagger 2 : Error when two components has same inject method signature

c# - 日历绑定(bind) SelectedDate 和 DisplayDate : gray dates

java - 如何将 Context 传递给 Fragment 类

android - 将小部件存储在应用程序中是否会导致性能损失(或内存泄漏)?

java - 找到应用程序在 Android 操作系统世界中某处崩溃之前执行的代码中的最后一点?

java - 日历返回错误时间

java - 比较 enum 与 int、Calendar 类

java - 在android中显示之前修改字符串值