>

Fórum

Fórum da RL System, voltado para analistas, programadores etc. Tudo sobre linguagem de programação e desenvolvimento Full Stack: Banco de Dados, Android, C#, Java, .NET, PHP, Node, Javascript, TypeScript, Front, HTML e muito mais.



Erro na tela de Login - Projeto pessoal


Estou tentando fazer uma tela de login para um projeto que estou criando e está dando um problema quando clico no botão Login. Era pra aparecer uma mensagem de alerta no Toast, mas aparece esse texto "Index -1 requested, with a size of 1". Segue o código:


package com.example.busquetaxi;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

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

public void RegisteringClick(View view) {
Intent it = new Intent(this, RegisteringActivity.class);
startActivity(it);
}

public void LoginClick(View view) {
SQLiteDatabase db = openOrCreateDatabase("usuarios.db", Context.MODE_PRIVATE, null);

EditText txtEmail = (EditText) findViewById(R.id.txtEmail);
EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
try {
Cursor cursor = db.rawQuery("SELECT password FROM usuarios WHERE email = ?" ,
new String[]{String.valueOf(txtEmail.getText().toString())});
Toast.makeText(getBaseContext(), cursor.getString(cursor.getColumnIndex("password")), Toast.LENGTH_LONG).show();
if (cursor.getString(cursor.getColumnIndex("password")).equals(SHA(txtPassword))) {
/*Intent it = new Intent(this, ListActivity.class);
startActivity(it);*/
db.close();
Toast.makeText(getBaseContext(), "Login efetuado com sucesso", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Email ou senha errados",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}


}

public String SHA(EditText password) {
StringBuilder pas = new StringBuilder();
MessageDigest algorithm = null;
try {
algorithm = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
byte hash[] = algorithm.digest(password.toString().getBytes("UTF-8"));
for (byte b : hash){
pas.append(String.format("%02X", 0xFF & b));
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return pas.toString();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


Esse é o xml:
[XML]
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbEmail" />

android:id="@+id/txtEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textEmailAddress" >




android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbPassword" />

android:id="@+id/txtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />

android:id="@+id/btnOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="LoginClick"
android:text="@string/lbLogin" />

android:id="@+id/btnRegistering"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="RegisteringClick"
android:text="@string/lbRegistering" />


[/XML]

A mensagem que aparece no Logcat é:
[quote]08-09 15:32:13.762: I/WindowManager(79): createSurface Window{413e53d8 Toast paused=false}: DRAW NOW PENDING[/quote]



8 Respostas


Ola Alexander

poste aqui sua criacao do banco de dados




O banco ele está criando direitinho, mas quando volto para a página de login, ocorre o erro:


package br.ufrj.gta.alexsander.busquetaxi;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

public class RegisteringActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registering);

SQLiteDatabase db = openOrCreateDatabase("usuarios.db", Context.MODE_PRIVATE, null);

StringBuilder sqlClientes = new StringBuilder();
sqlClientes.append("CREATE TABLE IF NOT EXISTS usuarios (");
sqlClientes.append("_id INTEGER PRIMARY KEY AUTOINCREMENT, ");
sqlClientes.append("name VARCHAR(50) NOT NULL, ");
sqlClientes.append("email VARCHAR(50) NOT NULL, ");
sqlClientes.append("birthdate TIMESTAMP, ");
sqlClientes.append("password VARCHAR(300) NOT NULL, ");
sqlClientes.append("option VARCHAR(10) NOT NULL, ");
sqlClientes.append("date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, ");
sqlClientes.append("car VARCHAR(20)");

db.execSQL(sqlClientes.toString());

db.close();


}
public void OKClick(View v) {
SQLiteDatabase db = openOrCreateDatabase("usuarios.db", Context.MODE_PRIVATE, null);
EditText txtPassword = (EditText)findViewById(R.id.txtPassword);
EditText txtConfirmPassword = (EditText)findViewById(R.id.txtConfirmPassowrd);

if (txtPassword.getText().toString().equals(
txtConfirmPassword.getText().toString())) {
EditText txtName = (EditText) findViewById(R.id.txtName);
EditText txtEmail = (EditText) findViewById(R.id.txtEmailRegistering);
EditText txtBirthdate = (EditText)findViewById(R.id.txtBirthdate);
RadioGroup rdg = (RadioGroup) findViewById(R.id.rdgOpcao);
final ContentValues ctv = new ContentValues();


rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (checkedId == R.id.cabby) {
ctv.put("option", "Cabby");
}else {
ctv.put("option", "Passenger");
}
}
});

ctv.put("name", txtName.getText().toString());
ctv.put("email", txtEmail.getText().toString());
ctv.put("birthdate", txtBirthdate.getText().toString());
ctv.put("password", SHA(txtPassword));
try {
if (db.insert("usuarios", "_id, date", ctv) > 0) {
Toast.makeText(getBaseContext(), "Cadastrado com sucesso!", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Erro ao cadastrar!", Toast.LENGTH_SHORT).show();
}
db.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}

}else {
Toast.makeText(getApplicationContext(), "Erro ao cadastrar!", Toast.LENGTH_SHORT).show();
}

}

public String SHA(EditText password) {
StringBuilder pas = new StringBuilder();
MessageDigest algorithm = null;
try {
algorithm = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
byte hash[] = algorithm.digest(password.toString().getBytes("UTF-8"));
for (byte b : hash){
pas.append(String.format("%02X", 0xFF & b));
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return pas.toString();
}
}





Essa é a tela de registro:

[quote]

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

android:id="@ id/txtName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbName" />

android:id="@ id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >




android:id="@ id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbEmail" />

android:id="@ id/txtEmailRegistering"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textEmailAddress" />

android:id="@ id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbBirthdate" />

android:id="@ id/txtBirthdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="date" />

android:id="@ id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbPassword" />

android:id="@ id/txtPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />

android:id="@ id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbConfirmPassword" />

android:id="@ id/txtConfirmPassowrd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />

android:id="@ id/rdgOpcao"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

android:id="@ id/cabby"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/lbCabby" />

android:id="@ id/passenger"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbPassenger" />


android:id="@ id/btnOK"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="OKClick"
android:text="@string/lbOK" />



[/quote]




coloque um log cat ali depois

if (cursor.getString(cursor.getColumnIndex("password")).equals(SHA(txtPassword))) {

Log.d("ERRO", String.valueof(SHA(txtPassword));

e mostre o q gerou




Dá essa mensagem

08-12 23:14:55.334: I/WindowManager(79): createSurface Window{4177d400 Toast paused=false}: DRAW NOW PENDING




Dá essa mensagem

08-12 23:14:55.334: I/WindowManager(79): createSurface Window{4177d400 Toast paused=false}: DRAW NOW PENDING




Consegui resolver esse problema, tava dando uma mensagem de Index requested -1, size of 2. Coloquei um cursor.moveToFirst() e resolveu. Agora to tendo um problema com a criptografia na senha. Poderiam me ajudar? A senha que criptografa e salva no banco de dados quando faz o login não bate com a senha que é criptografada quando o usuário loga. Segue o código do algoritmo de criptografia:


//Método para criptografar senha no formato SHA-256
public String SHA(EditText password) {
StringBuilder pas = new StringBuilder();
MessageDigest algorithm = null;
try {
algorithm = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
byte hash[] = algorithm.digest(password.toString().getBytes("UTF-8"));
for (byte b : hash){
pas.append(String.format("%02X", 0xFF & b));
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return pas.toString();
}




Alexsander

Quando comparar no login, criptografe primeiro a senha digitada pelo usuário e só assim, compare.