我点击按钮时得到NullPointerException,但不知道在哪里修复它

时间:2016-04-01 22:06:33

标签: java android android-studio nullpointerexception

当我点击我的界面上的“创建”按钮时,我得到一个空指针异常,该按钮链接到另一个活动,一旦我点击就会崩溃我的应用程序。唯一的问题是我不知道问题出在哪里。我在Java编程方面没有很多经验,所以这可能看起来有点愚蠢,但有人可以指出问题在哪里以及如何解决它?

提前致谢。

这是我的代码:

MainActivity.java:

package iftikhar.danayal.uninotes;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.List;

import iftikhar.danayal.uninotes.data.NoteItem;
import iftikhar.danayal.uninotes.data.NotesData;

public class MainActivity extends ListActivity {

    public static final int EDITOR_ACTIVITY_REQUEST = 1001;
    private NotesData datasource;
    List<NoteItem> notesList;
    Button action_create;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        action_create = (Button)findViewById(R.id.action_create);

        action_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NoteEditorActivity.class);
                startActivity(intent);
            }
        });

//        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });

        datasource = new NotesData(this);

        refreshDisplay();




    }



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

    private void setListAdapter(ArrayAdapter<NoteItem> adapt) {
    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        createNote();



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



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

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

NoteEditorActivity.java:

package iftikhar.danayal.uninotes;

/**
 * Created by danayal_94 on 01/04/16.
 */

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.EditText;

import iftikhar.danayal.uninotes.data.NoteItem;


public class NoteEditorActivity extends Activity{

    private NoteItem note;

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

        Intent intent = this.getIntent();
        note = new NoteItem();
        note.setKey(intent.getStringExtra("key"));
        note.setText(intent.getStringExtra("text"));

        EditText edit = (EditText) findViewById(R.id.noteText);
        edit.setText(note.getText());
        edit.setSelection(note.getText().length());
    }

    private void save() {
        EditText edit = (EditText) findViewById(R.id.noteText);
        String noteText = edit.getText().toString();
        Intent intent = new Intent();
        intent.putExtra("key", note.getKey());
        intent.putExtra("text", noteText);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            save();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        this.save();
    }
}

NoteItem.java:

package iftikhar.danayal.uninotes.data;

import android.widget.ListView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by danayal_94 on 24/03/16.
 */
public class NoteItem {
    private String text;
    private String key;


    public String getKey() {
        return key;
    }

    public void  setKey(String key) {
        this.key = key;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }


    public static NoteItem getNew() {
        Locale locale = new Locale("en_UK");
        Locale.setDefault(locale);
        String format = "dd-MM-yyyy HH:mm:ss Z";
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String key = formatter.format(new Date());

        NoteItem note = new NoteItem();
        note.setKey(key);
        note.setText("");
        return note;
    }

    @Override
    public String toString() {
        return this.getText();
    }
}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:fitsSystemWindows="true"
    tools:context="iftikhar.danayal.uninotes.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:id="@+id/listView">


        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>





    </android.support.design.widget.AppBarLayout>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@android:id/list" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/action_create"
        android:id="@+id/action_create"
        android:layout_below="@+id/listView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="44dp"
        android:layout_marginStart="44dp"
        android:layout_marginTop="50dp" />






</android.support.design.widget.CoordinatorLayout>

的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="iftikhar.danayal.uninotes">

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NoteEditorActivity"/>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

在NoteEditor.onCreate()中你有这个:

note.setKey(intent.getStringExtra("key"));
note.setText(intent.getStringExtra("text"));

EditText edit = (EditText) findViewById(R.id.noteText);
edit.setText(note.getText());
edit.setSelection(note.getText().length());

但是,由于您在创建Intent时未向getStringExtra("text")提供“额外”信息,null将返回note.getText().length()。因此,当您执行NullPointerException时,您将触发note.getText(),因为null将为public void onClick(View v) { Intent intent = new Intent(MainActivity.this, NoteEditorActivity.class); intent.putExtra("key", "my key"); intent.putExtra("text", "my text"); startActivity(intent); }

您需要在创建Intent时提供这些“额外”字符串,如下所示:

{{1}}