Olá pessoal,
Agora, ao final da aula 6, quando clico para abrir o formulário de cadastro de Aluno aparece o seguinte erro: Interessante que quando tento alterar um cadastro já salvo ele funciona perfeitamente.
FATAL EXCEPTION: main
Process: cadastro.caelum.com.br.cadastrocaelum, PID: 15742
java.lang.RuntimeException: Unable to start activity ComponentInfo{cadastro.caelum.com.br.cadastrocaelum/cadastro.caelum.com.br.cadastrocaelum.FormularioActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String cadastro.caelum.com.br.cadastrocaelum.modelo.Aluno.getNome()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3125)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3224)
at android.app.ActivityThread.access$1000(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1682)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6843)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String cadastro.caelum.com.br.cadastrocaelum.modelo.Aluno.getNome()' on a null object reference
at cadastro.caelum.com.br.cadastrocaelum.FormularioHelper.colocaAlunoNoFormulario(FormularioHelper.java:50)
at cadastro.caelum.com.br.cadastrocaelum.FormularioActivity.onCreate(FormularioActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6500)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3078)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3224)
at android.app.ActivityThread.access$1000(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1682)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6843)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Eis aqui meu código:
FormularioActivity:
package cadastro.caelum.com.br.cadastrocaelum;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.Serializable;
import cadastro.caelum.com.br.cadastrocaelum.DAO.AlunoDAO;
import cadastro.caelum.com.br.cadastrocaelum.modelo.Aluno;
/**
* Created by Paulo on 30/11/2015.
*/
public class FormularioActivity extends Activity {
private FormularioHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.formulario);
final Button botao = (Button) findViewById(R.id.botao);
//helper = new FormularioHelper(this);
final FormularioHelper helper = new FormularioHelper(this);
final Aluno alunoParaSerAlterado = (Aluno) getIntent().getSerializableExtra("alunoSelecionado");
helper.colocaAlunoNoFormulario(alunoParaSerAlterado);
Toast.makeText(this, "Alunos: " + alunoParaSerAlterado, Toast.LENGTH_LONG).show();
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Aluno aluno = helper.pegaAlunoDoFormulario();
Toast.makeText(FormularioActivity.this, "Objeto aluno criado: " + aluno.getNome(), Toast.LENGTH_LONG).show();
AlunoDAO dao = new AlunoDAO(FormularioActivity.this);
if (alunoParaSerAlterado != null) {
aluno.setId(alunoParaSerAlterado.getId());
botao.setText("Alterar");
dao.atualizar(aluno);
} else {
dao.insere(aluno);
}
dao.close();
finish();
}
});
}
}
FormularioHelper
package cadastro.caelum.com.br.cadastrocaelum;
import android.widget.EditText;
import android.widget.RatingBar;
import cadastro.caelum.com.br.cadastrocaelum.modelo.Aluno;
/**
* Created by Paulo on 05/12/2015.
*/
public class FormularioHelper {
private EditText campoNome;
private EditText campoTelefone;
private EditText campoEndereco;
private EditText campoSite;
private RatingBar campoNota;
private Aluno camposAluno;
public FormularioHelper(FormularioActivity activity){
camposAluno = new Aluno();
campoNome = (EditText) activity.findViewById(R.id.nome);
campoTelefone = (EditText) activity.findViewById(R.id.telefone);
campoEndereco = (EditText) activity.findViewById(R.id.endereco);
campoSite = (EditText) activity.findViewById(R.id.site);
campoNota = (RatingBar) activity.findViewById(R.id.nota);
}
public Aluno pegaAlunoDoFormulario(){
String nome = this.campoNome.getText().toString();
String telefone = this.campoTelefone.getText().toString();
String endereco = this.campoEndereco.getText().toString();
String site = this.campoSite.getText().toString();
int nota = this.campoNota.getProgress();
camposAluno.setNome(nome);
camposAluno.setTelefone(telefone);
camposAluno.setEndereco(endereco);
camposAluno.setSite(site);
camposAluno.setNota(Double.valueOf(nota));
return camposAluno;
}
public void colocaAlunoNoFormulario(Aluno alunoParaSerAlterado) {
campoNome.setText(alunoParaSerAlterado.getNome());
campoEndereco.setText(alunoParaSerAlterado.getEndereco());
campoSite.setText(alunoParaSerAlterado.getSite());
campoTelefone.setText(alunoParaSerAlterado.getTelefone());
campoNota.setRating(alunoParaSerAlterado.getNota().floatValue());
}
}
AlunoDAO
package cadastro.caelum.com.br.cadastrocaelum.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import cadastro.caelum.com.br.cadastrocaelum.modelo.Aluno;
/**
* Created by Paulo on 05/12/2015.
*/
public class AlunoDAO extends SQLiteOpenHelper {
private static final String DATABASE = "NomeDoBanco";
private static final int VERSAO = 1;
private static final String TABELA = "Alunos";
public AlunoDAO(Context ctx){
super(ctx, DATABASE, null, VERSAO);
}
@Override
public void onCreate(SQLiteDatabase database) {
String sql = "CREATE TABLE " + TABELA + " ("
+ "id INTEGER PRIMARY KEY, "
+ "nome TEXT UNIQUE NOT NULL, "
+ "telefone TEXT, "
+ "endereco TEXT, "
+ "site TEXT, "
+ "nota REAL, "
+ "caminhoFoto TEXT"
+ ");";
database.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABELA;
database.execSQL(sql);
onCreate(database);
}
public void insere(Aluno aluno){
ContentValues values = new ContentValues();
values.put("nome", aluno.getNome());
values.put("telefone", aluno.getTelefone());
values.put("endereco", aluno.getEndereco());
values.put("site", aluno.getSite());
values.put("nota", aluno.getNota());
values.put("caminhoFoto", aluno.getCaminhoFoto());
getWritableDatabase().insert(TABELA, null, values);
}
public List<Aluno> getLista(){
List<Aluno> alunos = new ArrayList<Aluno>();
String sql = "SELECT * FROM " + TABELA + ";";
Cursor cursor = getWritableDatabase().rawQuery(sql, null);
//laço para o cursor continuar pegando dados enquanto houver um "proximo"
while (cursor.moveToNext()){
Aluno aluno = new Aluno();
aluno.setId(cursor.getLong(cursor.getColumnIndex("id")));
aluno.setNome(cursor.getString(cursor.getColumnIndex("nome")));
aluno.setTelefone(cursor.getString(cursor.getColumnIndex("telefone")));
aluno.setEndereco(cursor.getString(cursor.getColumnIndex("endereco")));
aluno.setSite(cursor.getString(cursor.getColumnIndex("site")));
aluno.setNota(cursor.getDouble(cursor.getColumnIndex("nota")));
aluno.setCaminhoFoto(cursor.getString(cursor.getColumnIndex("caminhoFoto")));
alunos.add(aluno);
}
return alunos;
}
public void deletar(Aluno aluno){
String[] args = {aluno.getId().toString()};
getWritableDatabase().delete(TABELA, "id=?", args);
}
public void atualizar(Aluno aluno) {
ContentValues values = new ContentValues();
values.put("nome", aluno.getNome());
values.put("telefone", aluno.getTelefone());
values.put("endereco", aluno.getEndereco());
values.put("site", aluno.getSite());
values.put("nota", aluno.getNota());
values.put("caminhoFoto", aluno.getCaminhoFoto());
String[] args = {aluno.getId().toString()};
getWritableDatabase().update("Alunos", values, "id=?", args);
}
}