Doubt: FATAL EXCEPTION

Asked

Viewed 79 times

0

I have 2 Activity the contact cadstro and the contacts, the registration the code is like this:

package com.example.marcio.agendacontatos;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.marcio.agendacontatos.database.DataBase;
import com.example.marcio.agendacontatos.dominio.RepositorioContato;
import com.example.marcio.agendacontatos.dominio.entidades.Contato;

import java.util.Date;

public class ActCadContatos extends AppCompatActivity {

    private EditText edtNome;
    private EditText edtEmail;
    private EditText edtTelefone;
    private EditText edtEndereco;
    private EditText edtDatasEspeciais;
    private EditText edtGrupos;

    private Spinner spnTipoEmail;
    private Spinner spnTipoTelefone;
    private Spinner spnTipoEndereco;
    private Spinner spnDatasEspeciais;

    private ArrayAdapter adpTipoEmail;
    private ArrayAdapter adpTipoTelefone;
    private ArrayAdapter adpTipoEndereco;
    private ArrayAdapter adpDatasEspeciais;

    private DataBase dataBase;//banco de dados
    private SQLiteDatabase conn; //conexão do banco
    private RepositorioContato repositorioContato;
    private Contato contato;


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

        edtNome = (EditText) findViewById(R.id.edtNome);
        edtEmail = (EditText) findViewById(R.id.edtEmail);
        edtTelefone = (EditText) findViewById(R.id.edtTelefone);
        edtEndereco = (EditText) findViewById(R.id.edtEndereco);
        edtDatasEspeciais = (EditText) findViewById(R.id.edtDatasEspeciais);
        edtGrupos = (EditText) findViewById(R.id.edtGrupos);

        spnTipoEmail = (Spinner) findViewById(R.id.spnTipoEmail);
        spnTipoTelefone = (Spinner) findViewById(R.id.spnTipoTelefone);
        spnTipoEndereco = (Spinner) findViewById(R.id.spnTipoEndereco);
        spnDatasEspeciais = (Spinner) findViewById(R.id.spnDatasEspeciais);

        //aqui criei as instâncias de cada objeto tipo arrayadapter;
        adpTipoEmail = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adpTipoEmail.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adpTipoTelefone = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adpTipoTelefone.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adpTipoEndereco = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adpTipoEndereco.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adpDatasEspeciais = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adpDatasEspeciais.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //associando cada objeto spinner ao arrayadpater
        spnTipoEmail.setAdapter(adpTipoEmail);
        spnTipoTelefone.setAdapter(adpTipoTelefone);
        spnTipoEndereco.setAdapter(adpTipoEndereco);
        spnDatasEspeciais.setAdapter(adpDatasEspeciais);


        //adicionando os tipos no spinner
        adpTipoEmail.add("Casa");
        adpTipoEmail.add("Trabalho");
        adpTipoEmail.add("Outros");
        adpTipoTelefone.add("Celular");
        adpTipoTelefone.add("Trabalho");
        adpTipoTelefone.add("Casa");
        adpTipoTelefone.add("Fax");
        adpTipoTelefone.add("Principal");
        adpTipoTelefone.add("Fax Trabalho");
        adpTipoTelefone.add("Outros");
        adpTipoEndereco.add("Casa");
        adpTipoEndereco.add("Trabalho");
        adpTipoEndereco.add("Outros");
        adpDatasEspeciais.add("Aniversario");
        adpDatasEspeciais.add("Data Comemorativa");
        adpDatasEspeciais.add("Outros");

        //sempre por o bloco do banco de dados em um try catch para tratar a exceção, caso exista.
        try {

            dataBase = new DataBase(this);
            conn = dataBase.getWritableDatabase();

            repositorioContato = new RepositorioContato(conn);

        } catch (SQLException ex) {
            //mensagem de erro
            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setMessage("Erro ao criar o banco" + ex.getMessage());//retornei o erro
            dlg.setNeutralButton("OK", null);//botão
            dlg.show();

        }

    }

    //responsável por fazer a associação do meu menu com a classe de contatos
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_act_cad_contatos, menu);


        return super.onCreateOptionsMenu(menu);
    }

    //responsável pela seleção da opção da ação dos menus
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.mni_acao1:

                if (contato == null) {
                    inserir();
                }
                finish();

                break;

            case R.id.mni_acao2:

                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void inserir() {

        try {
            contato = new Contato();

            contato.setNome(edtNome.getText().toString());
            contato.setTelefone(edtTelefone.getText().toString());
            contato.setEmail(edtEmail.getText().toString());
            contato.setEndereco(edtEndereco.getText().toString());

            Date date = new Date();
            contato.setDatasEspeciais(date);

            contato.setGrupos(edtGrupos.getText().toString());

            contato.setTipoTelefone("");
            contato.setTipoEmail("");
            contato.setTipoEndereco("");
            contato.setTipoDatasEspeciais("");

            repositorioContato.inserir(contato);
        } catch (Exception ex) {
            //mensagem de erro
            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setMessage("Erro ao inserir os dados" + ex.getMessage());//retornei o erro
            dlg.setNeutralButton("OK", null);//botão
            dlg.show();

        }
    }
}

And the Contact so:

package com.example.marcio.agendacontatos;

import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.example.marcio.agendacontatos.database.DataBase;
import com.example.marcio.agendacontatos.dominio.RepositorioContato;

public class ActContato extends AppCompatActivity implements View.OnClickListener {

    private ImageButton btnAdicionar;
    private EditText edtPesquisa;
    private ListView lstContatos;
    private ArrayAdapter<String> adpContatos;

    private DataBase dataBase;//banco de dados
    private SQLiteDatabase conn; //conexão do banco
    private RepositorioContato repositorioContato;


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

        btnAdicionar = (ImageButton) findViewById(R.id.btnAdicionar);
        edtPesquisa = (EditText) findViewById(R.id.edtPesquisa);
        lstContatos = (ListView) findViewById(R.id.lstContatos);

        btnAdicionar.setOnClickListener(this);

        //sempre por o bloco do banco de dados em um try catch para tratar a exceção, caso exista.
        try {

            dataBase = new DataBase(this);
            conn = dataBase.getWritableDatabase();

            repositorioContato = new RepositorioContato(conn);
            /*repositorioContato.testeInserirContatos();*/

            adpContatos = repositorioContato.buscaContatos(this);
            lstContatos.setAdapter(adpContatos);//vinculei o listview ao adpContatos p/ exibir na tela

            /*//mensagem de teste no banco
            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setMessage("Conexão criada com sucesso");
            dlg.setNeutralButton("OK", null);//botão
            dlg.show();*/

        } catch (SQLException ex) {
            //mensagem de erro
            AlertDialog.Builder dlg = new AlertDialog.Builder(this);
            dlg.setMessage("Erro ao criar o banco" + ex.getMessage());//retornei o erro
            dlg.setNeutralButton("OK", null);//botão
            dlg.show();

        }
    }

    @Override
    public void onClick(View v) {
        //responsável por chamar a tela de cadContatos
        Intent it = new Intent(this, ActCadContatos.class);
        startActivityForResult(it, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        adpContatos = repositorioContato.buscaContatos(this);
        lstContatos.setAdapter(adpContatos);
    }
}

The Repository Classcontacts look like this:

Private Sqlitedatabase Conn;

//referencia da conexão com o banco de dados
public RepositorioContato(SQLiteDatabase conn) {
    this.conn = conn;
}

public void inserir(Contato contato) {
    ContentValues values = new ContentValues();

    values.put("NOME", contato.getNome());
    values.put("TELEFONE", contato.getTelefone());
    values.put("TIPOTELEFONE", contato.getTipoTelefone());
    values.put("EMAIL", contato.getEmail());
    values.put("TIPOEMAIL", contato.getTipoEmail());
    values.put("ENDERECO", contato.getEndereco());

    values.put("DATASESPECIAIS", contato.getDatasEspeciais().getTime());//para retornar datas
    values.put("TIPODATASESPECIAIS", contato.getTipoDatasEspeciais());
    values.put("GRUPOS", contato.getGrupos());

    conn.insertOrThrow("CONTATO",null, values);//salvar os dados passados no cadastro
}

public ArrayAdapter<String> buscaContatos(Context context) {
    ArrayAdapter<String> adpContatos = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);

    //metodo utlizado para realizar a consulta
    Cursor cursor = conn.query("CONTATO", null, null, null, null, null, null);
    if (cursor.getCount() > 0) {

        cursor.moveToFirst();

        //esse laço vai correr todos os itens da tabela enquanto houver registros
        do {
            String telefone = cursor.getString(1);
            adpContatos.add(telefone);
        } while (cursor.moveToNext());

    }
    return adpContatos;
}

}

The error that is appearing is as follows:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.marcio.agendacontatos, PID: 12531
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                      at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
                      at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2937)
                      at android.widget.ListView.makeAndAddView(ListView.java:1945)
                      at android.widget.ListView.fillDown(ListView.java:719)
                      at android.widget.ListView.fillFromTop(ListView.java:785)
                      at android.widget.ListView.layoutChildren(ListView.java:1735)
                      at android.widget.AbsListView.onLayout(AbsListView.java:2731)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:443)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
                      at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:3146)
                      at android.view.View.layout(View.java:17993)
                      at android.view.ViewGroup.layout(ViewGroup.java:5817)
                      at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2755)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2456)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1524)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7520)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                      at android.view.Choreographer.doFrame(Choreographer.java:622)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
                      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:7325)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Application terminated.

I can’t find where the error is, I imagine it must be because I’m trying to find a null object... but I couldn’t identify the error.

  • The problem is related to Adapter. What comes in this line adpContatos = repositorioContato.buscaContatos(this); is valid ? What you have adpContatos ?

  • @Isac first thank you for your attention. I put the Repositoriocontact class on top. Apparently it is valid.

  • If you are in Android Studio use Debug mode and go line by line until error

  • Probably this line is returning null: String phone = cursor.getString(1);

  • @Gabriellocalhost tried the Debug mode, but at the time I put it to run, the project starts and already ends, returning the error described above.

  • @Alexandreguerreiro Good night, when I use the SOUT print some information on the logcat, but it does not show where the error is. Anyway thanks for the help.

  • Problem solved, I changed the type of Adpter that was as String for Contact.

Show 2 more comments
No answers

Browser other questions tagged

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