编辑文本Android上的空指针异常

时间:2017-04-26 13:24:19

标签: java android nullpointerexception

我正在编写一个程序来保存编辑文本中的用户输入并将文本插入到列表视图中。即使我已经声明了编辑文本,我仍然会收到此null异常。

public class AddEditAlbum extends AppCompatActivity {

/**
 * These keys are to send back and forth information between the bundles and intents
 */
public static final String ALBUM_INDEX = "albumIndex";
public static final String ALBUM_NAME = "albumName";
EditText input;
Button save, cancel;
int albumIndex;

@Override
protected void onCreate(Bundle savedInstanceState) {

    save = (Button) findViewById(R.id.save);
    cancel = (Button) findViewById(R.id.cancel);
    input = (EditText) findViewById(R.id.add);

    // see if info was passed in to populate field
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        albumIndex = bundle.getInt(ALBUM_INDEX);
        input.setText(bundle.getString(ALBUM_NAME));
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_album);
}

public void Cancel(View view) {
    setResult(RESULT_CANCELED);
    finish();   //Returns to previous page on call stack
}

public void addAlbum(View view){

    String name = input.getText().toString();   //Fix this, goes to null pointer

    //Checks to see if input is null and returns
    if(name == null || name.length()==0){
        Toast.makeText(AddEditAlbum.this, "Enter valid album name", Toast.LENGTH_SHORT).show();
        Bundle bundle = new Bundle();
        bundle.putString(AlbumDialog.MESSAGE_KEY, "Album Name Required");
        DialogFragment newFragment = new AlbumDialog();
        newFragment.setArguments(bundle);
        newFragment.show(getFragmentManager(), "badfields");
        return;
    }
    //Toast.makeText(AddEditAlbum.this, "Enter valid album name", Toast.LENGTH_SHORT).show();
    Bundle bundle = new Bundle();
    bundle.putInt(ALBUM_INDEX, albumIndex);
    bundle.putString(ALBUM_NAME, name);

    // send back to caller
    Intent intent = new Intent();
    intent.putExtras(bundle);
    setResult(RESULT_OK,intent);
    finish();
}

}

public class MainActivity extends AppCompatActivity {

ListView listView;
private ArrayList<Album> albums;
public static final int EDIT_ALBUM_CODE = 1;
public static final int ADD_ALBUM_CODE = 2;

@Override
protected void onCreate(Bundle savedInstanceState) {

    listView = (ListView) findViewById(R.id.album_list);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void Create(View view){
    Intent intent = new Intent(this, AddEditAlbum.class);
    startActivityForResult(intent, ADD_ALBUM_CODE);
}

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode != RESULT_OK) {
        return;
    }

    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        return;
    }

    // gather all info passed back by launched activity
    String name = bundle.getString(AddEditAlbum.ALBUM_NAME);
    int index = bundle.getInt(AddEditAlbum.ALBUM_INDEX);

    if (requestCode == EDIT_ALBUM_CODE){
        Album album = albums.get(index);
        album.albumName = name;
    }
    else if (requestCode == ADD_ALBUM_CODE){
        ArrayList<Photo> photos = new ArrayList<>();
        albums.add(new Album(name, photos));
    }

    // redo Adapter since source content has changed
    //listView.setAdapter(new ArrayAdapter<Album>(this, album, albums));

}

所以这是我得到的完整错误,

FATAL EXCEPTION: main
                                                                             Process: com.example.mustu.androidphotos31, PID: 9965
                                                                             java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                 at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                                 at android.view.View.performClick(View.java:5610)
                                                                                 at android.view.View$PerformClick.run(View.java:22265)
                                                                                 at android.os.Handler.handleCallback(Handler.java:751)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                 at android.os.Looper.loop(Looper.java:154)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                              Caused by: java.lang.reflect.InvocationTargetException
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                                 at android.view.View.performClick(View.java:5610) 
                                                                                 at android.view.View$PerformClick.run(View.java:22265) 
                                                                                 at android.os.Handler.handleCallback(Handler.java:751) 
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                 at android.os.Looper.loop(Looper.java:154) 
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
                                                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                                                                                 at com.example.mustu.androidphotos31.AddEditAlbum.addAlbum(AddEditAlbum.java:54)
                                                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                                                 at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                                 at android.view.View.performClick(View.java:5610) 
                                                                                 at android.view.View$PerformClick.run(View.java:22265) 
                                                                                 at android.os.Handler.handleCallback(Handler.java:751) 
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                 at android.os.Looper.loop(Looper.java:154) 
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

3 个答案:

答案 0 :(得分:8)

super.onCreate(savedInstanceState);
setContentView(R.layout.add_album);

必须先执行此操作,否则不会设置contentView,findViewById将找不到任何内容,导致EditText为空。

答案 1 :(得分:0)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.album_list);

}

此外,您在onCreate方法之前调用listview,从而为您提供NPE

答案 2 :(得分:0)

update your onCreate() like this.
we should call setContentView(R.layout.your_layout) for passing the layout to the java class, then only it's views can be used.. failing to do so, will lead to NPE. 

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

    save = (Button) findViewById(R.id.save);
    cancel = (Button) findViewById(R.id.cancel);
    input = (EditText) findViewById(R.id.add);

    // see if info was passed in to populate field
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        albumIndex = bundle.getInt(ALBUM_INDEX);
        input.setText(bundle.getString(ALBUM_NAME));
    }


}