Error - Nullpointerexception

Asked

Viewed 377 times

-5

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 accusing a problem of Nullpointerexception, but I can not identify. To my point of view, It is right. I know you have a problem with lines 34 and 39 of Contactregister that lead to the if(moveToFirst()) condition in Contactrepository, but I cannot understand the error.

Follow Contactrepository and Contactregister codes. If you need to post any more, let me know in the comments.

The project is a schedule of contacts synchronized with that of 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();
    }

}
  • Make sure you’re putting in all the code. I at least could not find, nor with the help of Ctrl+F the listContacts() method of the Contactrepositoryscript class. This being the current error it would make sense to list the code of this method. Once available then I will take a look and try to find the source of Nullpointerexception.

  • Could post the code of lines 34 and 39 of the separate Contactregister for me look straight?

  • Lines alone do not make sense if seen alone. However, here they are: 34-updateList(); 39-Contacts = Repository.listContacts();

  • ah, you commented on them saying //erro aqui, now that I have seen , rs.

  • I said yes! D

  • Leo, your mistake is in ContactRepository.java but I can’t tell you where exactly, I can only tell you that you are in function listContacts(). I suggest you debug the function listContacts() and see which line will go wrong, so who knows I can help you.

  • Paul, I debugged the listContacts, but the error remains the same. Points out the consequences, and when arriving at the possible starting point, I come across the origin of the listContacts or the cursor moveToFirst.

  • The funny thing is that I even tried to take the statement of Arraylist commenting on it, but still the error persists, so I believe it is independent of that line. Maybe a cursor positioning error?

  • Make sure your cursor follows the following pattern: while (!cursor.isAfterLast()) cursor.moveToFirst(); //realiza operação... e depois: cursor.moveToNext(); and after that cursor.close()

  • It does not have "close". One thing I noticed is that the moveToFirst syntax is used for the second time in an if condition. Note in Contactrepository. The first statement is within a getCount in the Searchcontacts method. Does the device is waiting for an if value, which can only be obtained if a contact is searched?

  • I apologize if I say anything stupid. I’ve been working with java for two months, but before that I’ve never had any contact with the object-oriented programming language. C, C++ and block only.

  • I edited the post and await approval from the staff who suspended it.

  • 3

    @Leos: :) Come on, first you had posted a question/error, which was resolved below. After that you put in a comment that was going to edit the code so that the person could help you more. That would be another question. 2nd: the staff doesn’t even like long questions and big codes. The goal is to ask questions, not to review the whole code of the person seeking errors. Because we won’t import your entire project to be able to set breakpoints and run step-by-step, seeing the content of each variable as it runs.

  • 1

    @Leos: 3rd: The error log starts with an SQL error of not finding the "name" column. I didn’t find it in your code where Contact came from, so I’m guessing it’s one of the Iimports. But I was also struck by the "public Contact searchContactByName(String name1)" method, because inside it there is a Contact contact =null, and inside if it becomes a contact =new Contact(). I mean, it just exists inside the if, doesn’t it? And out of the if back to be a contact=null... vc, debugging, could set a point there and see its content in and out of the IF. I don’t, because I won’t care about your whole project.

  • You can leave, I will do it. I will also avoid more "unnecessary" content to you in the questions.

  • @leo.Cheating As the original question got the answer (apparently), I will remove the conjecture. Mark the answer that helped you as correct and, if you have new questions, ask another question. It’s okay to ask over and over again. It is the best alternative to ensure that the site remains organized, and more people can benefit from the answers.

Show 11 more comments

1 answer

2

As you can see in this line of error:

03-20 10:03:32.510: E/AndroidRuntime(940): Caused by: android.database.sqlite.SQLiteException: near "9851": syntax error (code 1): , while compiling: insert into contact(firstname,lastname,phone) values('Joao Pedro','Pereira',35 9851 9730);

Your problem is in INSERT's you’re forgetting to put quotes in the field phone, see how you’re putting it:

"insert into contact(firstname,lastname,phone) values('Joao Pedro','Pereira',35 9851 9730);",
"insert into contact(firstname,lastname,phone) values('Maria Amelia','Rodrigues',45 8814 9292);",
"insert into contact(firstname,lastname,phone) values('Pedro','Silva',15 9102 8922);" };

The right thing would be:

"insert into contact(firstname,lastname,phone) values('Joao Pedro','Pereira','35 9851 9730');",
"insert into contact(firstname,lastname,phone) values('Maria Amelia','Rodrigues','45 8814 9292');",
"insert into contact(firstname,lastname,phone) values('Pedro','Silva','15 9102 8922');" };
  • Thank you, the bug was fixed. However, another one came up when I was testing, pointing to a null Pointer Exception on lines 34 and 39 of Contactregister. I’ll edit the code so you can take a look and tell me if you know what it is.

  • 2

    Paul, open a Meta Question about this question here, can give your opinion there?

Browser other questions tagged

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