Problems saving SQLite data - Android

1

I'm trying to save the data in the SQLite database from a form in my app, but when I click the save button, the app closes and the following error is shown.

Android Studio points to the error for this code snippet

aluno.setName (String.valueOf (fieldName.getText ()))

found in class

Helper Form

Error Stack

  E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.alura.magnero2018.agendaalura, PID: 24918
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.alura.magnero2018.agendaalura.FormularioHelper.pegarAluno(FormularioHelper.java:73)
        at com.alura.magnero2018.agendaalura.FormularioActivity.onOptionsItemSelected(FormularioActivity.java:63)
        at android.app.Activity.onMenuItemSelected(Activity.java:3547)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
        at android.support.v7.app.AppCompatDelegateImpl.onMenuItemSelected(AppCompatDelegateImpl.java:888)
        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
        at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
        at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
        at android.view.View.performClick(View.java:6600)
        at android.view.View.performClickInternal(View.java:6577)
        at android.view.View.access$3100(View.java:781)
        at android.view.View$PerformClick.run(View.java:25912)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6912)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
Application terminated.

Activity Code

package com.alura.magnero2018.agendaalura;

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

import alura.modelo.Aluno;
import br.com.alura.dao.AlunoDAO;

public class FormularioActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_formulario);
        FormularioHelper helper = new FormularioHelper(this);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        FormularioHelper helper = new FormularioHelper(this);


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

                Aluno aluno = helper.pegarAluno();
                AlunoDAO dao = new AlunoDAO(this);
                dao.insere(aluno);
                dao.close();

                Toast.makeText(FormularioActivity.this, "Aluno" + aluno.getNome() + "salvo", Toast.LENGTH_LONG).show();
                Intent abrirLista = new Intent(FormularioActivity.this, ListaAlunosActivity.class);
               startActivity(abrirLista);

                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Student.java

package alura.modelo;

import android.text.Editable;

public class Aluno {
    private Long id;
    private String nome;
    private String endereco;
    private String telefone;
    private String site;
    private Double nota;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getSite() {
        return site;
    }

    public void setSite(String site) {
        this.site = site;
    }

    public Double getNota() {
        return nota;
    }

    public void setNota(Double nota) {
        this.nota = nota;
    }

    public String toString() {
        return getId() + " " + getNome();
    }
}

Formper.java

package com.alura.magnero2018.agendaalura;

import android.widget.EditText;
import android.widget.RatingBar;

import com.alura.magnero2018.agendaalura.FormularioActivity;
import com.alura.magnero2018.agendaalura.R;


import alura.modelo.Aluno;

public class FormularioHelper
{
    private EditText campoNome;
    private EditText campoEndereco;
    private EditText campoSitesPessoais;
    private EditText campoTelefone;
    private RatingBar campoNotas;

    public EditText getCampoNome() {
        return campoNome;
    }

    public void setCampoNome(EditText campoNome) {
        this.campoNome = campoNome;
    }

    public EditText getCampoEndereco() {
        return campoEndereco;
    }

    public void setCampoEndereco(EditText campoEndereco) {
        this.campoEndereco = campoEndereco;
    }

    public EditText getCampoSitesPessoais() {
        return campoSitesPessoais;
    }

    public void setCampoSitesPessoais(EditText campoSitesPessoais) {
        this.campoSitesPessoais = campoSitesPessoais;
    }

    public EditText getCampoTelefone() {
        return campoTelefone;
    }

    public void setCampoTelefone(EditText campoTelefone) {
        this.campoTelefone = campoTelefone;
    }

    public RatingBar getCampoNotas() {
        return campoNotas;
    }

    public void setCampoNotas(RatingBar campoNotas) {
        this.campoNotas = campoNotas;
    }


    public FormularioHelper(FormularioActivity activity)
    {
        EditText campoNome = activity.findViewById(R.id.nome);
        EditText campoEndereco = activity.findViewById(R.id.endereco);
        EditText campoSitesPessoais = activity.findViewById(R.id.sitesPessoais);
        EditText campoTelefone = activity.findViewById(R.id.telefone);
        RatingBar campoNotas = (RatingBar) activity.findViewById(R.id.notas);
    }

    public Aluno pegarAluno()
    {
        Aluno aluno = new Aluno();
        aluno.setNome(String.valueOf(campoNome.getText()));
        aluno.setEndereco(String.valueOf(campoEndereco.getText()));
        aluno.setSite(String.valueOf(campoSitesPessoais.getText()));
        aluno.setTelefone(String.valueOf(campoTelefone.getText()));
        aluno.setNota(Double.valueOf(campoNotas.getProgress()));

        return aluno;
    }
}

AlunoDAO.java

package br.com.alura.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

import alura.modelo.Aluno;

public class AlunoDAO extends SQLiteOpenHelper
{

    public AlunoDAO (Context context) {
        super(context, "Agenda", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE Alunos (id INTEGER PRIMARY KEY, nome TEXT NOT NULL, endereco TEXT, site TEXT, nota REAL);";

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        String sql = "DROP TABLE IF EXISTS Alunos";
        db.execSQL(sql);
        onCreate(db);
    }

    public void insere(Aluno aluno)
    {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues dados = new ContentValues();
        dados.put("nome", aluno.getNome());
        dados.put("endereco", aluno.getEndereco());
        dados.put("telefone", aluno.getTelefone());
        dados.put("site", aluno.getSite());
        dados.put("nota", aluno.getNota());

        db.insert("Alunos", null, dados);
    }

    public List<Aluno> buscaAlunos()
    {
        String sql = "SELECT * FROM Alunos;";
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.rawQuery(sql, null);

        List<Aluno> alunos = new ArrayList<Aluno>();
        while (c.moveToNext())
        {
            Aluno aluno = new Aluno();
            aluno.setId(c.getLong(c.getColumnIndex("id")));
            aluno.setNome(c.getString(c.getColumnIndex("nome")));
            aluno.setEndereco(c.getString(c.getColumnIndex("endereco")));
            aluno.setTelefone(c.getString(c.getColumnIndex("telefone")));
            aluno.setSite(c.getString(c.getColumnIndex("site")));
            aluno.setNota(c.getDouble(c.getColumnIndex("nota")));
        }

        c.close();
        return alunos;
    }
}
    
asked by anonymous 18.12.2018 / 15:57

2 answers

1

The problem is in the FormularioHelper constructor that is used in Activity:

public boolean onOptionsItemSelected(MenuItem item)
{
    FormularioHelper helper = new FormularioHelper(this); // <-- AQUI

    ... mais códigos ...

Your builder looks like this:

public FormularioHelper(FormularioActivity activity)
{
    EditText campoNome = activity.findViewById(R.id.nome);
    EditText campoEndereco = activity.findViewById(R.id.endereco);
    EditText campoSitesPessoais = activity.findViewById(R.id.sitesPessoais);
    EditText campoTelefone = activity.findViewById(R.id.telefone);
    RatingBar campoNotas = (RatingBar) activity.findViewById(R.id.notas);
}

Your idea, it seems to me, was to set the attributes of this class. But that's not what you did! There you create 5 NEW variables that are not being used.

So when you try to retrieve the values of Views they are null causing this error:

'android.text.Editable android.widget.EditText.getText()' on a null object reference

Well as I said the message, the reference (id) is null.

To fix this, you just need to do the following:

public FormularioHelper(FormularioActivity activity)
{
    this.campoNome = activity.findViewById(R.id.nome);
    this.campoEndereco = activity.findViewById(R.id.endereco);
    this.campoSitesPessoais = activity.findViewById(R.id.sitesPessoais);
    this.campoTelefone = activity.findViewById(R.id.telefone);
    this.campoNotas = (RatingBar) activity.findViewById(R.id.notas);
}
    
18.12.2018 / 18:22
0

I had some problems with creating and inserting the data in the table as well.

Follow the functional codes of my solution

ActivityAjativity

package com.alura.magnero2018.agendaalura;

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

import alura.modelo.Aluno;
import br.com.alura.dao.AlunoDAO;

public class FormularioActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_formulario);
        FormularioHelper helper = new FormularioHelper(this);
     /*   Button btnSalvar = findViewById(R.id.btnSalvar);

        btnSalvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* insere uma mensagem em forma de pop up na tela do usuario
                Parâmetros da função
                contexto (activity atual o qual a função será chamada)
                mensagem que deseaja inserir no pop up
                tempo que a mensagem deve estar visível

                Toast.makeText(FormularioActivity.this, "Usuário salvo com sucesso!", Toast.LENGTH_LONG).show();
                Intent abrirLista = new Intent(FormularioActivity.this, ListaAlunosActivity.class);
                finish();
            }
        }); */


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        /*cria um objeto do tipo MenuInflater, o qual é responsável por criar objetos do tipo menu, a partir de um
        arquivo xml
         */
        MenuInflater inflater = getMenuInflater();
        /*metodo que pega a referencia do arquivo xml e pega item por item e vai criando os MenuItem e adicionando no menu */
        inflater.inflate(R.menu.activity_menu_formulario, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) //switch vai aqui
    {
        FormularioHelper helper = new FormularioHelper(this);

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

                Aluno aluno = helper.pegarAluno();
                AlunoDAO dao = new AlunoDAO(this);
                dao.insere(aluno);
                dao.close();

                Toast.makeText(FormularioActivity.this, "Aluno " + aluno.getNome() + " salvo", Toast.LENGTH_LONG).show();
                Intent abrirLista = new Intent(FormularioActivity.this, ListaAlunosActivity.class);
               startActivity(abrirLista);

                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

AlunoDAO.java

package br.com.alura.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

import alura.modelo.Aluno;

public class AlunoDAO extends SQLiteOpenHelper
{

    public AlunoDAO (Context context) {
        super(context, "Agenda", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE Alunos (id INTEGER PRIMARY KEY, nome TEXT NOT NULL, endereco TEXT, site TEXT, telefone TEXT, nota REAL);";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        String sql = "DROP TABLE IF EXISTS Alunos";
        db.execSQL(sql);
        onCreate(db);
    }

    public void insere(Aluno aluno)
    {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues dados = new ContentValues();
        dados.put("nome", aluno.getNome());
        dados.put("endereco", aluno.getEndereco());
        dados.put("telefone", aluno.getTelefone());
        dados.put("site", aluno.getSite());
        dados.put("nota", aluno.getNota());

        db.insert("Alunos", null, dados);
        db.close();
    }

    public List<Aluno> buscaAlunos()
    {
        String sql = "SELECT * FROM Alunos;";
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.rawQuery(sql, null);

        List<Aluno> alunos = new ArrayList<Aluno>();
        while (c.moveToNext())
        {
            Aluno aluno = new Aluno();
            aluno.setId(c.getLong(c.getColumnIndex("id")));
            aluno.setNome(c.getString(c.getColumnIndex("nome")));
            aluno.setEndereco(c.getString(c.getColumnIndex("endereco")));
            aluno.setTelefone(c.getString(c.getColumnIndex("telefone")));
            aluno.setSite(c.getString(c.getColumnIndex("site")));
            aluno.setNota(c.getDouble(c.getColumnIndex("nota")));
        }

        c.close();
        return alunos;
    }
}

Student.java

package alura.modelo;

import android.support.annotation.NonNull;
import android.text.Editable;

public class Aluno {
    private Long id;
    private String nome;
    private String endereco;
    private String telefone;
    private String site;
    private Double nota;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public String getSite() {
        return site;
    }

    public void setSite(String site) {
        this.site = site;
    }

    public Double getNota() {
        return nota;
    }

    public void setNota(Double nota) {
        this.nota = nota;
    }

    @NonNull
    public String toString() {
        return getId() + " " + getNome();
    }
}

Formper.java

package com.alura.magnero2018.agendaalura;

import android.widget.EditText;
import android.widget.RatingBar;

import com.alura.magnero2018.agendaalura.FormularioActivity;
import com.alura.magnero2018.agendaalura.R;


import alura.modelo.Aluno;

public class FormularioHelper
{
    private EditText campoNome;
    private EditText campoEndereco;
    private EditText campoSitesPessoais;
    private EditText campoTelefone;
    private RatingBar campoNotas;

    public EditText getCampoNome() {
        return campoNome;
    }

    public void setCampoNome(EditText campoNome) {
        this.campoNome = campoNome;
    }

    public EditText getCampoEndereco() {
        return campoEndereco;
    }

    public void setCampoEndereco(EditText campoEndereco) {
        this.campoEndereco = campoEndereco;
    }

    public EditText getCampoSitesPessoais() {
        return campoSitesPessoais;
    }

    public void setCampoSitesPessoais(EditText campoSitesPessoais) {
        this.campoSitesPessoais = campoSitesPessoais;
    }

    public EditText getCampoTelefone() {
        return campoTelefone;
    }

    public void setCampoTelefone(EditText campoTelefone) {
        this.campoTelefone = campoTelefone;
    }

    public RatingBar getCampoNotas() {
        return campoNotas;
    }

    public void setCampoNotas(RatingBar campoNotas) {
        this.campoNotas = campoNotas;
    }


    public FormularioHelper(FormularioActivity activity)
    {
        this.campoNome = activity.findViewById(R.id.nome);
        this.campoEndereco = activity.findViewById(R.id.endereco);
        this.campoSitesPessoais = activity.findViewById(R.id.sitesPessoais);
        this.campoTelefone = activity.findViewById(R.id.telefone);
        this.campoNotas = (RatingBar) activity.findViewById(R.id.notas);
    }

    public Aluno pegarAluno()
    {
        Aluno aluno = new Aluno();
        aluno.setNome(String.valueOf(campoNome.getText()));
        aluno.setEndereco(String.valueOf(campoEndereco.getText()));
        aluno.setSite(String.valueOf(campoSitesPessoais.getText()));
        aluno.setTelefone(String.valueOf(campoTelefone.getText()));
        aluno.setNota(Double.valueOf(campoNotas.getProgress()));

        return aluno;
    }
}
    
19.12.2018 / 14:22