anita
anita

Reputation: 23

To Do app crash

I'm trying to make a To Do app in android studio. But as soon as I click on add-button (+ in top right corner) the app crashes. I am very new to java and android studio but I think the problem may lay in "saveListInfo()" but I can't figure out how to fix it...

Code from 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();
            }
        });
    }
}

Code from 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);
    }


}

This is the error I get when clicking the add-button:

02-12 16:07:40.553 1410-1410/com.carpe_diem.anitas_todolist E/AndroidRuntime: FATAL EXCEPTION: main Process: com.carpe_diem.anitas_todolist, PID: 1410 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.carpe_diem.anitas_todolist/com.carpe_diem.anitas_todolist.EditedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: 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) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1067) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Upvotes: 0

Views: 153

Answers (2)

guipivoto
guipivoto

Reputation: 18677

By the logs, we can see that you crash is happening in following line:

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)
...

After checking your code, I can find in line 40 (EditedActivity.java:40) that following code is outside of any method or function.

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

So, you have to move the lines above to onCreate() method.

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();
        }
    });
}

Root Cause

If you leave the line below outside of any method, it will run during object instantiation.

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

However, during object creation, the view was not created yet. So, findViewById wont find anything and will return null. Thus, that CRASH (or Force Close) will happen.

Solution

So, make sure to add findViewById() inside a method which is called after the view was already created (otherwise, it will never find the view).

As you can see, I suggested to add at onCreate() method after setContentView(R.layout.activity_edited) (which is responsible to add the objects to VIEW).

After that line, findViewById() will be able to find the views (if you add them in the layout, of course).

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191681

Remove the brackets around this code

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

Should look like this

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

If you want to know why the crash happened, you can read more about What is an initialization block?

Upvotes: 1

Related Questions