NullPointerException异常的android.content.ContextWrapper [英] NullPointerException at android.content.ContextWrapper
本文介绍了NullPointerException异常的android.content.ContextWrapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试获得通过 getResources颜色()的getColor(R.color.yellow)
在一个正常的活动我得到这个异常:
11月七号日至12日:58:38.019:E / AndroidRuntime(3233):致命异常:主要
11月7日至12日:58:38.019:E / AndroidRuntime(3233):java.lang.RuntimeException的:无法实例活动ComponentInfo {com.moveinblue.planner / com.moveinblue.planner.controller.plan.PlanDayScreen}:java.lang中。空指针异常
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1993)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.ActivityThread.access $ 600(ActivityThread.java:132)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1157)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.os.Handler.dispatchMessage(Handler.java:99)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.os.Looper.loop(Looper.java:137)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.ActivityThread.main(ActivityThread.java:4575)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在java.lang.reflect.Method.invokeNative(本机方法)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在java.lang.reflect.Method.invoke(Method.java:511)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:789)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在dalvik.system.NativeStart.main(本机方法)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):由:显示java.lang.NullPointerException
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.content.ContextWrapper.getResources(ContextWrapper.java:81)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在com.moveinblue.planner.controller.plan.PlanDayScreen $ 4< INIT>(PlanDayScreen.java:408)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在com.moveinblue.planner.controller.plan.PlanDayScreen< INIT>(PlanDayScreen.java:406)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在java.lang.Class.newInstanceImpl(本机方法)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在java.lang.Class.newInstance(Class.java:1319)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.Instrumentation.newActivity(Instrumentation.java:1023)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1984)
11月7日至12日:58:38.019:E / AndroidRuntime(3233):11 ...更多
任何人都可以给我一些后知后觉吗?我完全失去了。
code。在活动:
包com.moveinblue.planner.controller.plan;
进口java.text.SimpleDateFormat的;
进口java.util.BitSet中;
进口的java.util.Calendar;
进口android.app.AlertDialog;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.ArrayAdapter;
进口android.widget.AutoCompleteTextView;
进口android.widget.ImageButton;
进口android.widget.ImageView;
进口android.widget.ListView;
进口android.widget.Toast;
进口com.moveinblue.api.Login;
进口com.moveinblue.api.Planner;
进口com.moveinblue.api.UnauthorizedException;
进口com.moveinblue.api.io.InvalidURLException;
进口com.moveinblue.api.io.OfflineException;
进口com.moveinblue.api.model.ModelObject;
进口com.moveinblue.api.model.Plan;
进口com.moveinblue.api.model.time.Day;
进口com.moveinblue.api.model.time.ScheduledThingToDo;
进口com.moveinblue.api.model.time.ScheduledTime;
进口com.moveinblue.api.model.time.ScheduledTime.TimeOfDay;
进口com.moveinblue.planner.R;
进口com.moveinblue.planner.controller.GenericPlannerScreen;
进口com.moveinblue.planner.controller.thingtodo.ThingsToDoListScreen;
进口com.moveinblue.planner.controller.user.LoginScreen;
进口com.moveinblue.planner.ui.actionbar.ActionBar;
进口com.moveinblue.planner.ui.draganddroplist.DragListener;
进口com.moveinblue.planner.ui.draganddroplist.DragNDropListView;
进口com.moveinblue.planner.ui.draganddroplist.DropListener;
进口com.moveinblue.planner.ui.draganddroplist.RemoveListener;
进口com.moveinblue.planner.utils.CommonActionStorage;
进口com.moveinblue.planner.utils.CurrentItemsStorage;
进口com.moveinblue.planner.utils.adapter.DragNDropAdapter;
进口com.moveinblue.planner.utils.adapter.listeners.OnCheckListener;
公共类PlanDayScreen扩展GenericPlannerScreen {
DragNDropListView LISTA;
AutoCompleteTextView ACTV;
的String [] dests;
DragNDropAdapter适配器;
私人布尔idDroppedOrDeleted = FALSE;
私人位集合checkedBoxes =新的BitSet();
私人布尔firstLoad = TRUE;
日复一日;
@燮pressWarnings(未使用)
私有静态最后弦乐LOG_TAG = PlanDayScreen.class
.getCanonicalName();
@覆盖
公共无效负载(){
的setContentView(R.layout.plan_day_list);
setUpList();
setUpBottomLayout(假);
lista.requestFocus();
}
@覆盖
保护无效loadActionBar(){
计划P = CurrentItemsStorage.currentPlan;
日历C = CurrentItemsStorage.currentDay;
AB =新的动作条(本,ActionBar.TYPE_LIST);
。字符串日期=新的SimpleDateFormat(MMM DD,YYYY)格式(c.getTime());
日期= Character.toUpperCase(date.charAt(0))+ date.substring(1);
日期=(+日期+);
字符串称号;
标题=(P!= NULL)? p.name ++日期计划草案;
ab.setTitle(职称);
ab.setBackAction(R.drawable.back,新OnClickListener(){
@覆盖
公共无效的onClick(查看为arg0){
意向意图=新的意图(PlanDayScreen.this,
PlanTabsScreen.class);
intent.putExtra(标签,2);
startActivity(意向);
overridePendingTransition(android.R.anim.slide_in_left,
android.R.anim.fade_out);
}
});
CommonActionStorage.setUpActionBar(AB);
}
私人无效addNewTTD(){
如果(getIntent()getBooleanExtra(时间表,假)及。&安培; firstLoad){
尝试 {
日历C = CurrentItemsStorage.currentDay;
TimeOfDay的TOD = CurrentItemsStorage.currentTimeOfDaySelectedOption;
Planner.schedule(
CurrentItemsStorage.getCurrentThingToDo()。ttdId,
新ScheduledTime(C,TOD));
}赶上(例外前){
ex.getStackTrace();
}
}
firstLoad = FALSE;
}
/ **
*设定底栏按钮
*
* @参数ID
*您要设置的底部栏按钮的ID
* /
私人无效setUpBottomButton(INT ID){
的ImageButton B =(的ImageButton)findViewById(ID);
开关(ID){
案例R.id.buttonBottom1:
如果(!areThereCheckedBoxes()){
b.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
//添加TTD计划
意向意图=新的意图(PlanDayScreen.this,
ThingsToDoListScreen.class);
startActivity(意向);
}
});
} 其他 {
b.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
// 日期
}
});
}
打破;
案例R.id.buttonBottom2:
如果(!areThereCheckedBoxes()){
b.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
// 地图
如果(天!= NULL){
CurrentItemsStorage.mapModelObjects =新ModelObject [0];
CurrentItemsStorage.mapModelObjects [1] =天;
意向意图=新的意图(PlanDayScreen.this,
PlanTabsScreen.class);
startActivity(意向);
}
}
});
} 其他 {
b.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
// 确认
新AlertDialog.Builder(PlanDayScreen.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(
删除+ checkedCount()
+要做的事情)
.setMessage(
你真的要删除
+ checkedCount()
+的东西,从你的计划吗?)
.setPositiveButton(是,
新DialogInterface.OnClickListener(){
@覆盖
公共无效的onClick(
DialogInterface对话框,
其中INT){
//删除
的for(int i = 0; I< LISTA
.getCount();我++){
如果(checkedBoxes.get(i))的{
//获取检查项目
对象TTD =适配器
.getItem(ⅰ);
如果(TTD的instanceof ScheduledThingToDo){
尝试 {
// 去掉它
ScheduledThingToDo TTD =(ScheduledThingToDo)TTD;
Planner.unschedule(
tTD.ttdId,
tTD.time);
}赶上(OfflineException前){
Toast.makeText(
PlanDayScreen.this,
getResources()
.getString(
R.string.unschedule_error)
Toast.LENGTH_SHORT)
。显示();
}赶上(InvalidURLException E){
}
}
}
}
//重置checkedBoxes和
// BottomLayout
checkedBoxes =新的BitSet();
setUpBottomLayout(假);
//重绘列表
setUpList();
}
})setNegativeButton(否,空).show()。
}
});
}
打破;
案例R.id.buttonBottom3:
b.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
//更新
}
});
打破;
}
}
/ **
*设定列表
* /
私人无效setUpList(){
LISTA =(DragNDropListView)findViewById(R.id.listViewAgenda);
新LoadList();
}
/ **
*计数检查箱子的数量
*
返回:托运箱数
* /
私人诠释checkedCount(){
INT X = 0;
的for(int i = 0; I< checkedBoxes.length();我++){
X + = checkedBoxes.get(我)? 1:0;
}
返回X;
}
/ **
*更改底部操作栏上的buttoms。如果传递真实,你会得到
*删除项目操作栏。否则,你得到的添加项目操作栏。
*
* @参数isAnythingMarked
*如果你想,如果你想添加删除的项目,假假真真
* 他们。
* /
私人无效setUpBottomLayout(布尔isAnythingMarked){
的ImageButton B1 =(的ImageButton)findViewById(R.id.buttonBottom1);
的ImageButton B2 =(的ImageButton)findViewById(R.id.buttonBottom2);
的ImageButton B3 =(的ImageButton)findViewById(R.id.buttonBottom3);
b1.setImageDrawable(getResources()。getDrawable(
isAnythingMarked? R.drawable.action_plans
:R.drawable.action_add));
b2.setImageDrawable(getResources()。getDrawable(
isAnythingMarked? R.drawable.action_delete
:R.drawable.action_map));
b3.setImageDrawable(getResources()
.getDrawable(R.drawable.action_reload));
setUpBottomButton(R.id.buttonBottom1);
setUpBottomButton(R.id.buttonBottom2);
setUpBottomButton(R.id.buttonBottom3);
}
私人布尔areThereCheckedBoxes(){
的for(int i = 0; I< checkedBoxes.length();我++){
如果(checkedBoxes.get(i))的{
返回true;
}
}
返回false;
}
公共无效clickControlRowHandler(视图v){
意向意图=新的意图(PlanDayScreen.this,
ThingsToDoListScreen.class);
startActivity(意向);
}
/ **
*删除侦听DragNDropListView
* /
私人DropListener mDropListener =新DropListener(){
公共无效onDrop(从最终诠释,诠释到){
如果(至== 0)
为= 1;
//如果初始位置是相同的最终位置,什么也不做。
如果(至!=从){
如果(适配器的instanceof DragNDropAdapter){
如果(adapter.getItem(从)的instanceof ScheduledThingToDo){
新DropCall(从,到);
((DragNDropAdapter)适配器).onDrop(从,到);
}
}
}
}
};
公共OnClickListener onClickSave =新OnClickListener(){
公共无效的onClick(视图v){
尝试 {
如果(Login.isRegistered()){
如果(Planner.loadPlan()。名称== NULL){
CurrentItemsStorage.shallGoAfterCreatePlan = PlanDayScreen.class;
如果(idDroppedOrDeleted){
manageListChanges();
}
意向意图=新的意图(PlanDayScreen.this,
SavePlanScreen.class);
startActivity(意向);
返回;
}
} 其他 {
CurrentItemsStorage.currentPlan = Planner.loadPlan();
CurrentItemsStorage.shallGoAfterLogin = PlanDayScreen.class;
意向意图=新的意图(PlanDayScreen.this,
LoginScreen.class);
startActivity(意向);
}
}赶上(OfflineException E){
Toast.makeText(PlanDayScreen.this,
getResources()的getString(R.string.plan_error)
Toast.LENGTH_SHORT).show();
}
如果(idDroppedOrDeleted){
manageListChanges();
}
}
};
/ **
* Unschedules每TTD,然后再次调度它。
* /
私人无效manageListChanges(){
的for(int i = 0; I< adapter.getCount();我++){
对象项目= adapter.getItem(我);
如果(项目的instanceof ScheduledThingToDo){
尝试 {
ScheduledThingToDo计划=(ScheduledThingToDo)项目;
Planner.unschedule(scheduled.getId(),scheduled.time);
}赶上(例外五){
e.printStackTrace();
}
}
}
INT状态= 0;
对于(INT它= 0;它< adapter.getCount();它++){
对象项目= adapter.getItem(它);
TimeOfDay的TOD = TimeOfDay.morning;
如果(项目的instanceof ScheduledThingToDo){
开关(州){
情况1:
TOD = TimeOfDay.morning;
打破;
案例2:
TOD = TimeOfDay.afternoon;
打破;
案例3:
TOD = TimeOfDay.evening;
打破;
}
尝试 {
Planner.schedule(((ScheduledThingToDo)项).ttdId,
新ScheduledTime(CurrentItemsStorage.currentDay,
TOD));
}赶上(OfflineException E){
Toast.makeText(PlanDayScreen.this,无连接,
Toast.LENGTH_SHORT).show();
}
} 其他 {
国家++;
}
}
}
/ **
*的removeListener为DragNDropListView
* /
私人的removeListener mRemoveListener =新的removeListener(){
公共无效onRemove(INT它){
// ListAdapter适配器= getListAdapter();
如果(适配器的instanceof DragNDropAdapter){
((DragNDropAdapter)适配器).onRemove(所);
lista.invalidateViews();
}
}
};
/ **
* DragListener为DragNDropListView
* /
私人DragListener mDragListener =新DragListener(){
INT的backgroundColor = getResources()的getColor(R.color.yellow)。
INT defaultBackgroundColor = getResources()的getColor(R.color.blue_bg)。
公共ondrag当无效(INT X,INT Y,ListView控件的ListView){
// TODO自动生成方法存根
}
公共无效onStartDrag(查看ItemView控件){
itemView.setVisibility(View.INVISIBLE);
itemView.setBackgroundColor(的backgroundColor);
ImageView的IV =(ImageView的)itemView.findViewById(R.id.imageView1);
如果(IV!= NULL)
iv.setVisibility(View.INVISIBLE);
}
公共无效onStopDrag(查看ItemView控件){
itemView.setVisibility(View.VISIBLE);
itemView.setBackgroundColor(defaultBackgroundColor);
ImageView的IV =(ImageView的)itemView.findViewById(R.id.imageView1);
如果(IV!= NULL)
iv.setVisibility(View.VISIBLE);
}
};
私有类LoadList扩展的AsyncTask<虚空,虚空,虚空> {
公共LoadList(){
执行();
}
@覆盖
在preExecute保护无效(){
的String [] X = {载入中...};
addNewTTD();
ArrayAdapter<字符串>航空自卫队=新的ArrayAdapter<字符串>(
PlanDayScreen.this,R.layout.add_more,x)的;
lista.setAdapter(ASDF);
}
@覆盖
保护无效doInBackground(虚空......为arg0){
ScheduledThingToDo [] TTDS;
尝试 {
尝试 {
//加载当前天
天= Planner.loadDay(CurrentItemsStorage.currentDay);
TTDS = day.ttds;
}赶上(NullPointerException异常前){
//没有当前天:今天负载
日复一日= Planner.loadDay(Calendar.getInstance());
TTDS = day.ttds;
}
}赶上(OfflineException E){
//当前离线
Toast.makeText(PlanDayScreen.this,
getResources()的getString(R.string.day_error)
Toast.LENGTH_SHORT).show();
TTDS =新ScheduledThingToDo [0];
}赶上(UnauthorizedException E){
//奇怪的事情发生
TTDS =新ScheduledThingToDo [0];
}赶上(例外五){
//东西更奇怪的事情发生
TTDS =新ScheduledThingToDo [0];
}
适配器=新DragNDropAdapter(PlanDayScreen.this,
新的INT [] {} R.layout.dragitemttd,TTDS);
adapter.setOnCheckListener(新OnCheckListener(){
@覆盖
公共无效的oncheck(布尔器isChecked,INT位置){
checkedBoxes.set(位置,器isChecked);
setUpBottomLayout(areThereCheckedBoxes());
}
});
返回null;
}
@覆盖
保护无效onPostExecute(无效的结果){
lista.setAdapter(适配器);
lista.setDropListener(mDropListener);
lista.setRemoveListener(mRemoveListener);
lista.setDragListener(mDragListener);
}
}
私有类DropCall扩展的AsyncTask<虚空,虚空,虚空> {
从到私人诠释;
公共DropCall(从int,int值){
this.from =距离;
this.to =到;
执行();
lista.invalidateViews();
}
@覆盖
保护无效doInBackground(虚空......为arg0){
changeScheduledTTD(从,到);
返回null;
}
/ **
* Unschedules一个TTD,然后重新安排其在适当的位置
*
*从@param
*在TTD来自位置
* @参数来
*该位置TTD一直拖到
* /
保护无效changeScheduledTTD(INT从,INT到){
ScheduledThingToDo currentTTD;
如果(adapter.getItem(到)的instanceof ScheduledThingToDo)
currentTTD =(ScheduledThingToDo)adapter.getItem(到);
其他
返回;
INT indexMorning = 0;
INT indexAfternoon = 0;
INT indexEvening = 0;
对象项目= NULL;
字符串currentTime的= NULL;
//获取索引,上午,下午和晚上
的for(int i = 0; I< adapter.getCount();我++){
项= adapter.getItem(ⅰ);
如果(项目的instanceof字符串){
currentTime的=(字符串)项目;
如果(currentTime.equals(早晨)){
indexMorning =我;
}
如果(currentTime.equals(午)){
indexAfternoon =我;
}
如果(currentTime.equals(黄昏)){
indexEvening =我;
}
}
}
TimeOfDay的TOD = NULL;
如果(到大于= indexEvening){
TOD = TimeOfDay.evening;
}否则如果(到大于= indexAfternoon){
TOD = TimeOfDay.afternoon;
}否则如果(到大于= indexMorning){
TOD = TimeOfDay.morning;
}
如果(!currentTTD.time.getTimeOfDay()。等于(TOD)){
尝试 {
Planner.unschedule(currentTTD.ttdId,currentTTD.time);
Planner.schedule(currentTTD.ttdId,新ScheduledTime(
CurrentItemsStorage.currentDay,TOD));
}赶上(OfflineException E){
e.printStackTrace();
}
}
}
}
}
解决方案
您 mDragListener
是一个成员变量。在初始化活动对象的点/实例可能还没有准备好。因此调用的getResource()
的活动将失败。
//内部类和普通类的...如果需要更改范围
私有类DragListener {
INT颜色= 0;
公共DragListener(上下文的背景下){
。颜色= context.getResource()的getColor(R.color.yellow);
}
}
// 活动
私人DragListener mDragListener;
公共无效的onCreate(...){
mDragListener =新DragListener(本);
//更多code
}
When I try to get a color via getResources().getColor(R.color.yellow)
in a normal Activity I get this exception:
07-12 11:58:38.019: E/AndroidRuntime(3233): FATAL EXCEPTION: main
07-12 11:58:38.019: E/AndroidRuntime(3233): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.moveinblue.planner/com.moveinblue.planner.controller.plan.PlanDayScreen}: java.lang.NullPointerException
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1993)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.ActivityThread.access$600(ActivityThread.java:132)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.os.Handler.dispatchMessage(Handler.java:99)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.os.Looper.loop(Looper.java:137)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.ActivityThread.main(ActivityThread.java:4575)
07-12 11:58:38.019: E/AndroidRuntime(3233): at java.lang.reflect.Method.invokeNative(Native Method)
07-12 11:58:38.019: E/AndroidRuntime(3233): at java.lang.reflect.Method.invoke(Method.java:511)
07-12 11:58:38.019: E/AndroidRuntime(3233): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
07-12 11:58:38.019: E/AndroidRuntime(3233): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
07-12 11:58:38.019: E/AndroidRuntime(3233): at dalvik.system.NativeStart.main(Native Method)
07-12 11:58:38.019: E/AndroidRuntime(3233): Caused by: java.lang.NullPointerException
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
07-12 11:58:38.019: E/AndroidRuntime(3233): at com.moveinblue.planner.controller.plan.PlanDayScreen$4.<init>(PlanDayScreen.java:408)
07-12 11:58:38.019: E/AndroidRuntime(3233): at com.moveinblue.planner.controller.plan.PlanDayScreen.<init>(PlanDayScreen.java:406)
07-12 11:58:38.019: E/AndroidRuntime(3233): at java.lang.Class.newInstanceImpl(Native Method)
07-12 11:58:38.019: E/AndroidRuntime(3233): at java.lang.Class.newInstance(Class.java:1319)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
07-12 11:58:38.019: E/AndroidRuntime(3233): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1984)
07-12 11:58:38.019: E/AndroidRuntime(3233): ... 11 more
Can anybody give me some hindsight here? I'm totally lost.
Code in the activity:
package com.moveinblue.planner.controller.plan;
import java.text.SimpleDateFormat;
import java.util.BitSet;
import java.util.Calendar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.moveinblue.api.Login;
import com.moveinblue.api.Planner;
import com.moveinblue.api.UnauthorizedException;
import com.moveinblue.api.io.InvalidURLException;
import com.moveinblue.api.io.OfflineException;
import com.moveinblue.api.model.ModelObject;
import com.moveinblue.api.model.Plan;
import com.moveinblue.api.model.time.Day;
import com.moveinblue.api.model.time.ScheduledThingToDo;
import com.moveinblue.api.model.time.ScheduledTime;
import com.moveinblue.api.model.time.ScheduledTime.TimeOfDay;
import com.moveinblue.planner.R;
import com.moveinblue.planner.controller.GenericPlannerScreen;
import com.moveinblue.planner.controller.thingtodo.ThingsToDoListScreen;
import com.moveinblue.planner.controller.user.LoginScreen;
import com.moveinblue.planner.ui.actionbar.ActionBar;
import com.moveinblue.planner.ui.draganddroplist.DragListener;
import com.moveinblue.planner.ui.draganddroplist.DragNDropListView;
import com.moveinblue.planner.ui.draganddroplist.DropListener;
import com.moveinblue.planner.ui.draganddroplist.RemoveListener;
import com.moveinblue.planner.utils.CommonActionStorage;
import com.moveinblue.planner.utils.CurrentItemsStorage;
import com.moveinblue.planner.utils.adapter.DragNDropAdapter;
import com.moveinblue.planner.utils.adapter.listeners.OnCheckListener;
public class PlanDayScreen extends GenericPlannerScreen {
DragNDropListView lista;
AutoCompleteTextView actv;
String[] dests;
DragNDropAdapter adapter;
private Boolean idDroppedOrDeleted = false;
private BitSet checkedBoxes = new BitSet();
private boolean firstLoad = true;
Day day;
@SuppressWarnings("unused")
private static final String LOG_TAG = PlanDayScreen.class
.getCanonicalName();
@Override
public void load() {
setContentView(R.layout.plan_day_list);
setUpList();
setUpBottomLayout(false);
lista.requestFocus();
}
@Override
protected void loadActionBar() {
Plan p = CurrentItemsStorage.currentPlan;
Calendar c = CurrentItemsStorage.currentDay;
ab = new ActionBar(this, ActionBar.TYPE_LIST);
String date = new SimpleDateFormat("MMM dd, yyyy").format(c.getTime());
date = Character.toUpperCase(date.charAt(0)) + date.substring(1);
date = "(" + date + ")";
String title;
title = (p != null) ? p.name + " " + date : "Draft plan";
ab.setTitle(title);
ab.setBackAction(R.drawable.back, new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(PlanDayScreen.this,
PlanTabsScreen.class);
intent.putExtra("tab", 2);
startActivity(intent);
overridePendingTransition(android.R.anim.slide_in_left,
android.R.anim.fade_out);
}
});
CommonActionStorage.setUpActionBar(ab);
}
private void addNewTTD() {
if (getIntent().getBooleanExtra("schedule", false) && firstLoad) {
try {
Calendar c = CurrentItemsStorage.currentDay;
TimeOfDay tod = CurrentItemsStorage.currentTimeOfDaySelectedOption;
Planner.schedule(
CurrentItemsStorage.getCurrentThingToDo().ttdId,
new ScheduledTime(c, tod));
} catch (Exception ex) {
ex.getStackTrace();
}
}
firstLoad = false;
}
/**
* Sets up a bottom bar button
*
* @param id
* The bottom bar button id you want to set
*/
private void setUpBottomButton(int id) {
ImageButton b = (ImageButton) findViewById(id);
switch (id) {
case R.id.buttonBottom1:
if (!areThereCheckedBoxes()) {
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Add TTD to plan
Intent intent = new Intent(PlanDayScreen.this,
ThingsToDoListScreen.class);
startActivity(intent);
}
});
} else {
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Date
}
});
}
break;
case R.id.buttonBottom2:
if (!areThereCheckedBoxes()) {
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Map
if (day != null) {
CurrentItemsStorage.mapModelObjects = new ModelObject[0];
CurrentItemsStorage.mapModelObjects[1] = day;
Intent intent = new Intent(PlanDayScreen.this,
PlanTabsScreen.class);
startActivity(intent);
}
}
});
} else {
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Confirm
new AlertDialog.Builder(PlanDayScreen.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(
"Remove " + checkedCount()
+ " things to do")
.setMessage(
"Do you really wish to remove "
+ checkedCount()
+ " things to do from your plan?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
// Remove
for (int i = 0; i < lista
.getCount(); i++) {
if (checkedBoxes.get(i)) {
// Get checked item
Object ttd = adapter
.getItem(i);
if (ttd instanceof ScheduledThingToDo) {
try {
// Remove it
ScheduledThingToDo tTD = (ScheduledThingToDo) ttd;
Planner.unschedule(
tTD.ttdId,
tTD.time);
} catch (OfflineException ex) {
Toast.makeText(
PlanDayScreen.this,
getResources()
.getString(
R.string.unschedule_error),
Toast.LENGTH_SHORT)
.show();
} catch (InvalidURLException e) {
}
}
}
}
// Reset checkedBoxes and
// BottomLayout
checkedBoxes = new BitSet();
setUpBottomLayout(false);
// Redraws the list
setUpList();
}
}).setNegativeButton("No", null).show();
}
});
}
break;
case R.id.buttonBottom3:
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Update
}
});
break;
}
}
/**
* Sets up the list
*/
private void setUpList() {
lista = (DragNDropListView) findViewById(R.id.listViewAgenda);
new LoadList();
}
/**
* Counts the number of checked boxes
*
* @return the number of checked boxes
*/
private int checkedCount() {
int x = 0;
for (int i = 0; i < checkedBoxes.length(); i++) {
x += checkedBoxes.get(i) ? 1 : 0;
}
return x;
}
/**
* Changes the buttoms on the bottom action bar. If you pass true, you get
* the "delete items" action bar. Else, you get the "add items" action bar.
*
* @param isAnythingMarked
* True if you want to delete items, false if you want to add
* them.
*/
private void setUpBottomLayout(boolean isAnythingMarked) {
ImageButton b1 = (ImageButton) findViewById(R.id.buttonBottom1);
ImageButton b2 = (ImageButton) findViewById(R.id.buttonBottom2);
ImageButton b3 = (ImageButton) findViewById(R.id.buttonBottom3);
b1.setImageDrawable(getResources().getDrawable(
isAnythingMarked ? R.drawable.action_plans
: R.drawable.action_add));
b2.setImageDrawable(getResources().getDrawable(
isAnythingMarked ? R.drawable.action_delete
: R.drawable.action_map));
b3.setImageDrawable(getResources()
.getDrawable(R.drawable.action_reload));
setUpBottomButton(R.id.buttonBottom1);
setUpBottomButton(R.id.buttonBottom2);
setUpBottomButton(R.id.buttonBottom3);
}
private boolean areThereCheckedBoxes() {
for (int i = 0; i < checkedBoxes.length(); i++) {
if (checkedBoxes.get(i)) {
return true;
}
}
return false;
}
public void clickControlRowHandler(View v) {
Intent intent = new Intent(PlanDayScreen.this,
ThingsToDoListScreen.class);
startActivity(intent);
}
/**
* Drop Listener for the DragNDropListView
*/
private DropListener mDropListener = new DropListener() {
public void onDrop(final int from, int to) {
if (to == 0)
to = 1;
// If initial position is the same as final position, do nothing.
if (to != from) {
if (adapter instanceof DragNDropAdapter) {
if (adapter.getItem(from) instanceof ScheduledThingToDo) {
new DropCall(from, to);
((DragNDropAdapter) adapter).onDrop(from, to);
}
}
}
}
};
public OnClickListener onClickSave = new OnClickListener() {
public void onClick(View v) {
try {
if (Login.isRegistered()) {
if (Planner.loadPlan().name == null) {
CurrentItemsStorage.shallGoAfterCreatePlan = PlanDayScreen.class;
if (idDroppedOrDeleted) {
manageListChanges();
}
Intent intent = new Intent(PlanDayScreen.this,
SavePlanScreen.class);
startActivity(intent);
return;
}
} else {
CurrentItemsStorage.currentPlan = Planner.loadPlan();
CurrentItemsStorage.shallGoAfterLogin = PlanDayScreen.class;
Intent intent = new Intent(PlanDayScreen.this,
LoginScreen.class);
startActivity(intent);
}
} catch (OfflineException e) {
Toast.makeText(PlanDayScreen.this,
getResources().getString(R.string.plan_error),
Toast.LENGTH_SHORT).show();
}
if (idDroppedOrDeleted) {
manageListChanges();
}
}
};
/**
* Unschedules every TTD, then schedules it again.
*/
private void manageListChanges() {
for (int i = 0; i < adapter.getCount(); i++) {
Object item = adapter.getItem(i);
if (item instanceof ScheduledThingToDo) {
try {
ScheduledThingToDo scheduled = (ScheduledThingToDo) item;
Planner.unschedule(scheduled.getId(), scheduled.time);
} catch (Exception e) {
e.printStackTrace();
}
}
}
int state = 0;
for (int it = 0; it < adapter.getCount(); it++) {
Object item = adapter.getItem(it);
TimeOfDay tod = TimeOfDay.morning;
if (item instanceof ScheduledThingToDo) {
switch (state) {
case 1:
tod = TimeOfDay.morning;
break;
case 2:
tod = TimeOfDay.afternoon;
break;
case 3:
tod = TimeOfDay.evening;
break;
}
try {
Planner.schedule(((ScheduledThingToDo) item).ttdId,
new ScheduledTime(CurrentItemsStorage.currentDay,
tod));
} catch (OfflineException e) {
Toast.makeText(PlanDayScreen.this, "No connection",
Toast.LENGTH_SHORT).show();
}
} else {
state++;
}
}
}
/**
* RemoveListener for the DragNDropListView
*/
private RemoveListener mRemoveListener = new RemoveListener() {
public void onRemove(int which) {
// ListAdapter adapter = getListAdapter();
if (adapter instanceof DragNDropAdapter) {
((DragNDropAdapter) adapter).onRemove(which);
lista.invalidateViews();
}
}
};
/**
* DragListener for the DragNDropListView
*/
private DragListener mDragListener = new DragListener() {
int backgroundColor = getResources().getColor(R.color.yellow);
int defaultBackgroundColor = getResources().getColor(R.color.blue_bg);
public void onDrag(int x, int y, ListView listView) {
// TODO Auto-generated method stub
}
public void onStartDrag(View itemView) {
itemView.setVisibility(View.INVISIBLE);
itemView.setBackgroundColor(backgroundColor);
ImageView iv = (ImageView) itemView.findViewById(R.id.imageView1);
if (iv != null)
iv.setVisibility(View.INVISIBLE);
}
public void onStopDrag(View itemView) {
itemView.setVisibility(View.VISIBLE);
itemView.setBackgroundColor(defaultBackgroundColor);
ImageView iv = (ImageView) itemView.findViewById(R.id.imageView1);
if (iv != null)
iv.setVisibility(View.VISIBLE);
}
};
private class LoadList extends AsyncTask<Void, Void, Void> {
public LoadList() {
execute();
}
@Override
protected void onPreExecute() {
String[] x = { "Loading..." };
addNewTTD();
ArrayAdapter<String> asdf = new ArrayAdapter<String>(
PlanDayScreen.this, R.layout.add_more, x);
lista.setAdapter(asdf);
}
@Override
protected Void doInBackground(Void... arg0) {
ScheduledThingToDo[] ttds;
try {
try {
// Loads current day
day = Planner.loadDay(CurrentItemsStorage.currentDay);
ttds = day.ttds;
} catch (NullPointerException ex) {
// No current day: Loads today
Day day = Planner.loadDay(Calendar.getInstance());
ttds = day.ttds;
}
} catch (OfflineException e) {
// Offline
Toast.makeText(PlanDayScreen.this,
getResources().getString(R.string.day_error),
Toast.LENGTH_SHORT).show();
ttds = new ScheduledThingToDo[0];
} catch (UnauthorizedException e) {
// Something strange happened
ttds = new ScheduledThingToDo[0];
} catch (Exception e) {
// Something even more strange happened
ttds = new ScheduledThingToDo[0];
}
adapter = new DragNDropAdapter(PlanDayScreen.this,
new int[] { R.layout.dragitemttd }, ttds);
adapter.setOnCheckListener(new OnCheckListener() {
@Override
public void onCheck(boolean isChecked, int position) {
checkedBoxes.set(position, isChecked);
setUpBottomLayout(areThereCheckedBoxes());
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
lista.setAdapter(adapter);
lista.setDropListener(mDropListener);
lista.setRemoveListener(mRemoveListener);
lista.setDragListener(mDragListener);
}
}
private class DropCall extends AsyncTask<Void, Void, Void> {
private int from, to;
public DropCall(int from, int to) {
this.from = from;
this.to = to;
execute();
lista.invalidateViews();
}
@Override
protected Void doInBackground(Void... arg0) {
changeScheduledTTD(from, to);
return null;
}
/**
* Unschedules a TTD and then re-schedules it in its proper place
*
* @param from
* The position the TTD came from
* @param to
* The position the TTD has been dragged to
*/
protected void changeScheduledTTD(int from, int to) {
ScheduledThingToDo currentTTD;
if (adapter.getItem(to) instanceof ScheduledThingToDo)
currentTTD = (ScheduledThingToDo) adapter.getItem(to);
else
return;
int indexMorning = 0;
int indexAfternoon = 0;
int indexEvening = 0;
Object item = null;
String currentTime = null;
// Gets the indexes for Morning, Afternoon and Evening
for (int i = 0; i < adapter.getCount(); i++) {
item = adapter.getItem(i);
if (item instanceof String) {
currentTime = (String) item;
if (currentTime.equals("MORNING")) {
indexMorning = i;
}
if (currentTime.equals("AFTERNOON")) {
indexAfternoon = i;
}
if (currentTime.equals("EVENING")) {
indexEvening = i;
}
}
}
TimeOfDay tod = null;
if (to >= indexEvening) {
tod = TimeOfDay.evening;
} else if (to >= indexAfternoon) {
tod = TimeOfDay.afternoon;
} else if (to >= indexMorning) {
tod = TimeOfDay.morning;
}
if (!currentTTD.time.getTimeOfDay().equals(tod)) {
try {
Planner.unschedule(currentTTD.ttdId, currentTTD.time);
Planner.schedule(currentTTD.ttdId, new ScheduledTime(
CurrentItemsStorage.currentDay, tod));
} catch (OfflineException e) {
e.printStackTrace();
}
}
}
}
}
解决方案
Your mDragListener
is a member variable. At the point of initializing the Activity object/instance might not be ready. So calling getResource()
of the Activity will fail.
// inner class or normal class ... change scope if needed
private class DragListener {
int color = 0;
public DragListener(Context context) {
color = context.getResource().getColor(R.color.yellow);
}
}
// activity
private DragListener mDragListener;
public void onCreate(...) {
mDragListener = new DragListener(this);
// more code
}
这篇关于NullPointerException异常的android.content.ContextWrapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文