待应用程序崩溃

时间:2016-02-12 15:11:23

标签: java android xml android-studio

我正在尝试在Android工作室制作待办事项应用程序。但是只要我点击添加按钮(右上角的+),应用程序就会崩溃。我是java和android工作室的新手,但我认为问题可能在于“saveListInfo()”,但我无法弄清楚如何修复它......

EditedActivity.java的代码:

public class EditedActivity extends AppCompatActivity {

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

        String name;
        name = getIntent().getStringExtra("theName");

        EditText editList = (EditText) findViewById(R.id.editText);
        editList.setText(name);
    }


    private void saveListInfo() {
        EditText editList = (EditText) findViewById(R.id.editText);
        String name = editList.getText().toString();

        Bundle listBundle = new Bundle();
        listBundle.putString("name", name);

        Intent finalIntent = new Intent(this, MainActivity.class);
        finalIntent.putExtras(listBundle);

        setResult(RESULT_OK, finalIntent);

    }

    Button addBtn = (Button) findViewById(R.id.add_btn);

    {
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveListInfo();
            }
        });
    }
}

MainActivity.java中的代码:

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_task:
                saveTodoInfo();

        }

        return true;
    }

    private void saveTodoInfo(){
        TextView nameView = (TextView) findViewById(R.id.action_add_task);
        String name = nameView.getText().toString();

        Intent myIntent = new Intent(this, EditedActivity.class);
        myIntent.putExtra("theName", name);

        startActivityForResult(myIntent, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0){
            if(resultCode == RESULT_OK){
                Bundle ListBundle = data.getExtras();
                String name = ListBundle.getString("theName");

                updateToDo(name);
            }
        }

    }

    private void updateToDo(String name){
        TextView nameView = (TextView) findViewById(R.id.action_add_task);
        nameView.setText(name);
    }


}

这是我点击添加按钮时出现的错误:

  

02-12 16:07:40.553 1410-1410 / com.carpe_diem.anitas_todolist   E / AndroidRuntime:致命异常:主要                                                                                 处理:com.carpe_diem.anitas_todolist,PID:1410                                                                                 java.lang.RuntimeException:无法实例化活动   ComponentInfo {com.carpe_diem.anitas_todolist / com.carpe_diem.anitas_todolist.EditedActivity}:   java.lang.NullPointerException:尝试调用虚方法   'android.view.View android.view.Window.findViewById(int)'在null上   对象参考                                                                                     在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)                                                                                     在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)                                                                                     在android.app.ActivityThread.-wrap11(ActivityThread.java)                                                                                     在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)                                                                                     在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                     在android.os.Looper.loop(Looper.java:148)                                                                                     在android.app.ActivityThread.main(ActivityThread.java:5417)                                                                                     at java.lang.reflect.Method.invoke(Native Method)                                                                                     在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)                                                                                     在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)                                                                                  引起:java.lang.NullPointerException:尝试调用虚拟   方法'android.view.View android.view.Window.findViewById(int)'上的一个   null对象引用                                                                                     在android.app.Activity.findViewById(Activity.java:2090)                                                                                     在   com.carpe_diem.anitas_todolist.EditedActivity。(EditedActivity.java:40)                                                                                     at java.lang.Class.newInstance(Native Method)                                                                                     在android.app.Instrumentation.newActivity(Instrumentation.java:1067)                                                                                     在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)                                                                                     在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)                                                                                     在android.app.ActivityThread.-wrap11(ActivityThread.java)                                                                                     在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)                                                                                     在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                     在android.os.Looper.loop(Looper.java:148)                                                                                     在android.app.ActivityThread.main(ActivityThread.java:5417)                                                                                     at java.lang.reflect.Method.invoke(Native Method)                                                                                     在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)                                                                                     在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:1)

删除此代码周围的括号

{
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveListInfo();
        }
    });
}

应该是这样的

Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        saveListInfo();
    }
});

如果您想知道崩溃发生的原因,可以阅读有关What is an initialization block?

的更多信息

答案 1 :(得分:1)

通过日志,我们可以看到您崩溃发生在以下行:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference  at
android.app.Activity.findViewById(Activity.java:2090)  at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
...

检查完代码后,我可以在第40行(EditedActivity.java:40)中找到以下代码不在任何方法或函数之内。

Button addBtn = (Button) findViewById(R.id.add_btn);
{
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveListInfo();
        }
    });
}

因此,您必须将上面的行移到onCreate()方法。

<强> EditedActivity.java

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

    String name;
    name = getIntent().getStringExtra("theName");

    EditText editList = (EditText) findViewById(R.id.editText);
    editList.setText(name);

    Button addBtn = (Button) findViewById(R.id.add_btn);
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveListInfo();
        }
    });
}

根本原因

如果将下面的行留在任何方法之外,它将在对象实例化期间运行。

 Button addBtn = (Button) findViewById(R.id.add_btn);

但是,在创建对象期间,尚未创建视图。所以,findViewById不会找到任何东西,并将返回null。因此,CRASH(或强制关闭)将会发生。

<强>解决方案

因此,请确保在已创建视图后调用的方法中添加findViewById()(否则,它将永远不会找到视图)。

如您所见,我建议在setContentView(R.layout.activity_edited)之后添加atCreate()方法(它负责将对象添加到VIEW)。

在该行之后,findViewById()将能够找到视图(当然,如果你在布局中添加它们)。