03-20 10:35:20.250: I/Process(897): Sending signal. PID: 897 SIG: 9
03-20 10:35:25.870: E/SQLiteLog(914): (1) no such column: name
03-20 10:35:25.870: E/data(914): Error while searching contacts: android.database.sqlite.SQLiteException: no such column: name (code 1): , while compiling: SELECT _id, name, lastname, phone FROM contact
03-20 10:35:25.880: D/AndroidRuntime(914): Shutting down VM
03-20 10:35:25.880: W/dalvikvm(914): threadid=1: thread exiting with uncaught exception (group=0xb4aefb90)
03-20 10:35:25.890: E/AndroidRuntime(914): FATAL EXCEPTION: main
03-20 10:35:25.890: E/AndroidRuntime(914): Process: br.com.contactsmanager, PID: 914
03-20 10:35:25.890: E/AndroidRuntime(914): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.contactsmanager/br.com.contactsmanager.ContactRegister}: java.lang.NullPointerException
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.ActivityThread.access$700(ActivityThread.java:135)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.os.Handler.dispatchMessage(Handler.java:102)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.os.Looper.loop(Looper.java:137)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.ActivityThread.main(ActivityThread.java:4998)
03-20 10:35:25.890: E/AndroidRuntime(914): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 10:35:25.890: E/AndroidRuntime(914): at java.lang.reflect.Method.invoke(Method.java:515)
03-20 10:35:25.890: E/AndroidRuntime(914): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-20 10:35:25.890: E/AndroidRuntime(914): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-20 10:35:25.890: E/AndroidRuntime(914): at dalvik.system.NativeStart.main(Native Method)
03-20 10:35:25.890: E/AndroidRuntime(914): Caused by: java.lang.NullPointerException
03-20 10:35:25.890: E/AndroidRuntime(914): at br.com.contactsmanager.ContactRepository.listContacts(ContactRepository.java:166)
03-20 10:35:25.890: E/AndroidRuntime(914): at br.com.contactsmanager.ContactRegister.updateList(ContactRegister.java:39)
03-20 10:35:25.890: E/AndroidRuntime(914): at br.com.contactsmanager.ContactRegister.onCreate(ContactRegister.java:34)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.Activity.performCreate(Activity.java:5243)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-20 10:35:25.890: E/AndroidRuntime(914): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
03-20 10:35:25.890: E/AndroidRuntime(914): ... 11 more
LogCat is experiencing a NullPointerException problem, but I can not identify it. In my point of view, that's right. I know there are problems in ContactRegister lines 34 and 39 that lead to the if (moveToFirst ()) condition in the ContactRepository, but I can not figure out which error.
Follow the ContactRepository and ContactRegister codes. If there is need to post any more, let me know in the comments.
The project is a calendar of contacts synchronized with Android, which will serve as the basis for an application to be developed.
ContactRepository.java
package br.com.contactsmanager;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
import br.com.contactsmanager.Contact.Contacts;
public class ContactRepository {
private static final String CATEGORY = "data";
private static final String DB_NAME = "android_data";
public static final String TABLE_NAME = "contact";
protected SQLiteDatabase db;
public ContactRepository(Context ctx)
{
db = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
}
protected ContactRepository()
{
}
public long save(Contact contact)
{
long id = contact.id1;
if (id != 0) {
update(contact);
}
else
{
id = insert(contact);
}
return id;
}
// Insere uma nova pessoa
public long insert(Contact contact)
{
ContentValues values = new ContentValues();
values.put(Contacts.NAME, contact.name1);
values.put(Contacts.LASTNAME, contact.name2);
values.put(Contacts.PHONE, contact.phone1);
long id = insert(values);
return id;
}
// Insere uma nova pessoa
public long insert(ContentValues values)
{
long id = db.insert(TABLE_NAME, "", values);
return id;
}
// Atualiza a pessoa no banco. O id da pessoa é utilizado.
public int update(Contact contact)
{
ContentValues values = new ContentValues();
values.put(Contacts.NAME, contact.name1);
values.put(Contacts.LASTNAME, contact.name2);
values.put(Contacts.PHONE, contact.phone1);
String _id = String.valueOf(contact.id1);
String where = Contacts._ID + "=?";
String[] whereArgs = new String[] { _id };
int count = update(values, where, whereArgs);
return count;
}
// Atualiza a pessoa com os valores abaixo
// A cláusula where é utilizada para identificar a pessoa a ser atualizado
public int update(ContentValues values, String where, String[] whereArgs)
{
int count = db.update(TABLE_NAME, values, where, whereArgs);
Log.i(CATEGORY, "Updated [" + count + "] registers");
return count;
}
// Deleta a pessoa com o id fornecido
public int delete(long id) {
String where = Contacts._ID + "=?";
String _id = String.valueOf(id);
String[] whereArgs = new String[] { _id };
int count = delete(where, whereArgs);
return count;
}
// Deleta a pessoa com os argumentos fornecidos
public int delete(String where, String[] whereArgs) {
int count = db.delete(TABLE_NAME, where, whereArgs);
Log.i(CATEGORY, "Has deleted [" + count + "] registers");
return count;
}
// Busca a pessoa pelo id
public Contact searchContact(long id)
{
// select * from pessoa where _id=?
Cursor c = db.query(true, TABLE_NAME, Contact.columns, Contacts._ID + "=" + id, null, null, null, null, null);
c.moveToFirst ();
if (c.getCount() > 0) {
// Posiciona no primeiro elemento do cursor
//c.moveToFirst ();
Contact contact = new Contact();
// Lê os dados
contact.id1 = c.getLong(0);
contact.name1 = c.getString(1);
contact.name2 = c.getString(2);
contact.phone1 = c.getInt(3);
return contact;
}
return null;
}
// Retorna um cursor com todas as pessoas
public Cursor getCursor()
{
try {
// select * from pessoas
return db.query(TABLE_NAME, Contact.columns, Contacts.NAME, null, null, null, null, null);
}
catch (SQLException e)
{
Log.e(CATEGORY, "Error while searching contacts: " + e.toString());
e.printStackTrace();
return null;
}
}
// Retorna uma lista com todas as pessoas
public List<Contact> listContacts()
{
Cursor c = getCursor();
List<Contact> contacts = new ArrayList<Contact>();
if ( c.moveToFirst() )
{
// Recupera os índices das colunas
int idxId = c.getColumnIndex(Contacts._ID);
int idxFirstName = c.getColumnIndex(Contacts.NAME);
int idxLastName = c.getColumnIndex(Contacts.LASTNAME);
int idxPhone = c.getColumnIndex(Contacts.PHONE);
// Loop até o final
do
{
Contact contact = new Contact();
contacts.add(contact);
// recupera os atributos da pessoa
contact.id1 = c.getLong(idxId);
contact.name1 = c.getString(idxFirstName);
contact.name2 = c.getString(idxLastName);
contact.phone1 = c.getInt(idxPhone);
}
while ( c.moveToNext() );
}
return contacts;
}
// Busca a pessoa pelo nome "select * from pessoa where nome=?"
public Contact searchContactByName(String name1) {
Contact contact = null;
try {
// Idem a: SELECT _id,nome,cpf,idade from pessoa where nome = ?
Cursor c = db.query(TABLE_NAME, Contact.columns, Contacts.NAME + "='" + name1 + "'", null, null, null, null);
// Se encontrou...
if (c.moveToNext()) {
contact = new Contact();
// utiliza os métodos getLong(), getString(), getInt(), etc para recuperar os valores
contact.id1 = c.getLong(0);
contact.name1 = c.getString(1);
contact.name2 = c.getString(2);
contact.phone1 = c.getInt(3);
}
} catch (SQLException e) {
Log.e(CATEGORY, "Error while searching person by name: " + e.toString());
return null;
}
return contact;
}
// Busca uma pessoa utilizando as configurações definidas no
// SQLiteQueryBuilder
// Utilizado pelo Content Provider de pessoa
public Cursor query(SQLiteQueryBuilder queryBuilder, String[] projection, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy)
{
Cursor c = queryBuilder.query(this.db, projection, selection, selectionArgs, groupBy, having, orderBy);
return c;
}
// Fecha o banco
public void close()
{
// fecha o banco de dados
if (db != null)
{
db.close();
}
}
}
----------------------
ContactRegister.java
package br.com.contactsmanager;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import br.com.contactsmanager.Contact.Contacts;
public class ContactRegister extends ListActivity {
protected static final int INSERT_EDIT = 1;
protected static final int SEARCH = 2;
public static ContactRepositoryScript repository;
private List<Contact> contacts;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
repository = new ContactRepositoryScript(this);
updateList();
}
protected void updateList()
{
contacts = repository.listContacts();
setListAdapter(new ContactListAdapter(this, contacts));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_EDIT, 0, "Insert new").setIcon(R.drawable.newcontact);
menu.add(0, SEARCH, 0, "Search").setIcon(R.drawable.search);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case INSERT_EDIT:
startActivityForResult(new Intent(this, EditContact.class), INSERT_EDIT);
break;
case SEARCH:
startActivity(new Intent(this, SearchContact.class));
break;
}
return true;
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
editContact(position);
}
protected void editContact(int position)
{
Contact contact = contacts.get(position);
Intent it = new Intent(this, EditContact.class);
it.putExtra(Contacts._ID, contact.id1);
startActivityForResult(it, INSERT_EDIT);
}
@Override
protected void onActivityResult(int code, int returnCode, Intent it) {
super.onActivityResult(code, returnCode, it);
if (returnCode == RESULT_OK)
{
updateList();
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
repository.close();
}
}