Android错误:尝试在空对象引用上调用虚拟... setOnClickListener(android.view.View $ OnClickListener)'

时间:2016-06-08 23:06:18

标签: java android android-layout nullpointerexception

我的应用关闭并提供错误。请帮忙。

活动类

public class MenuPrincipalActivity extends AppCompatActivity {

    SQLiteDatabase db;
    Button btcadastrar_ferramenta;
    Button btconsultar_ferramenta;
    Button btalterar_dados;
    Button btexcluir_ferramenta;



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

        btcadastrar_ferramenta = (Button)
                findViewById(R.id.btcadastrar_ferramenta);
        btalterar_dados = (Button)
                findViewById(R.id.btalterar_dados);
        btconsultar_ferramenta = (Button)
                findViewById(R.id.btconsultar_ferramenta) ;
        btexcluir_ferramenta = (Button) findViewById(R.id.btexcluir_ferramenta);
        btcadastrar_ferramenta.setOnClickListener ( new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent cadastrarFerramentaActivity = new
                        Intent(MenuPrincipalActivity.this, CadastrarFerramentasActivity.class
                );
                MenuPrincipalActivity.this.startActivity
                        (cadastrarFerramentaActivity);
                btalterar_dados.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        Intent consultaFerramentaActivity = new
                                Intent(MenuPrincipalActivity.this,
                                BuscaFerramentasActivity.class);
                        consultaFerramentaActivity.putExtra("opcao_dados", 1);

                        MenuPrincipalActivity.this.startActivity(consultaFerramentaActivity);
                    }
                });


                btconsultar_ferramenta.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        Intent consultaFerramentaActivity = new
                                Intent(MenuPrincipalActivity.this, BuscaFerramentasActivity.class);
                        consultaFerramentaActivity.putExtra("opcao_dados", 2);
                        MenuPrincipalActivity.this.startActivity(consultaFerramentaActivity);
                    }
                });
                btexcluir_ferramenta.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View argO) {
                        Intent consultaFerramentaActivity = new
                                Intent(MenuPrincipalActivity.this, BuscaFerramentasActivity.class);
                        consultaFerramentaActivity.putExtra("opcao_dados", 3);
                        MenuPrincipalActivity.this.startActivity(consultaFerramentaActivity);
                    }
                });
                try {
                    db = openOrCreateDatabase("banco_dados", Context.MODE_PRIVATE, null);
                    db.execSQL("create table if not exists  " + "ferramentas(numreg integer primary key " +
                            "autoincrement, nome_ferramenta text not null," +
                            "fabricante text not null, " + "preco float not null," +
                            "cor text not null, referencia text not null)");
                } catch (Exception e) {
                    MostraMensagem("Erro" + e.toString());
                }
            }

            public void MostraMensagem(String str) {
                AlertDialog.Builder dialogo = new AlertDialog.Builder(MenuPrincipalActivity.this);
                dialogo.setTitle("Aviso");
                dialogo.setMessage(str);
                dialogo.setNeutralButton("OK", null);
                dialogo.show();
            }

        } );}}

CadastrarFerramentasActivity class

public class CadastrarFerramentasActivity extends Activity {

    EditText ednome_ferramenta, edfabricante, edpreco, edcor, edreferencia;

    Button btcadastrar, btfechar;

    SQLiteDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastrar_ferramentas);
        ednome_ferramenta= (EditText)
                findViewById(R.id. ednome_ferramenta);
        edfabricante = (EditText) findViewById(R. id .edfabricante);
        edpreco = (EditText) findViewById(R. id . edpreco);
        edcor = (EditText) findViewById(R. id.edcor);
        edreferencia = (EditText) findViewById(R. id .edreferencia);
        btcadastrar = (Button) findViewById(R.id.btcadastrar_ferramenta);
        btcadastrar .setOnClickListener(new View.OnClickListener() {

            @Override public void onClick(View view) {
                String nome_ferramenta = ednome_ferramenta. getText( ) . toString() ;
                String fabricante = edfabricante.getText() .toString();
                String preco = edpreco.getText() .toString() ;
                String cor = edcor.getText() .toString();
                String referencia = edreferencia.getText() . toString();
                ContentValues valor = new ContentValues();
                valor. put ( "nome_ferramenta " , nome_ferramenta);
                valor. put ( "fabricante " , fabricante);
                valor. put ( "preco " , Float . parseFloat(preco));
                valor. put ("cor", cor) ;
                valor. put ( " referencia " , referencia) ;
                db. insert ( "ferramentas " , null, valor);
                AlertDialog.Builder dialogo = new
                        AlertDialog.Builder  (CadastrarFerramentasActivity. this) ;
                dialogo. setTitle( "Aviso");
                dialogo. setMessage( "Dados cadastrados com sucesso! " ) ;
                dialogo. setNeutralButton( "OK" , new DialogInterface.OnClickListener() {
                    @Override  public void onClick(DialogInterface argO, int argl) {
                                CadastrarFerramentasActivity.this.finish();
                            }});
                                dialogo. show( ) ;

                            }

    });
        btfechar = (Button) findViewById(R. id .btfechar); btfechar. setOnClickListener(new View. OnClickListener() {
            @Override
            public void onClick(View argO) {
                CadastrarFerramentasActivity.this.finish();
            }});
                try {
                    db = openOrCreateDatabase("banco_dados",
                            Context.MODE_PRIVATE, null);
                } catch (Exception e) {
                    MostraMensagem("Erro" + e.toString());
                }
            }

            public void MostraMensagem(String str) {
                AlertDialog.Builder dialogo = new AlertDialog.Builder(CadastrarFerramentasActivity.this);
                dialogo.setTitle("Aviso");
                dialogo.setMessage(str);
                dialogo.setNeutralButton("OK ", null);
                dialogo.show();
            }
        }

给出的错误是:

06-08 20:09:46.136 6894-6894/com.example.iohananabc.ferramentas E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.iohananabc.ferramentas, PID: 6894
     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iohananabc.ferramentas/com.example.iohananabc.ferramentas.CadastrarFerramentasActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
         at android.app.ActivityThread.access$800(ActivityThread.java:144)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5221)
         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:899)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
         at com.example.iohananabc.ferramentas.CadastrarFerramentasActivity.onCreate(CadastrarFerramentasActivity.java:33)
         at android.app.Activity.performCreate(Activity.java:5937)
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
         at android.app.ActivityThread.access$800(ActivityThread.java:144) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:135) 
         at android.app.ActivityThread.main(ActivityThread.java:5221) 
         at java.lang.reflect.Method.invoke(Native Method)

2 个答案:

答案 0 :(得分:1)

Pelo nome das classes acreditoquevocêfaleportuguês,entãofmotivoéqueum dos comandos findViewById()deve estar retornando nulo ou ocastestádandoerrado,entãorverifique se no arquivo de layout as idsdosbotõesestãorocttas。< / p>

如果您不会说葡萄牙语。发生的事情是findViewById()命令之一返回null或者转换操作失败。所以你需要做的是检查你的布局文件,看看按钮的id是否正确设置;

答案 1 :(得分:0)

因为我已经问过xml布局已经有一段时间了,但仍未发布,我将继续发布我的分析作为答案。

在您的错误日志中,它指向setOnClickListener()中包含NPE的CadastrarFerramentasActivity,根据您提供的代码段,唯一一个调用它的是btfechar.setOnClickListener

关于为什么会发生这种情况的一个解释是因为您的findViewId()引用了一个id(在您的代码中使用R.id.btfechar),这不在您设置的活动布局中(R.layout.activity_cadastrar_ferramentas 1}})。

检查你的布局xml文件,让我知道会发生什么(最好更新你的帖子)。

干杯!