1
Logcat is accusing a problem of NullPointerException
, but I can’t identify it. From my point of view, it’s right. I know there’s a problem in lines 34 and 39 of ContactRegister
that lead to condition if(moveToFirst())
in the ContactRepository
, but I can’t understand which error. It might be a cursor positioning problem?
E/AndroidRuntime(914): FATAL EXCEPTION: main
E/AndroidRuntime(914): Process: br.com.contactsmanager, PID: 914
E/AndroidRuntime(914): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.contactsmanager/br.com.contactsmanager.ContactRegister}: java.lang.NullPointerException
E/AndroidRuntime(914): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
E/AndroidRuntime(914): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
E/AndroidRuntime(914): at android.app.ActivityThread.access$700(ActivityThread.java:135)
E/AndroidRuntime(914): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
E/AndroidRuntime(914): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(914): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(914): at android.app.ActivityThread.main(ActivityThread.java:4998)
E/AndroidRuntime(914): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(914): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(914): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
E/AndroidRuntime(914): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
E/AndroidRuntime(914): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(914): Caused by: java.lang.NullPointerException
E/AndroidRuntime(914): at br.com.contactsmanager.ContactRepository.listContacts(ContactRepository.java:175)
E/AndroidRuntime(914): at br.com.contactsmanager.ContactRegister.updateList(ContactRegister.java:39)
E/AndroidRuntime(914): at br.com.contactsmanager.ContactRegister.onCreate(ContactRegister.java:34)
E/AndroidRuntime(914): at android.app.Activity.performCreate(Activity.java:5243)
E/AndroidRuntime(914): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(914): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
E/AndroidRuntime(914): ... 11 more
Finally, they follow the codes of Contactrepository and Contactregister.
The project is a schedule of contacts synchronized with that of Android, which will serve as the basis for an application to be developed. I’m new to object-oriented programming.
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();
}
}
"Does the OS have any kind of feedback?" Any discussion about the site can be done in the meta (including in the footer of all pages it is listed as "feedback":P). If what you want is to contact the SE team, use the contact page (also in the footer).
– mgibsonbr
Thank you very much!
– Leonardo Saldanha
@If you keep having different mistakes every time you solve one, it’s okay to create new questions. Just keep in mind that it is best to present only information that is relevant to the specific problem. Also, if you have been getting answers to your questions, mark them as correct so that everyone can know which solution has helped you.
– Gabe