-2

There have been many posts asking for help with this error, but I could not find one that explained my scenario. I have the home screen of my app asking the user to enter a username that will correspond to the date/score of the game once it concludes. Obviously the score/date(time) the game is lost is unknown until the end, so only the username is being added to the DB on the front end, yet for some reason my code is generating a an error before the app even gets to the point of requesting the information.

Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

Code is below. I am still rather new to Android, so I'm not certain if perhaps the code is in the wrong place or being called at the wrong time.

This is the line that seems to be throwing the error.

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

This is the line in context with the rest of the class.

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 File

<?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>

I did not believe this to be a duplicate of the existing posts (which I did read) as none of the previous samples involved an input from user (my Edittext) or included that the error referenced a line of code that did not exist in my code (EditText.getText()) Perhaps it is my inexperience that leads the previous answer to not explain what is causing this error to be thrown, but the other question was not of help to me. Apologies for the inconvenience if this is truly a dup, that was not my intention.

Kay Ana
  • 81
  • 1
  • 2
  • 12
  • 1
    your error says edittext.gettext on null object and in your code its just edittext.tostring().. please post correct code and also the xml code where u assigned edittext id – Aalap Patel Aug 22 '17 at 14:07
  • That is part of the issue, Aalap, I have searched the entire project and can find no instance where I used edittext.gettext. – Kay Ana Aug 22 '17 at 14:19
  • that onClick(v View) method looks a bit mysterious, should'nt that be encapsulated within an onClickListener? – GordonW Aug 22 '17 at 14:58
  • This was helpful, @ScottishUser and helped resolve the problem. I would give you credit for pointing me to this, if I could. – Kay Ana Aug 22 '17 at 22:31

1 Answers1

0

Try editTextName.getText.toString() instead of editTextName.toString()

Jamesp
  • 50
  • 10