SQLite Search Error

2

Can anyone help me? I've done it in several ways but the app gives error and date. I am using database (SQLite) when it has to fetch it gives error :

01-05 03:40:18.544: E/AndroidRuntime(12226): FATAL EXCEPTION: main
01-05 03:40:18.544: E/AndroidRuntime(12226): Process: com.example.acquaconnect, PID: 12226
01-05 03:40:18.544: E/AndroidRuntime(12226): java.lang.IllegalStateException: Could not execute method of the activity
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.view.View$1.onClick(View.java:3841)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.view.View.performClick(View.java:4456)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.view.View$PerformClick.run(View.java:18482)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.os.Handler.handleCallback(Handler.java:733)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.os.Looper.loop(Looper.java:136)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.app.ActivityThread.main(ActivityThread.java:5097)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at java.lang.reflect.Method.invokeNative(Native Method)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at java.lang.reflect.Method.invoke(Method.java:515)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at dalvik.system.NativeStart.main(Native Method)
01-05 03:40:18.544: E/AndroidRuntime(12226): Caused by: java.lang.reflect.InvocationTargetException
01-05 03:40:18.544: E/AndroidRuntime(12226):    at java.lang.reflect.Method.invokeNative(Native Method)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at java.lang.reflect.Method.invoke(Method.java:515)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at android.view.View$1.onClick(View.java:3836)
01-05 03:40:18.544: E/AndroidRuntime(12226):    ... 11 more
0 1-05 03:40:18.544: E/AndroidRuntime(12226): Caused by: java.lang.NullPointerException
01-05 03:40:18.544: E/AndroidRuntime(12226):    at c om.example.Banco.RepositorioClientes.buscarClientes(RepositorioClientes.java:198)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at    com.example.acquaconnect.Login.buscarClientes(Login.java:103)
01-05 03:40:18.544: E/AndroidRuntime(12226):    at          com.example.acquaconnect.Login.butEntrar(Login.java:37)
01-05 03:40:18.544: E/AndroidRuntime(12226):    ... 14 more

Error line (line 37)

}else if ( loginCliente.equals(buscarClientes(loginCliente))){

Code

public class Login extends ActionBarActivity {

    private EditText vlogin;
        private EditText vsenha;
        Bundle params = new Bundle();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            vlogin = (EditText) findViewById(R.id.TextLogin);
            vsenha = (EditText) findViewById(R.id.TextSenha);
        }   


        public void butEntrar(View v) {
            String loginCliente = vlogin.getText().toString();
            String senhaCliente = vsenha.getText().toString();

            if(loginCliente.equals("") || senhaCliente.equals("")){
                Toast toast = Toast.makeText(this ,"Campo(s) vazio(s)!!", Toast.LENGTH_SHORT);
                toast.show();

            }else if ( loginCliente.equals(buscarClientes(loginCliente))){
                    Clientes c = buscarClientes(loginCliente);
                    String Login = c.login;
                    String Senha = c.senha;

                    if(senhaCliente.equals(Senha)){
                        //declaração para envio de informaçoes
                        //Bundle params = new Bundle();
                        params.putLong("id", c.id);
                        params.putString("nivel", c.nivel);
                        params.putString("nome", c.nome);
                        params.putString("login", c.login);
                        params.putString("senha", c.senha);
                        params.putString("ncel", c.ncel);
                        params.putString("numbomba", c.numbomba);
                        params.putString("b1", c.b1);
                        params.putString("b2", c.b2);
                        params.putString("b3", c.b3);
                        params.putString("b4", c.b4);
                        params.putString("b5", c.b5);
                        params.putString("b6", c.b6);

                        //usuario
                        if(String.valueOf("1").equals(c.nivel)){
                            //mandar dados cliente---passagem de paramentros
                            //envia os dados para a prox activity
                            Intent intent = new Intent(this, Usuario.class);
                            intent.putExtras(params);
                            startActivity(intent);
                        }
                        //adm
                        else if(String.valueOf("2").equals(c.nivel)){
                                //envia os dados para a prox activity
                                Intent intent = new Intent(this, ConfigADM.class);
                                intent.putExtras(params);
                                startActivity(intent);
                            }
                }/*fim if senha*/else{
                    Toast toast = Toast.makeText(this ,"Login não encontrado!!", Toast.LENGTH_SHORT);
                    toast.show();
                    }
            }
        }//botao


        private Toast toast;
        private long lastBackPressTime = 0;

        @Override
        public void onBackPressed() {
          if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
            toast = Toast.makeText(this, "Pressione novamente para sair.", 4000);
            toast.show();
            this.lastBackPressTime = System.currentTimeMillis();
          } else {
            if (toast != null) {
            toast.cancel();
          }
          super.onBackPressed();
         }
        }

        //Busca um Cliente pelo login
        public Clientes buscarClientes(String loginCliente) {
            Clientes clientes = RepositorioClientes.buscarClientes(loginCliente);
            return clientes;
        }

    }

Error line (line 198)

    Cursor c = db.query( NOME_TABELA, Clientes.colunas, Cliente.LOGIN + "='" + login + "'", null, null, null, null);

Code

public class RepositorioClientes {      

    private static final String CATEGORIA = "acqua";

    // Nome do banco
    private static final String NOME_BANCO = "acquaconnect";
    // Nome da tabela
    public static final String NOME_TABELA = "clientes";

    protected static SQLiteDatabase db;

    public RepositorioClientes(Context ctx) {
        // Abre o banco de dados já existente
        db = ctx.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null);
    }

    public RepositorioClientes() {
        // Apenas para criar uma subclasse...
    }

    // Salva o cliente, insere um novo ou atualiza
    public long salvar(Clientes clientes) {
        long id = clientes.id;

        if (id != 0) {
            atualizar(clientes);
        } else {
            // Insere novo
            id = inserir(clientes);
        }

        return id;
    }

    // Insere um novo Clientes
    public long inserir(Clientes clientes) {
        ContentValues values = new ContentValues();
        values.put(Cliente.NIVEL, clientes.nivel);
        values.put(Cliente.NOME, clientes.nome);
        values.put(Cliente.LOGIN, clientes.login);
        values.put(Cliente.SENHA, clientes.senha);
        values.put(Cliente.NCEL, clientes.ncel);
        values.put(Cliente.NUMBOMBA, clientes.numbomba);
        values.put(Cliente.B1, clientes.b1);
        values.put(Cliente.B2, clientes.b2);
        values.put(Cliente.B3, clientes.b3);
        values.put(Cliente.B4, clientes.b4);
        values.put(Cliente.B5, clientes.b5);
        values.put(Cliente.B6, clientes.b6);


        long id = inserir(values);
        return id;
    }

    // Insere um novo Clientes
    public long inserir(ContentValues valores) {
        long id = db.insert(NOME_TABELA, "", valores);
        return id;
    }

    // Atualiza o Clientes no banco. O id do Clientes é utilizado.
    public int atualizar(Clientes clientes) {
        ContentValues values = new ContentValues();
        values.put(Cliente.NIVEL, clientes.nivel);
        values.put(Cliente.NOME, clientes.nome);
        values.put(Cliente.LOGIN, clientes.login);
        values.put(Cliente.SENHA, clientes.senha);
        values.put(Cliente.NCEL, clientes.ncel);
        values.put(Cliente.NUMBOMBA, clientes.numbomba);
        values.put(Cliente.B1, clientes.b1);
        values.put(Cliente.B2, clientes.b2);
        values.put(Cliente.B3, clientes.b3);
        values.put(Cliente.B4, clientes.b4);
        values.put(Cliente.B5, clientes.b5);
        values.put(Cliente.B6, clientes.b6);

        String _id = String.valueOf(clientes.id);

        String where = Cliente._ID + "=?";
        String[] whereArgs = new String[] { _id };

        int count = atualizar(values, where, whereArgs);

        return count;
    }

    // Atualiza o cliente com os valores abaixo
    // A cláusula where é utilizada para identificar o cliente a ser atualizado
    public int atualizar(ContentValues valores, String where, String[] whereArgs) {
        int count = db.update(NOME_TABELA, valores, where, whereArgs);
        Log.i(CATEGORIA, "Atualizou [" + count + "] registros");
        return count;
    }

    // Deleta o Cliente com o id fornecido
    public int deletar(long id) {
        String where = Cliente._ID + "=?";

        String _id = String.valueOf(id);
        String[] whereArgs = new String[] { _id };

        int count = deletar(where, whereArgs);

        return count;
    }

    // Deleta o Cliente com os argumentos fornecidos
    public int deletar(String where, String[] whereArgs) {
        int count = db.delete(NOME_TABELA, where, whereArgs);
        Log.i(CATEGORIA, "Deletou [" + count + "] registros");
        return count;
    }


    // Retorna um cursor com todos os clientes
    public Cursor getCursor() {
        try {
            // select * from carros
            return db.query(NOME_TABELA, Clientes.colunas, null, null, null, null, null, null);
        } catch (SQLException e) {
            Log.e(CATEGORIA, "Erro ao buscar o cliente: " + e.toString());
            return null;
        }
    }

    // Retorna uma lista com todos os clientes
    public List<Clientes> listarCliente() {
        Cursor c = getCursor();

        List<Clientes> cliente = new ArrayList<Clientes>();

        if (c.moveToFirst()) {

            // Recupera os índices das colunas
            int idxId = c.getColumnIndex(Cliente._ID);
            int idxNivel = c.getColumnIndex(Cliente.NIVEL);
            int idxNome = c.getColumnIndex(Cliente.NOME);
            int idxLogin = c.getColumnIndex(Cliente.LOGIN);
            int idxSenha = c.getColumnIndex(Cliente.SENHA);
            int idxNcel = c.getColumnIndex(Cliente.NCEL);
            int idxNumBomba = c.getColumnIndex(Cliente.NUMBOMBA);
            int idxB1 = c.getColumnIndex(Cliente.B1);
            int idxB2 = c.getColumnIndex(Cliente.B2);
            int idxB3 = c.getColumnIndex(Cliente.B3);
            int idxB4 = c.getColumnIndex(Cliente.B4);
            int idxB5 = c.getColumnIndex(Cliente.B5);
            int idxB6 = c.getColumnIndex(Cliente.B6);

            // Loop até o final
            do {
                Clientes clientes = new Clientes();
                cliente.add(clientes);

                // recupera os atributos de cliente
                clientes.id = c.getLong(idxId);
                clientes.nivel = c.getString(idxNivel);
                clientes.nome = c.getString(idxNome);
                clientes.login = c.getString(idxLogin);
                clientes.senha = c.getString(idxSenha);
                clientes.ncel = c.getString(idxNcel);
                clientes.numbomba = c.getString(idxNumBomba);
                clientes.b1 = c.getString(idxB1);
                clientes.b2 = c.getString(idxB2);
                clientes.b3 = c.getString(idxB3);
                clientes.b4 = c.getString(idxB4);
                clientes.b5 = c.getString(idxB5);
                clientes.b6 = c.getString(idxB6);

            } while (c.moveToNext());
        }

        return cliente;
    }

    // Busca o cliente pelo login "select * from cliente where nome=?" MODIFICANDOO
    public static Clientes buscarClientes(String login) {
        Clientes clientes = null;

        try {
            // Idem a: SELECT _id,nivel,nome,login,senha,ncel,numbomba,b1,b2,b3,b4,b5,b6 from CARRO where login = ?
            Cursor c = db.query( NOME_TABELA, Clientes.colunas, Cliente.LOGIN + "='" + login + "'", null, null, null, null);

            // Se encontrou...
            if (c.moveToNext()) {

                clientes = new Clientes();

                // utiliza os métodos getLong(), getString(), getInt(), etc para recuperar os valores
                clientes.id = c.getLong(0);
                clientes.nivel = c.getString(1);
                clientes.nome = c.getString(2);
                clientes.login = c.getString(3);
                clientes.senha = c.getString(4);
                clientes.ncel = c.getString(5);
                clientes.numbomba = c.getString(6);
                clientes.b1 = c.getString(7);
                clientes.b2 = c.getString(8);
                clientes.b3 = c.getString(9);
                clientes.b4 = c.getString(10);
                clientes.b5 = c.getString(11);
                clientes.b6 = c.getString(12);
            }
        } catch (SQLException e) {
            Log.e(CATEGORIA, "Erro ao buscar o cliente" + e.toString());
            return null;
        }

        return clientes;
    }

    // Busca o carro pelo id
    public Clientes buscarClientesporID(long id) {
            // select * from carro where _id=?
            Cursor c = db.query(true, NOME_TABELA, Clientes.colunas, Cliente._ID + "=" + id, null, null, null, null, null);

            if (c.getCount() > 0) {

                // Posicinoa no primeiro elemento do cursor
                c.moveToFirst();

                Clientes clientes = new Clientes();

                // Lê os dados
                clientes.id = c.getLong(0);
                clientes.nivel = c.getString(1);
                clientes.nome = c.getString(2);
                clientes.login = c.getString(3);
                clientes.senha = c.getString(4);
                clientes.ncel = c.getString(5);
                clientes.numbomba = c.getString(6);
                clientes.b1 = c.getString(7);
                clientes.b2 = c.getString(8);
                clientes.b3 = c.getString(9);
                clientes.b4 = c.getString(10);
                clientes.b5 = c.getString(11);
                clientes.b6 = c.getString(12);

                return clientes;
            }

            return null;
        }

    // Busca um carro utilizando as configurações definidas no
    // SQLiteQueryBuilder
    // Utilizado pelo Content Provider de carro
    public Cursor query(SQLiteQueryBuilder queryBuilder, String[] projection, String selection, String[] selectionArgs,
            String groupBy, String having, String orderBy) {
        @SuppressWarnings("static-access")
        Cursor c = queryBuilder.query(this.db, projection, selection, selectionArgs, groupBy, having, orderBy);
        return c;
    }

    // Fecha o banco
    public void fechar() {
        // fecha o banco de dados
        if (db != null) {
            db.close();
        }
    }

}
    
asked by anonymous 05.01.2015 / 06:44

1 answer

4

In Java, one exception may cause another, cause another, etc. so that it is necessary to search for the root cause of the error. In the stack trace this is shown via Caused by: ... :

java.lang.IllegalStateException: Could not execute method of the activity
    ...
Caused by: java.lang.reflect.InvocationTargetException
    ...
Caused by: java.lang.NullPointerException
    ...

The source is then in the last exception displayed (the first occurred). Each line in that line shows which line of code the problem occurred, from "deepest" to "shallower" (ie if the a method called b which called c that threw an exception, c then b then a ). As the problem is rarely in the language itself and / or its libraries, always look for a line you wrote.

Unfortunately, many times the stack trace is truncated, but in this case the line where the exception occurred (the one at the top) is one you wrote:

Caused by: java.lang.NullPointerException
    at com.example.Banco.RepositorioClientes.buscarClientes(RepositorioClientes.java:198)

This indicates that a null reference error occurred exactly on this line, not in a code called by it, not someone calling it. Looking at the line in question:

Cursor c = db.query( NOME_TABELA, Clientes.colunas, Cliente.LOGIN + "='" + login + "'", null, null, null, null);

Note that there are only three possibilities: or db is null, or Clientes is null or Cliente is null. Assuming these last two are classes, not variables (by capitalization convention), the problem is probably in db .

In the rest of your code, I notice that db is a static (i.e. class) field of RepositorioClientes , but its only assignment is made during the call of its constructor. In some cases this may be interesting (lazy initialization of a global object, for example) but in general is a bad practice - because if the field is static it should not depend on the creation of any particular instance. More: If two instances are created one after the other, the db field will be overwritten during the second constructor call, without the first one being closed , which may lead to a memory.

My suggestion is to make it an instance field (i.e. not static), so a reference to RepositorioClientes is required to access it:

public class RepositorioClientes {      
    ...
    protected SQLiteDatabase db;

...

RepositorioClientes rep = new RepositorioCliente(ctx);
try {
    rep.buscarClientes(str); // Também passa a ser um método de instância
}
finally {
    rep.fechar(); // Só um exemplo: feche a conexão só quando ela não for mais necessária
}

In this way there will be no risk of a NullPointerException , since every RepositorioClientes object will have an instance of db guaranteed by the constructor. The most that can happen is that it has been previously closed - in which case there would also be an error, but different.

    
07.01.2015 / 02:07