therapy therapy - 7 months ago 20
Java Question

Trying to store data in a LinkedList on my test android app and keep getting a nullpointerexception

Problem: (All info below) I've set up the app to get text from

EditText
component and add it into a
LinkedList
once the button is pressed.

Tests: Testing for
getText.toString()
was successful (so u_in had a usable string) and I also tried to implement a simple array within my MainActivity and perform the same function which worked perfectly. Although I keep getting a
NullPointerException
with the database class and
LinkedList
.

I've also tried adding a null check in the
OnClick
anonymous method, but still got the same error.

Testing using physical device and running Android Studio 2.1

Main class:

public class MainActivity extends AppCompatActivity {

public Data_base db;
public String u_in;

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


public void check_button() {
Button add_button = (Button) findViewById(R.id.button);
final EditText etext = (EditText) findViewById(R.id.editText);
add_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
u_in = etext.getText().toString();
db.add(u_in,0);
}
});
}


Input class(Initializes information):

public class Input {

public String input;
public int age;

public Input (String input, int age) {
this.input = input;
this.age = age;
}

}


Database class (where I have my linkedlist and methods to manipulate it):

public class Data_base {

public LinkedList<Input> user_in = new LinkedList<>();

public void add(String in, int age) {
user_in.add(new Input(in, age));
}

public LinkedList<Input> getList() {
return user_in;
}

}


Error:

05-02 22:51:59.202 2813-2813/com.example.user.test_app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.test_app, PID: 2813
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.user.test_app.Data_base.add(java.lang.String, int)' on a null object reference
at com.example.user.test_app.MainActivity$1.onClick(MainActivity.java:33)
at android.view.View.performClick(View.java:5155)
at android.view.View$PerformClick.run(View.java:20747)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Answer

In your MainActivity you're using db.add without instantiating db first.