therapy therapy - 2 years ago 85
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

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

Tests: Testing for
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
with the database class and

I've also tried adding a null check in the
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;

protected void onCreate(Bundle savedInstanceState) {

public void check_button() {
Button add_button = (Button) findViewById(;
final EditText etext = (EditText) findViewById(;
add_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
u_in = etext.getText().toString();

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;



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(
at android.view.View.performClick(
at android.view.View$
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download