【问题标题】:Actionbar menu button clicked caused app to stop单击操作栏菜单按钮导致应用程序停止
【发布时间】:2015-04-21 11:10:01
【问题描述】:

我对 android 开发完全陌生。我目前正在尝试制作笔记应用程序。操作栏将有 2 个按钮,创建和设置,引导用户创建和设置页面。创建按钮工作得很好,但我不知道为什么每当我运行应用程序并单击设置按钮时,它并没有引导我进入设置页面,应用程序突然停止。

这是我的代码

MainActivity.java

包 com.example.sunny.mynote;

import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.sunny.mynote.com.example.sunny.mynote.data.NoteDataSource;
import com.example.sunny.mynote.com.example.sunny.mynote.data.NoteItem;

import java.util.List;


public class MainActivity extends ListActivity {

    public static final int EDITOR_ACRIVITY_REQUEST = 1001;
    public static final int SETTINGS_REQUEST = 1003;
    private static final int MENU_DELETE_ID = 1002;
    private int currentNoteId;
    private NoteDataSource datasource;
    List<NoteItem> notesList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerForContextMenu(getListView());

        datasource = new NoteDataSource(this);

        refreshDisplay();
    }

    private void refreshDisplay() {
        notesList = datasource.findAll();
        ArrayAdapter<NoteItem> adapter =
                new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
        setListAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_create)
        {
            createNote();
        }
        int id = item.getItemId();
        if (id == R.id.action_create) {
            return true;
        }

        if (item.getItemId() == R.id.action_settings)
        {
            Intent intent2 = new Intent(MainActivity.this, Settings.class);
            startActivity(intent2);
        }
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void createNote()
    {
        NoteItem note = NoteItem.getNew();
        Intent intent = new Intent(this, NoteEditorActivity.class);
        intent.putExtra("key", note.getKey());
        intent.putExtra("text", note.getText());
        startActivityForResult(intent, EDITOR_ACRIVITY_REQUEST);
    }

    private void Settings()
    {

    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        NoteItem note = notesList.get(position);
        Intent intent = new Intent(this, NoteEditorActivity.class);
        intent.putExtra("key", note.getKey());
        intent.putExtra("text", note.getText());
        startActivityForResult(intent, EDITOR_ACRIVITY_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == EDITOR_ACRIVITY_REQUEST && resultCode == RESULT_OK)
        {
            overridePendingTransition(R.anim.fadein, R.anim.fadeout);
            NoteItem note = new NoteItem();
            note.setKey(data.getStringExtra("key"));
            note.setText(data.getStringExtra("text"));
            datasource.update(note);
            refreshDisplay();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        currentNoteId = (int)info.id;
        menu.add(0, MENU_DELETE_ID, 0, "Delete");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        if (item.getItemId() == MENU_DELETE_ID)
        {
            NoteItem note = notesList.get(currentNoteId);
            datasource.remove(note);
            refreshDisplay();
        }

        return super.onContextItemSelected(item);
    }
}

Settings.java

    package com.example.sunny.mynote;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;

/**
 * Created by Sunny on 19/04/2015.
 */
public class Settings extends Activity {

    View view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_note_editor, null);

    private RadioGroup RadioGroup1;
    private RadioButton rdbRed, rdbBlue, rdbOrange;
    private Button btnSave;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        View view = LayoutInflater.from(getApplication()).inflate(R.layout.settings, null);

        RadioGroup1 = (RadioGroup) findViewById(R.id.RadioGroup1);

        RadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.rdbRed)
                {
                    Toast.makeText(getApplicationContext(), "choice: Red",
                            Toast.LENGTH_SHORT).show();
                }
                else if(checkedId == R.id.rdbBlue)
                {
                    Toast.makeText(getApplicationContext(), "choice: Blue",
                            Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "choice: Orange",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        Intent intent = new Intent(this, NoteEditorActivity.class);

        rdbRed = (RadioButton) findViewById(R.id.rdbRed);
        rdbBlue = (RadioButton) findViewById(R.id.rdbBlue);
        rdbOrange = (RadioButton) findViewById(R.id.rdbOrange);
        textView = (TextView) findViewById(R.id.noteText);

        btnSave = (Button)findViewById(R.id.btn_Save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedId = RadioGroup1.getCheckedRadioButtonId();
                if(selectedId == rdbRed.getId()) {
                    textView.setTextColor(Color.parseColor("#FF0000"));
                } else if(selectedId == rdbBlue.getId()) {
                    textView.setTextColor(Color.parseColor("#0066FF"));
                } else {
                    textView.setTextColor(Color.parseColor("#FF6600"));
                }
                finish();
            }

        });
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}

日志

04-21 22:02:11.583  26636-26636/com.example.sunny.mynote I/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file.
04-21 22:02:11.603  26636-26636/com.example.sunny.mynote I/SELinux﹕ Function: selinux_android_load_priority , spota verifySig and checkHash pass. priority version is VE=SEPF_SM-N9005_4.4.2_0040
04-21 22:02:11.603  26636-26636/com.example.sunny.mynote I/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /data/security/spota/seapp_contexts
04-21 22:02:11.603  26636-26636/com.example.sunny.mynote E/dalvikvm﹕ >>>>> Normal User
04-21 22:02:11.603  26636-26636/com.example.sunny.mynote E/dalvikvm﹕ >>>>> com.example.sunny.mynote [ userId:0 | appId:10383 ]
04-21 22:02:11.603  26636-26636/com.example.sunny.mynote D/dalvikvm﹕ Late-enabling CheckJNI
04-21 22:02:11.613  26636-26636/com.example.sunny.mynote I/dalvikvm﹕ Enabling JNI app bug workarounds for target SDK version 7...
04-21 22:02:11.693  26636-26636/com.example.sunny.mynote W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-21 22:02:11.693  26636-26636/com.example.sunny.mynote I/PersonaManager﹕ getPersonaService() name persona_policy
04-21 22:02:11.723  26636-26636/com.example.sunny.mynote E/MoreInfoHPW_ViewGroup﹕ Parent view is not a TextView
04-21 22:02:11.743  26636-26636/com.example.sunny.mynote D/AbsListView﹕ Get MotionRecognitionManager
04-21 22:02:11.763  26636-26636/com.example.sunny.mynote D/AbsListView﹕ onVisibilityChanged() is called, visibility : 4
04-21 22:02:11.763  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:11.763  26636-26636/com.example.sunny.mynote D/AbsListView﹕ onVisibilityChanged() is called, visibility : 0
04-21 22:02:11.763  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:11.773  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:11.793  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:11.793  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:11.823  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:12.868  26636-26636/com.example.sunny.mynote D/AbsListView﹕ Get MotionRecognitionManager
04-21 22:02:12.898  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:12.948  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:12.948  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:12.998  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:12.998  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:13.758  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:13.758  26636-26636/com.example.sunny.mynote D/AbsListView﹕ onDetachedFromWindow
04-21 22:02:13.758  26636-26636/com.example.sunny.mynote D/AbsListView﹕ unregisterIRListener() is called
04-21 22:02:13.758  26636-26636/com.example.sunny.mynote D/AndroidRuntime﹕ Shutting down VM
04-21 22:02:13.758  26636-26636/com.example.sunny.mynote W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x417e0da0)
04-21 22:02:13.768  26636-26636/com.example.sunny.mynote E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.sunny.mynote, PID: 26636
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.sunny.mynote/com.example.sunny.mynote.Settings}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
            at android.app.ActivityThread.access$800(ActivityThread.java:163)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5335)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at android.view.LayoutInflater.from(LayoutInflater.java:212)
            at com.example.sunny.mynote.Settings.<init>(Settings.java:21)
            at java.lang.Class.newInstanceImpl(Native Method)
            at java.lang.Class.newInstance(Class.java:1208)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
            at android.app.ActivityThread.access$800(ActivityThread.java:163)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5335)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
04-21 22:02:15.248  26636-26636/com.example.sunny.mynote I/Process﹕ Sending signal. PID: 26636 S

IG:9

【问题讨论】:

  • 请发布崩溃日志
  • 它是否显示任何错误?日志猫?
  • 需要 logcat 跟踪来显示您的错误。 See this link.
  • 已更新。请检查
  • @LuluHarper 这不是 logcat

标签: android android-studio android-actionbar menubar


【解决方案1】:

尝试在设置中更改此行:

private View view;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings);
    view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_note_editor, null);
}

【讨论】:

  • 再次查看您的 logcat。
  • 一点解释。成员变量在构造函数调用之前被初始化。 LayoutInflater.from(getApplication()) 在构造函数之前调用,getApplication() 返回 null。 getApplication() 方法仅在“附加”活动后返回应用程序对象。所以你应该在onCreate() 做。
  • 你必须仔细检查你的 logcat。从您发布的 logcat 来看,这就是问题所在。现在也许会发生任何其他问题。所以通过你的logcat ..
  • 这是我使用 android studio 的第一天,老实说,当我阅读 logcat 时,我什么都不懂
  • Caused by: java.lang.NullPointerException at android.view.LayoutInflater.from(LayoutInflater.java:212) at com.example.sunny.mynote.Settings.&lt;init&gt;(Settings.java:21) 这取自您的 logcat。这是你的第一个问题。像这样你只需搜索错误。请参阅(Settings.java:21) 这是发生错误的行。
【解决方案2】:

您必须在内部膨胀视图或更改 OnCreate() 的调用 所以在 Settings.java 的 oncreate() 中移动你的行 View view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_note_editor, null);

【讨论】:

  • 我试过了,但是当我点击设置按钮时应用程序仍然崩溃
  • logcat 有什么变化还是一样?还更新您问题中的代码和 logcat
  • 您尚未删除 View view =.. oncreate() 之外的行。删除它...如果您在调用 onCreate() 之前调用 getApplication(),它将返回 null。 . 这就是为什么你得到空指针
  • 现在可以了,我可以进入设置页面。但另一个问题是当我单击设置页面中的保存按钮时,应用程序将崩溃。这是 logcar 04-21 22:09:09.427 29767-29767/com.example.sunny.mynote D/AbsListView 中的错误:unregisterIRListener() 被调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多