EditText条目上的Android Null对象引用

时间:2017-08-22 14:04:00

标签: android sqlite nullpointerexception android-edittext

有很多帖子都在寻求这个错误的帮助,但我找不到解释我的方案的帖子。我有我的应用程序的主屏幕,要求用户输入一个用户名,该用户名将在游戏结束后对应于游戏的日期/分数。显然,游戏丢失的得分/日期(时间)在结束之前是未知的,因此只有用户名被添加到前端的数据库中,但由于某种原因,我的代码在应用程序进入之前生成错误要求提供信息。

  

尝试调用虚拟方法' android.text.Editable   android.widget.EditText.getText()'在空对象引用上

代码如下。我仍然是Android的新手,所以我不确定代码是否在错误的位置或在错误的时间被调用。

这是似乎抛出错误的一行。

protected void insertIntoDB(){
    ContentValues cv = new ContentValues ();
    cv.put (db.USERNAME, editTextName.toString ());
    } 

这是与班级其他成员的背景线。

public class Snake extends AppCompatActivity {

DBHandler db;

Calendar c = Calendar.getInstance ();
Date d = c.getTime();

private SnakeView mSnakeView;
private static String ICICLE_KEY = "snake-view";
private static Context mContext;

private EditText editTextName;
private Button btnAdd;
private Button btnLastFive;
private RelativeLayout mRelativeLayout;

private PopupWindow mPopupWindow;

/**
 * Called when Activity is first created. Turns off the title bar, sets up
 * the content views, and fires up the SnakeView.
 * 
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);

    mContext = getApplicationContext ( );

    //set the layout
    setContentView (R.layout.snake_layout_r);

    db = new DBHandler (this);

    editTextName = (EditText) findViewById (R.id.editTextName);
    btnAdd = (Button) findViewById (R.id.btnAdd);
    btnLastFive = (Button) findViewById (R.id.btnLastFive);

    mSnakeView = (SnakeView) findViewById (R.id.snake);
    mSnakeView.setTextView ((TextView) findViewById (R.id.text));

    SimpleDateFormat dateFormat = new SimpleDateFormat ("MM/dd/yyyy");
    String format = dateFormat.format (d);

    if (savedInstanceState == null) {
        // We were just launched -- set up a new game
        mSnakeView.setMode (SnakeView.READY);
    } else {
        // We are being restored
        Bundle map = savedInstanceState.getBundle (ICICLE_KEY);
        if (map != null) {
            mSnakeView.restoreState (map);
        } else {
            mSnakeView.setMode (SnakeView.PAUSE);
        }
    }
}

public static Context getAppContext() {
    return mContext;
}

@Override
protected void onPause() {
    super.onPause();
    // Pause the game along with the activity
    mSnakeView.setMode(SnakeView.PAUSE);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    //Store the game state
    outState.putBundle(ICICLE_KEY, mSnakeView.saveState());
}

private Date currentdate(){
    final Calendar cal = Calendar.getInstance ();
    cal.add(Calendar.DATE, 0);
    return cal.getTime ();
}

protected void insertIntoDB(){
    ContentValues cv = new ContentValues ();
    cv.put (db.USERNAME, editTextName.toString ());
    }

public void lastFive(String[] args) {
    List<User> list = new ArrayList<User> ( );
    Collections.sort (list, User.Comparators._score);
}

public void onClick(View v) {
    if(v == btnAdd){
        insertIntoDB ();
    } else if (v == btnLastFive){
        // Initialize a new instance of LayoutInflater service
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

        // Inflate the custom layout/view
        View customView = inflater.inflate(R.layout.show_last_five,null);

            /*
                public PopupWindow (View contentView, int width, int height)
                    Create a new non focusable popup window which can display the contentView.
                    The dimension of the window must be passed to this constructor.

                    The popup does not provide any background. This should be handled by
                    the content view.

                Parameters
                    contentView : the popup's content
                    width : the popup's width
                    height : the popup's height
            */
        // Initialize a new instance of popup window
        mPopupWindow = new PopupWindow(
                customView,
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
        );

        // Set an elevation value for popup window
        // Call requires API level 21
        if(Build.VERSION.SDK_INT>=21){
            mPopupWindow.setElevation(5.0f);
        }

        // Get a reference for the custom view close button
        ImageButton closeButton = (ImageButton) customView.findViewById(R.id.ib_close);

        // Set a click listener for the popup window close button
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Dismiss the popup window
                mPopupWindow.dismiss();
            }
        });

            /*
                public void showAtLocation (View parent, int gravity, int x, int y)
                    Display the content view in a popup window at the specified location. If the
                    popup window cannot fit on screen, it will be clipped.
                    Learn WindowManager.LayoutParams for more information on how gravity and the x
                    and y parameters are related. Specifying a gravity of NO_GRAVITY is similar
                    to specifying Gravity.LEFT | Gravity.TOP.

                Parameters
                    parent : a parent view to get the getWindowToken() token from
                    gravity : the gravity which controls the placement of the popup window
                    x : the popup's x location offset
                    y : the popup's y location offset
            */
        // Finally, show the popup window at the center location of root relative layout
        mPopupWindow.showAtLocation(mRelativeLayout, Gravity.CENTER,0,0);
    }

};

XML文件

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Username"
        android:id="@+id/textViewName"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextName"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/buttonStyleSmall"
        android:text="Add"
        android:id="@+id/btnAdd"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Last 5 Games"
        android:id="@+id/btnLastFive"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/text"
            android:text="@string/snake_layout_text_text"
            android:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center_horizontal"
            android:textColor="#ff8888ff"
            android:textSize="24sp"/>
    </RelativeLayout>
</LinearLayout>

我不相信这是现有帖子(我读过的)的副本,因为以前的样本都没有涉及来自用户的输入(我的Edittext)或者包含错误引用了一行没有的存在于我的代码中(EditText.getText())也许是我的经验不足导致前面的答案没有解释导致这个错误被抛出的原因,但另一个问题对我没有帮助。如果真的是双重的话,请为此带来的不便表示歉意,这不是我的意图。

1 个答案:

答案 0 :(得分:0)

尝试使用editTextName.getText.toString()而不是editTextName.toString()