当我按下返回按钮时,应用程序崩溃

时间:2014-10-07 18:14:27

标签: java android eclipse android-intent nullpointerexception

我是Android编程的新手。我有一个带有一些活动的应用程序和一个SplashActivity,这是一个开始。类似的问题已经被提出,但没有一个答案对我有帮助,例如在我的finish()中添加EinkaufsListe-Activity功能,甚至添加此方法

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
         Intent intent = new Intent(this, MainActivity.class); 
            startActivity(intent);
            super.onStop();
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

添加super.onStop().没有! 我的应用程序包含一些Activities和一个SplashActivity,这是一个起始版本。 当我在ShopList-Activity并按下"后退按钮"应用程序崩溃并说:

     0-07 13:37:56.250: E/AndroidRuntime(1124): java.lang.RuntimeException: Unable to     stop activity {de.abayev.theapp/de.abayev.theapp.EinkaufsListe}:      java.lang.NullPointerException
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3188)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3234)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.ActivityThread.access$1100(ActivityThread.java:135)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1223)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.os.Looper.loop(Looper.java:136)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.ActivityThread.main(ActivityThread.java:5017)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at java.lang.reflect.Method.invokeNative(Native Method)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at java.lang.reflect.Method.invoke(Method.java:515)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at dalvik.system.NativeStart.main(Native Method)
10-07 13:37:56.250: E/AndroidRuntime(1124): Caused by: java.lang.NullPointerException
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.Activity.performStop(Activity.java:5388)
10-07 13:37:56.250: E/AndroidRuntime(1124):     at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3185)
10-07 13:37:56.250: E/AndroidRuntime(1124):     ... 11 more

这是我的清单:

     <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>


            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:name=".SplashActivity">
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
     <activity
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:name=".EinkaufsListe">
        <intent-filter >

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MHD_Liste">
        <intent-filter >
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

     <service android:name=".MyAlarmService"
             android:enabled="true" />

    <receiver android:name=".MyReceiver"/>

</application>

我真的像天一样搜索,没有任何帮助。 如果您需要更多代码,请告诉我。

修改 这是来自EinkaufsListe的OnCreate

    protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.einkaufsliste);

    openDB();           
    eddit1 = (EditText) findViewById (R.id.edittxt1);
    eddit1.setOnKeyListener(OnKey);

    LV = (ListView) findViewById (R.id.liVi1);
    registerForContextMenu(LV);

    startManagingCursor(cursor_main);
    update_list();

    LV.setAdapter(cur_adapter);

    Intent myIntent = new Intent(EinkaufsListe.this, MyReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(EinkaufsListe.this, 0, myIntent,0);

}   // OnCreate

编辑2:

好的我不知道哪些代码更相关,所以我只是发布了整个课程的其余部分:

// Methode für das Eingabefeld mit übergabe an DB   
    public OnKeyListener OnKey = new OnKeyListener ()       
    {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
            {
String writtenText = eddit1.getText().toString();

                if( writtenText.indexOf(",") != -1 )
                {
                    String a;
                    String b;

                    a = writtenText.substring( 0, writtenText.indexOf(",") );
                    b = writtenText.substring( writtenText.indexOf(",")+1, writtenText.length() ); // writtenText.indexOf(",")+1 um Abschnitt nach dem Komma zu beginnen                

                    myDb.insertRow(a,b,null,EinkaufTabelle);    //neue Zeile in DB anfügen
                    eddit1.setText("");
                    update_list();
                }
                else
                {
                    myDb.insertRow(writtenText," ohne Produktart ",null,EinkaufTabelle);    //neue Zeile in DB anfügen
                    eddit1.setText("");
                    update_list();
                }
            }
            return false;
        }   // OnKey

    };  // OnKeyListener
////////////////////////////////////////////__Datenbank-Methoden__/////////////////////////////////////////
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null != myDb)
        closeDB();
    }

    private void openDB() {
        myDb = new DBAdapter(this);
        myDb.open();
    }

    private void closeDB() {
        myDb.close();
    }

    public DBAdapter getDB()
    {
        DBAdapter angefragte_DB = myDb;
        return angefragte_DB;
    }

/////////////////////////////////////////////__ListView Methoden__///////////////////////////////////////// 
public void onToggleClicked(View view)  
{
    boolean on = ((ToggleButton) view).isChecked();
    if (on) 
    { checked = true; update_list(); }
    else 
    { checked = false; update_list(); }
} // onToggleClicked, nach dem Beispiel von developer.Android.com

protected void update_list()
{
    if (checked == true)
         cursor_main = myDb.orderRows(EinkaufTabelle); 
    else
        cursor_main = myDb.getAllRows(EinkaufTabelle);
    //startManagingCursor(cursor);

     final String[] anzeigeSpalten = new String[]{ "name", "productType"};
    final   int[] anzeigeViews      = new int[] { R.id.dataLV_tv, R.id.dataLV_tv2 };
        cur_adapter             = new SimpleCursorAdapter(this, R.layout.datensaetze_listview, cursor_main, anzeigeSpalten, anzeigeViews);

        LV.setAdapter(cur_adapter);
}   // update_list

//Contextmenu anlegen
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
    MenuInflater inflater = getMenuInflater();  

    inflater.inflate(R.menu.context_menu, menu);

};  // OnCreateContextMenu

//
public boolean onContextItemSelected(MenuItem item)
{
    AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
    int rowId;

    cursor_main = cur_adapter.getCursor();
    cursor_main.moveToPosition(menuInfo.position);
    rowId = cursor_main.getInt(cursor_main.getColumnIndex("_id"));
    itemId = cursor_main.getInt(cursor_main.getColumnIndex("_id"));

    switch (item.getItemId())
    {
            case R.id.loeschen  : myDb.deleteRow(rowId, EinkaufTabelle); break;

            case R.id.mhd       : showDialog(MHD_DIALOG);
                                  break;

            default:    break;      
    }   
    update_list();
    return true;
}  // onContextItemSelected

/////////////////////////////////////////////__Dialog Methoden__/////////////////////////////////////////   
protected Dialog onCreateDialog(int num)
{       Dialog rückgabe = null;

        switch(num)
        {
          case MHD_DIALOG:  rückgabe = zeigeMHDDialog();
                            break;

          default        :  break;
        }

    return rückgabe;
}   // onCreateDialog

private DatePickerDialog zeigeMHDDialog() 
{   

    final DatePickerDialog.OnDateSetListener datelistener;
    datelistener = new DatePickerDialog.OnDateSetListener() {
                       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)    // wird wegen des CallBack Meachanismus erst beim Schließen, 
                       {                                                                                    // des DatePickerDialogs aufgerufen
                           int Tag = dayOfMonth;
                           int Monat = monthOfYear;
                           int Jahr = year;
                           String ablaufsDat;

                           //switch-Anweisung falls Tag < 7 muss Benutzter trotzdem richtig gewarnt werden
                           switch(dayOfMonth)
                           {
                           case 7:  Tag = 30; Monat = monthOfYear - 1;  break;
                           case 6:  Tag = 29; Monat = monthOfYear - 1;  break;
                           case 5:  Tag = 28; Monat = monthOfYear - 1;  break;
                           case 4:  Tag = 27; Monat = monthOfYear - 1;  break;
                           case 3:  Tag = 26; Monat = monthOfYear - 1;  break;
                           case 2:  Tag = 25; Monat = monthOfYear - 1;  break;
                           case 1:  Tag = 24; Monat = monthOfYear - 1;  break;
                           default: Tag = dayOfMonth - 7; Monat = monthOfYear; Jahr = year; break;
                           }

                           if(monthOfYear == 0)     // per Definition gehen die Monate im PC von 0 - 11
                           {
                               switch(dayOfMonth)
                               {
                               case 7:  Tag = 30; Monat = 11; Jahr = year - 1;  break;
                               case 6:  Tag = 29; Monat = 11; Jahr = year - 1;  break;
                               case 5:  Tag = 28; Monat = 11; Jahr = year - 1;  break;
                               case 4:  Tag = 27; Monat = 11; Jahr = year - 1;  break;
                               case 3:  Tag = 26; Monat = 11; Jahr = year - 1;  break;
                               case 2:  Tag = 25; Monat = 11; Jahr = year - 1;  break;
                               case 1:  Tag = 24; Monat = 11; Jahr = year - 1;  break;
                               default: Tag = dayOfMonth - 7; Monat = monthOfYear; Jahr = year; break;
                               }
                           }


                           String name = cursor_main.getString(cursor_main.getColumnIndex("name"));
                           String productType = cursor_main.getString(cursor_main.getColumnIndex("productType"));

                           neuesDat = Tag + "." + (Monat +1) + "." + Jahr ;
                           ablaufsDat = dayOfMonth + "." + (monthOfYear +1) + "." + year ;

                           myDb.updateRowDate(itemId, ablaufsDat);
                           myDb.insertRow(name, productType, ablaufsDat, MHD_Tabelle);  // in die MHD Tabelle einfügen

                           Toast.makeText(getApplicationContext(), "Mindesthaltbarkeitsdatum wurde eingestellt. Sie können es in der Liste für die aufzubewahrenden Produkte einsehen", Toast.LENGTH_LONG).show(); 

                           Calendar calendar = Calendar.getInstance();
                             calendar.set(Calendar.YEAR, Jahr);
                             calendar.set(Calendar.MONTH, Monat);
                             calendar.set(Calendar.DAY_OF_MONTH, Tag); 

                             AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                           alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
                       }    //onDateSet
                       };   //datelistener

    // Dialog erzeugen und Datum auf heute setzen
    Calendar c = Calendar.getInstance();
    int J   = c.get(Calendar.YEAR);
    int M  = c.get(Calendar.MONTH);
    int T    = c.get(Calendar.DAY_OF_MONTH); 

    DatePickerDialog dialog = new DatePickerDialog (this, datelistener, J, M, T);   
    return dialog; 
}

// methode für den back Button
@Override
public void onBackPressed() {

    Intent intent_x = new Intent(this, MainActivity.class); 
    startActivity(intent_x);
    finish();
 }


}   // end of class 

这里是清洁后的痕迹:

10-07 15:00:24.100: E/AndroidRuntime(1435): FATAL EXCEPTION: main
10-07 15:00:24.100: E/AndroidRuntime(1435): Process: de.abayev.theshapp, PID: 1435
10-07 15:00:24.100: E/AndroidRuntime(1435): java.lang.RuntimeException: Unable to stop activity {de.abayev.theshapp/de.abayev.theshapp.EinkaufsListe}: java.lang.NullPointerException
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3461)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3515)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.ActivityThread.access$1400(ActivityThread.java:135)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1249)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.os.Looper.loop(Looper.java:136)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.ActivityThread.main(ActivityThread.java:5017)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at java.lang.reflect.Method.invokeNative(Native Method)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at java.lang.reflect.Method.invoke(Method.java:515)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at dalvik.system.NativeStart.main(Native Method)
10-07 15:00:24.100: E/AndroidRuntime(1435): Caused by: java.lang.NullPointerException
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.Activity.performStop(Activity.java:5388)
10-07 15:00:24.100: E/AndroidRuntime(1435):     at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3456)
10-07 15:00:24.100: E/AndroidRuntime(1435):     ... 11 more

3 个答案:

答案 0 :(得分:2)

        super.onStop();
亲爱的领主没有。不要从其他方法手动调用Activity生命周期回调方法。

致电finish()以结束活动。

答案 1 :(得分:0)

使用此代替onKeyDown:

@Override
public void onBackPressed() {

    Intent intent = new Intent(this, MainActivity.class); 
    startActivity(intent);
    finish();
 }

答案 2 :(得分:0)

super.onStop()以外的任何地方致电onStop()是错误的,但不会导致异常。

你的问题

Caused by: java.lang.NullPointerException
  at android.app.Activity.performStop(Activity.java:5388)

是由于您向null Cursor提供了startManagingCursor() onCreate(),特别是startManagingCursor(cursor_main);

cursor_main

其中startManagingCursor()尚未初始化。

完全删除{{1}}。无论如何,你不应该将它用于新代码。