0

Sorry guys but I'm new here so if I do something wrong just let me know and I will make sure I don't let it happen again!

Well, I have a method called "verificaLogin" that checks if the login and password that have been typed in the login screen are ok.

The problem is that when I click the button I receive an exception.

This is my code

public class MainActivity extends Activity{

Button btnNovo, btnEntrar;
EditText txtLoginAcesso, txtSenhaAcesso;
//Button btnMainChat, btnMainUpload, btnMainAlbuns, btnMainAccount;

//private MainFragment mainFragment;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     btnNovo = (Button) findViewById(R.id.btnNovo);
     btnEntrar = (Button) findViewById(R.id.btnEntrar);


    //botão  novo - configuração
        btnNovo = (Button)findViewById(R.id.btnNovo);
        btnNovo.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                Intent trocatela = new Intent(MainActivity.this,CadastroActivity.class);
                MainActivity.this.startActivity(trocatela);
                //TelaPrincipalActivity.this.finish();
            }});

        //botão  entrar - configuração
        btnEntrar = (Button)findViewById(R.id.btnEntrar);
        btnEntrar.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                verificaLogin();
                //Intent trocatela = new Intent(MainActivity.this,TelaPrincipalActivity.class);
                //MainActivity.this.startActivity(trocatela);
                //TelaPrincipalActivity.this.finish();
            }});



public void verificaLogin(){
    try   {
        String DATABASE_TABLE = "Usuarios";
        SQLiteDatabase db = null;
        ContextoDados cd = new ContextoDados(this);
        cd.open();
        Cursor cursor;

        cursor = db.rawQuery("SELECT * FROM Usuarios WHERE Login LIKE'" + txtLoginAcesso.getText()+"'",null);


        if(cursor.getCount() < 1)
        {

            //System.out.println("Acesso ok");
            setContentView(R.layout.cadastro);

        } 
        else
        {
            if(cursor.getString(cursor.getColumnIndex("Senha")).equals (txtSenhaAcesso.getText().toString()) )  {
            setContentView(R.layout.telaprincipal);
            } else { //se for diferente ele diz que está errada
                setContentView(R.layout.cadastro);
          }

    }
     // irá sempre limpar os campos
     txtLoginAcesso.setText("");
     txtSenhaAcesso.setText("");
    }
    catch (SQLException e) 
    {
        e.printStackTrace();
    }

}


}

And the exception that I see:

java.lang.NullPointerException com.OnTheParty.Tcc.MainActivity.verificaLogin(MainActivity.java:99)

-- the line 99 is this:

cursor = db.rawQuery("SELECT * FROM Usuarios WHERE Login LIKE'" + txtLoginAcesso.getText()+"'",null);

Here is the class of my database

public class ContextoDados{


private static final String NOME_BD = "CadastroUsuario";
private static final int VERSAO_BD = 4;
private static final String LOG_TAG = "CadastroUsuario";


private static final String DATABASE_TABLE = "Usuarios";
public static final String KEY_ROWID = "Id";
public static final String KEY_NOME = "Nome";
public static final String KEY_LOGIN = "Login";
public static final String KEY_EMAIL = "Email";
public static final String KEY_SENHA = "Senha";



private final Context context;
private SQLiteDatabase db;
private DatabaseHelper DBHelper;
public static final String DATABASE_CREATE = "CREATE TABLE Usuarios (ID INTEGER PRIMARY KEY AUTOINCREMENT, Nome TEXT, Login TEXT, Email TEXT, Senha TEXT);";
public static final String DATABASE_DROP = "DROP TABLE IF EXISTS Usuarios";

public ContextoDados(Context ctx) {
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper{

    DatabaseHelper(Context context){
        super(context, NOME_BD, null, VERSAO_BD);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try 
        {
            db.execSQL(DATABASE_CREATE);
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        Log.w(LOG_TAG, "Atualizando a base de dados da versão " + oldVersion + " para " + newVersion + ", que destruirá todos os dados antigos");
        db.execSQL(DATABASE_DROP);
        onCreate(db);
    }

}
//abrir banco de dados
public ContextoDados open() throws SQLException{
    db = DBHelper.getWritableDatabase();
    return this;
}

//fechar banco de dados
public void close(){
    DBHelper.close();
}

//inserir valor
public long inserirUsuario(String Nome, String Login, String Email, String Senha){

    db = DBHelper.getWritableDatabase();
    try{
        ContentValues initialValues = new ContentValues();
        initialValues.put("Nome", Nome);
        initialValues.put("Login", Login);
        initialValues.put("Email", Email);
        initialValues.put("Senha", Senha);
        return db.insert("Usuarios", null, initialValues);
    }
    finally{
        db.close();
    }
}




public boolean deletarUsuario(long rowId){
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}


//retorna todos os valores da tabela MENOS A SENHA
public Cursor getTodosUsuarios(){
    return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NOME,  KEY_LOGIN, KEY_EMAIL}, null, null, null, null, null);
}



//retorna um valor especifico
public Cursor getUsuarioEspecifico(long rowId) throws SQLException  {
    Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NOME,  KEY_LOGIN, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}


//atualiza valores da tabela MENOS SENHA
public boolean atualizaUsuario(long rowId, String Nome, String Login, String Email){
    ContentValues args = new ContentValues();
    args.put(KEY_NOME, Nome);
    args.put(KEY_LOGIN, Login);
    args.put(KEY_EMAIL, Email);
    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) >
    0;
}

}

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
  • 1
    SQLiteDatabase db = null; --> where is your db? – muratgu Jun 03 '13 at 00:44
  • Perhaps actually set db to a context instead of NULL ? (which BTW you would see stepping through in debugger) – Mitch Wheat Jun 03 '13 at 00:47
  • This isn't a problem but I wanted to point out that you are initializing your `Buttons` twice, which isn't needed – codeMagic Jun 03 '13 at 00:50
  • For what it's worth, you should consider explicitly defining which columns you want out of table Usuarios instead of doing select *. See http://stackoverflow.com/questions/3639861/why-is-select-considered-harmful. Also, your query looks like it's vulnerable to SQL injection attacks. Take a read about the topic @ http://en.wikipedia.org/wiki/SQL_injection – Mike Pugh Jun 03 '13 at 00:54
  • @muratgu I just posted my database class –  Jun 03 '13 at 00:56

1 Answers1

1
SQLiteDatabase db = null;
ContextoDados cd = new ContextoDados(this);
cd.open();
Cursor cursor;
cursor = db.rawQuery("SELECT * FROM Usuarios WHERE Login LIKE'" + txtLoginAcesso.getText()+"'",null);

Your variable db can only be null at this point. You explicitly initialized it to be null.

If you get exceptions like this you can try a debugger. It will tell you where is the problem exactly.

With all those years of developmen java still does not tell you what is null.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207