我想在我的应用程序中调用alertdialog并收到错误
"12-02 09:40:07.500: E/AndroidRuntime(4693): FATAL EXCEPTION: main
12-02 09:40:07.500: E/AndroidRuntime(4693): java.lang.NullPointerException
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.getVolumeControlStream(Activity.java:3714)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Dialog.setOwnerActivity(Dialog.java:188)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.onPrepareDialog(Activity.java:2494)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.onPrepareDialog(Activity.java:2518)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.showDialog(Activity.java:2568)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.showDialog(Activity.java:2527)
12-02 09:40:07.500: E/AndroidRuntime(4693): at com.example.ok1.ToDoCalendarViewMaker$2.onItemLongClick(ToDoCalendarViewMaker.java:170)"
源代码:
public class ToDoCalendarViewMaker extends SherlockFragmentActivity implements OnItemLongClickListener {
//final String Tag="States";
public ToDoCalendarViewMaker() {
}
public void makeGrid(Context context, View view, final MyCalendar myCalendar) {
final String Tag="States";
Log.d(Tag, "ljokj до сюдого 4");
GridView myGridView;
final Context myContext;
final Context myContext1;
View myView;
myView = view;
myContext = context;
myGridView = (GridView) myView.findViewById(R.id.gridView);
String[] from = { "text", "background" };
int[] to = { R.id.tvDay, R.id.llDay };
ArrayList<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();
myData = (ArrayList<Map<String, Object>>) myCalendar.myData.clone();
SimpleAdapter sAdapter = new SimpleAdapter(myContext,
myData, R.layout.day_layout, from, to);
Log.d(Tag, "до биндера");
sAdapter.setViewBinder(new MyViewBinder());
Log.d(Tag, "после");
myGridView.setAdapter(sAdapter);
myGridView.setNumColumns(7);
myGridView.setVerticalSpacing(5);
myGridView.setHorizontalSpacing(5);
myGridView.setOnTouchListener(new MyGridOnTouchListener());
myGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id){
Log.d(Tag, "сработал onItemClick= "+ MainActivity.MyFlag_onClick);
if (MainActivity.MyFlag_onClick == true) {
Log.d(Tag, "идем в лист задач ");
//*********работа с БД****************
// создаем объект для данных
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(myContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
//*********работа с БД****************
// Toast.makeText(myContext,
// "" + myCalendar.returnDateById(position) + " + " + id,
// Toast.LENGTH_SHORT).show();
String id_for_listtsk=myCalendar.returnDateById(position).toString();
//добавляем строку в БД
cv.put("data_id", myCalendar.returnDateById(position));
// long rowID = db.insert("mytable", null, cv);
Log.d(Tag, "row inserted, ID = ");
Cursor c = db.query("mytable", null, null, null, null, null, null);
// logCursor(c);
dbHelper.close();
Intent intent = new Intent(myContext, ListTsk.class);
Log.d(Tag, "==== "+id_for_listtsk);
intent.putExtra("dat", id_for_listtsk.toString());
intent.putExtra("currentPagerList", "1");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Context myContext1=myContext.getApplicationContext();
myContext.startActivity(intent);
// return false;
//************************
// ToDoCalendarActivity.this.finish();
}
}
private void logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
if (c!=null) {
if (c.moveToFirst()) {
String str;
do {
str="";
for (String cn: c.getColumnNames()) {
str = str.concat(cn + " = " + c.getString(c.getColumnIndex(cn)) + "; ");
}
Log.d(Tag, str);
} while (c.moveToNext());
}
}
}
});
myGridView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Log.d(Tag, "11111111111111");
String id_for_listtsk=myCalendar.returnDateById(position).toString();
/*
* вызываем диалог
*/
int dialogId = 0;
dialogId = DialogFactory.DIALOG_TASKS;
//ToDoCalendarActivity.showDial(dialogId);//showDialog(dialogId);
showDialog(dialogId);
//***
return true;
}});
//sAdapter.notifyDataSetChanged();
}
@Override
protected Dialog onCreateDialog(int id) {
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(dialogButtonedit1, InputMethodManager.SHOW_IMPLICIT);
return DialogFactory.getDialogById(id, ToDoCalendarActivity.context);//this
}
public static Dialog createCustomAlertTasks(final Context context) {
//Dialog dialog2=null;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from( context );
View layout = inflater.inflate(R.layout.customnew, null);
builder.setView(layout);
Dialog dialog2 = builder.setTitle("Введите новый список")
.create();
return dialog2;
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
return false;
}
}
//********************************************************
class MyViewBinder implements SimpleAdapter.ViewBinder {
int p;
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
int i;
switch (view.getId()) {
// LinearLayout
case R.id.llDay:
i = ((Integer) data).intValue();
if (i == -1)
view.setBackgroundResource(R.drawable.another_day);
else if (i == 0)
view.setBackgroundResource(R.drawable.day);
else if (i == 1)
view.setBackgroundResource(R.drawable.weekend);
else if (i == 2)
p=4;//view.setBackgroundResource(R.drawable.today_another_day);
else if (i == 3)
view.setBackgroundResource(R.drawable.today_day);
else if (i == 4)
p=6;//view.setBackgroundResource(R.drawable.today_weekend);
return true;
}
return false;
}
}
class MyGridOnTouchListener implements OnTouchListener{
final String Tag="States";
@Override
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
Log.d(Tag, "сработал онтач.....");
// TODO Auto-generated method stub
MainActivity.MyFlag_onClick=false;
if (paramMotionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Log.d(Tag, "опустил палец");
ToDoCalendarActivity.touchX1 = paramMotionEvent.getX();
Log.d(Tag, "x1="+String.valueOf(ToDoCalendarActivity.touchX1));
ToDoCalendarActivity.touchY1 = paramMotionEvent.getY();
ToDoCalendarActivity.flag = true;
}
if (paramMotionEvent.getAction() == MotionEvent.ACTION_MOVE) {
ToDoCalendarActivity.touchY2 = paramMotionEvent.getY();
}
if (paramMotionEvent.getAction() == MotionEvent.ACTION_UP) {
ToDoCalendarActivity.touchX2 = paramMotionEvent.getX();
Log.d(Tag, "x2="+String.valueOf(ToDoCalendarActivity.touchX2));
Log.d(Tag, "Поднял палец");
if (ToDoCalendarActivity.flag==true &&
Math.abs(ToDoCalendarActivity.touchX2 - ToDoCalendarActivity.touchX1)>
Math.abs(ToDoCalendarActivity.touchY2 - ToDoCalendarActivity.touchY1)){
if (ToDoCalendarActivity.touchX2>ToDoCalendarActivity.touchX1){
if ((ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1)>50) {
ToDoCalendarActivity.prevMonth();
}
else if (((ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1)<10)) {
MainActivity.MyFlag_onClick=true;
}
Log.d(Tag, String.valueOf(ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1));
ToDoCalendarActivity.flag=false;
} else {
Log.d(Tag, String.valueOf(ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2));
if ((ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2)>50) {
ToDoCalendarActivity.nextMonth();
}
else if (((ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2)<10)) {
MainActivity.MyFlag_onClick=true;
}
ToDoCalendarActivity.flag=false;
}
}
// ToDoCalendarActivity.flag = false;
}
Log.d(Tag, "....................");
if (ToDoCalendarActivity.touchX1==ToDoCalendarActivity.touchX2){
Log.d(Tag, "Значения равны");
MainActivity.MyFlag_onClick=true;
}
return false;
}
}
public static Dialog getDialogById(int id, final Context context) {
Dialog dialog = null;
switch (id) {
case DIALOG_ALERT:
//dialog = createAlertDialog(context);
break;
case DIALOG_PROGRESS:
//dialog = createProgressDialog(context);
break;
case DIALOG_INPUT:
// dialog = Lists.createInputAlert(context);
dialog = Lists.createCustomAlertNew(context);
break;
case DIALOG_CUSTOM:
dialog = Lists.createCustomAlert(context);
break;
case DIALOG_TASKS:
dialog = ToDoCalendarViewMaker.createCustomAlertTasks(context);
break;
}
return dialog;
}
}
public class ToDoCalendarActivity extends Activity implements OnClickListener{
private KillReceiver mKillReceiver;
final String Tag="States";
static private View[] views = new View[3];
private static final String PREF_ACCOUNT_NAME = "accountName";
static MyCalendar[] cArray = new MyCalendar[3];
static ViewFlipper vf;
static int currentView;
View mainView;
AlarmManager alarmManager;
int REQUEST_CODE = 11223344;
static ToDoCalendarViewMaker toDoCalendarViewMaker;
static float touchX1,touchX2,touchY1,touchY2;
static boolean flag;
static int bb = 0;
static Context context;
static TextView myTextView;
static final String SOME_ACTION = "com.BAO.OK1.SOME_ACTION";
TextView[] textViewArray = new TextView[7];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
// if (getIntent().getBooleanExtra("finish_cal", true)) {
//
// finish();
// }
// Log.d(Tag, "!!!!!!!!!!!!!!!!!!финализируем календарь"+getIntent().getBooleanExtra("finish_cal", true));
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_layout);
// Log.d(Tag, "ljokj до сюдого");
//кнопки отвечающие за переход по месяцам
Log.d(Tag, "Пытаемся запустить календарь");
View prevButton = findViewById(R.id.prev_button);
prevButton.setOnClickListener(this);
View nextButton = findViewById(R.id.next_button);
nextButton.setOnClickListener(this);
//останавливаем AlarmManager
try {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent_stop_alarm = new Intent(MainActivity.BROADCAST_ACTION);
alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent_stop_alarm, 0));
} catch (Exception e) {
// TODO: handle exception
}
//*******************пытаемся навешать слушатель для закрытия активити
Log.d(Tag, "Пытаемся запустить календарь");
mKillReceiver = new KillReceiver();
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
registerReceiver(mKillReceiver,intentFilter);
Log.d(Tag, "Пытаемся запустить календарь1");
//******************************************************************
vf = (ViewFlipper) findViewById(R.id.flipper);
context = getApplicationContext();
// Log.d(Tag, "ljokj до сюдого 2");
LayoutInflater ltInflater = getLayoutInflater();
for (int i = 0; i<3; i++){
views[i] = ltInflater.inflate(R.layout.grid_layout, null, false);
}
// Log.d(Tag, "ljokj до сюдого 3");
mainView = findViewById(R.id.mainll);
Log.d(Tag, "ljokj до сюдого 3.1");
cArray[0] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю2");
cArray[1] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю3");
cArray[2] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю4");
Resources res = getResources();
MyCalendar.setNamesOfDays(
res.getString(R.string.Mon),
res.getString(R.string.Tue),
res.getString(R.string.Wed),
res.getString(R.string.Thu),
res.getString(R.string.Fri),
res.getString(R.string.Sat),
res.getString(R.string.Sun));
MyCalendar.setNamesOfMonths(
res.getString(R.string.January),
res.getString(R.string.February),
res.getString(R.string.March),
res.getString(R.string.April),
res.getString(R.string.May),
res.getString(R.string.June),
res.getString(R.string.July),
res.getString(R.string.August),
res.getString(R.string.September),
res.getString(R.string.October),
res.getString(R.string.November),
res.getString(R.string.December));
Log.d(Tag, "ljokj до сюдого 4");
cArray[0].setState();
Log.d(Tag, "ljokj до сюдого 4/0");
cArray[1].setState();
cArray[2].setState();
cArray[1].nextMonth();
toDoCalendarViewMaker = new ToDoCalendarViewMaker();
cArray[2].prevMonth();
Log.d(Tag, "ljokj до сюдого 4/1");
toDoCalendarViewMaker.makeGrid(this, views[0], cArray[0]);
Log.d(Tag, "ljokj до сюдого 4/1\1");
toDoCalendarViewMaker.makeGrid(this, views[1], cArray[1]);
Log.d(Tag, "ljokj до сюдого 4/1.2");
toDoCalendarViewMaker.makeGrid(this, views[2], cArray[2]);
Log.d(Tag, "ljokj до сюдого 4/1.3");
Log.d(Tag, "ljokj до сюдого 5");
vf.addView((View) views[0]);
vf.addView((View) views[1]);
vf.addView((View) views[2]);
currentView = 0;
myTextView = (TextView) findViewById(R.id.myText);
textViewArray[0] = (TextView) findViewById(R.id.textData);
textViewArray[1] = (TextView) findViewById(R.id.textView2);
textViewArray[2] = (TextView) findViewById(R.id.textView3);
textViewArray[3] = (TextView) findViewById(R.id.textView4);
textViewArray[4] = (TextView) findViewById(R.id.textView5);
textViewArray[5] = (TextView) findViewById(R.id.textView6);
textViewArray[6] = (TextView) findViewById(R.id.textView7);
// рисуем названия дней недели
Log.d(Tag, "ljokj до сюдого 6");
int j = MyCalendar.beforeFirstDay;
for (int i = 0; i < 7; i++) {
if (j == 7) {
j = 0;
}
textViewArray[i].setText(MyCalendar.namesOfDays[j]);
j++;
}
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
@Override
public void onClick(View v) {
Log.d(Tag, "onClick");
switch (v.getId()) {
case R.id.prev_button:
prevMonth();
break;
case R.id.next_button:
nextMonth();
break;
}
}
//****
public static void nextMonth(){
vf.setInAnimation(AnimationUtils.loadAnimation(context,R.anim.next_appear));
vf.setOutAnimation(AnimationUtils.loadAnimation(context,R.anim.next_disappear));
vf.showNext();
int prevView = currentView - 1;
if (prevView == -1) prevView = 2;
currentView++;
if (currentView == 3) currentView = 0;
cArray[prevView].nextMonth();
cArray[prevView].nextMonth();
cArray[prevView].nextMonth();
toDoCalendarViewMaker.makeGrid(context, views[prevView], cArray[prevView]);
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
public static void prevMonth(){
// Log.d(Tag, "предыдущий месяц");
vf.setInAnimation(AnimationUtils.loadAnimation(context,R.anim.next_appear_1));
vf.setOutAnimation(AnimationUtils.loadAnimation(context,R.anim.next_disappear_1));
vf.showPrevious();
int nextView = currentView + 1;
if (nextView == 3) nextView = 0;
currentView--;
if (currentView == -1) currentView = 2;
cArray[nextView].prevMonth();
cArray[nextView].prevMonth();
cArray[nextView].prevMonth();
toDoCalendarViewMaker.makeGrid(context, views[nextView], cArray[nextView]);
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.d(Tag, "onTouchEvent ToDoCalendarActivity");
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touchX1 = event.getX();
Log.d(Tag, "x1="+String.valueOf(touchX1));
touchY1 = event.getY();
flag = true;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
touchX2 = event.getX();
Log.d(Tag, "x2="+String.valueOf(touchX2));
touchY2 = event.getY();
if (flag==true && Math.abs(touchX2 - touchX1)>Math.abs(touchY2 - touchY1)){
if (touchX2>touchX1) {
Log.d(Tag, String.valueOf(touchX2-touchX1));
prevMonth();flag=false;
} else {
Log.d(Tag, String.valueOf(touchX1-touchX2));
nextMonth();flag=false;
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
flag = false;
}
return super.onTouchEvent(event);
}
//*****
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "Today");
// menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Exit");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
ListTsk.id_for_listtsk=null;
onDestroy();
break;
// case 2:
//
// break;
case 3:
//this.onDestroy();
Intent myintent = new Intent(this, MainActivity.class);
myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myintent.putExtra("finish", true);
startActivity(myintent);
onDestroy();
// break;
}
return super.onOptionsItemSelected(item);
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
try {
//******************************пробуем засунуть сюда настройки
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
String nastrPreferences = settings.getString(PREF_ACCOUNT_NAME, null);
//*******************************
startService(new Intent(this, ServiceUpdate.class).putExtra("preferences", nastrPreferences));
Log.d(Tag, "запустили службу ServiceUpdate");
} catch (Exception e) {
// TODO: handle exception
}
Log.d(Tag, "todocalendarActivity: onDestroy()");
finish();
// db.close();
}
@Override
protected void onStop() {
super.onStop();
Log.d(Tag, "todocalendarActivity: onStop()");
// finish();
}
@Override
protected void onPause() {
super.onPause();
//this.dbHelper.close();
Log.d(Tag, "todocalendarActivity: onPause()");
}
public static void showDial(int num) {
//Toast.makeText(context, "hello", 1000).show();
bb++;
// showDialog(num);
}
@Override
public void onBackPressed() {
// Log.d(Tag, "Была нажата кнопка возврат");
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(100);
return;
}
private final class KillReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
}
可能是我在raw“return DialogFactory.getDialogById(id,ToDoCalendarActivity.context)”中有错误?可能是我必须使用其他背景?请帮帮我