java.lang.Nullpointerexception: Attempt to invoke virtual method

Asked

Viewed 1,335 times

1

My program gave this problem when I tried to create a stack (database), to store strings on my Android app

package com.project.meuapp2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Principal extends AppCompatActivity {
    private Button btn;
    private EditText texto;
    BancodeDados DB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);
        texto = (EditText) findViewById(R.id.texto);
        btn = (Button) findViewById(R.id.btn);
        texto.setText("Insira um dado");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String y = texto.getText().toString();
                DB.InsereInicio(y);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        Intent i = null;

        switch(item.getItemId()) {
            case R.id.mnTela1:
                i = new Intent(this, pagina2.class);
                Toast.makeText(this, "item1", Toast.LENGTH_LONG).show();
                startActivity(i);
                break;
            case R.id.mnTela2:
                Toast.makeText(this, "item2", Toast.LENGTH_LONG).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

package com.project.meuapp2;

public class BancodeDados {
    elemento primeiro = new elemento();
    elemento ultimo = new elemento();

    public void InsereInicio(String x){
        elemento novodadoinicio = new elemento();
        novodadoinicio.dado = x;
        novodadoinicio.proximo = primeiro;
        if(primeiro==null){
            ultimo = novodadoinicio;
        }
        primeiro = novodadoinicio;
    }

    public void InsereFinal(String x){
        elemento novodadoultimo = new elemento();
        novodadoultimo.dado = x;
        novodadoultimo.proximo = primeiro;
        if(ultimo==null){
            primeiro = novodadoultimo;
        }
        ultimo = novodadoultimo;
    }

    public String removeInicio(){
        String x;
        x = primeiro.dado;
        primeiro = primeiro.proximo;
        return x;
    }
}

Log of Android Studio

03-27 18:14:28.017 5239-5239/com.project.meuapp2 E/Androidruntime: FATAL EXCEPTION: main Process: com.project.meuapp2, PID: 5239 java.lang.Nullpointerexception: Attempt to invoke virtual method 'void com.project.meuapp2.BancodeDados.Insereinicio(java.lang.String)' on a null Object Reference at com.project.meuapp2.Home$1.onClick(Home.java:30) at android.view.View.performClick(View.java:5198) at android.view.View$Performclick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.Activitythread.main(Activitythread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.Internal.os.Zygoteinit$Methodandargscaller.run(Zygoteinit.java:726) at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:616)

Note: I’ve tried initializing the variable primeiro, only that it accuses the same error.

  • It means your method is getting null, try debugging the code and see why this is happening.

  • 1

    Did the answer solve your problem? Do you think you can accept it? If you don’t know how, check out the [tour] how to do it. This would help a lot to indicate that the solution was useful for you and help everyone understand that. You can also vote for anything on the entire site.

1 answer

5

Possibly this solves the specific problem (there may still be others):

public class Principal extends AppCompatActivity {
    private Button btn;
    private EditText texto;
    BancodeDados DB = new BancodeDados(); // <===================== aqui

I put in the Github for future reference.

You need to have an instance created in order to access your members. Only declaring the variable does not help. Initialize solves this exception but it may be that the instance needs to be configured appropriately to work as desired.

  • 1

    ola thanks, gave up only that as you predicted gave another problem,he managed to enter the data correctly, so when I went to remove the data from the stack in another Activity,he gave Nullpointerexception again(because I think my entered data was erased when I went to another Activity),what should I do to keep the entered data independent of Activity that I am?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.