How to compare data from different activities using SQLite on Android Studio - java

//MAIN ACTIVITY
package com.example.saosteste2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BancoDados_Registo dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new BancoDados_Registo(MainActivity.this);
TextView email = (TextView) findViewById(R.id.id_email);
TextView password = (TextView) findViewById(R.id.id_password);
Button BLogIn = (Button) findViewById(R.id.id_Blogin);
Button conta_btn = (Button) findViewById(R.id.id_criarconta);
//testing email e password
BLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ????
}
});
conta_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, registo.class);
startActivity(intent);
}
});
}
}
//-----------------------SECOND ACTIVITY WITH THE DATABASE-----------------------//
//BANCODADOS_REGISTOS
package com.example.saosteste2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class BancoDados_Registo extends SQLiteOpenHelper {
public BancoDados_Registo(Context context) {
super(context, "REGISTOS.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create Table Registos(nome TEXT primary key, email TEXT, password TEXT, morada TEXT, telemovel TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop Table if exists Registos");
}
// INSERT DATA
public Boolean insertuserdata(String nome, String email, String password, String morada, String telemovel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
long result=db.insert("Registos", null, contentValues);
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}
//UPDATE DATA
public Boolean updateuserdata(String nome, String email, String password, String morada, String telemovel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
Cursor cursor = db.rawQuery("Select * from Registos where nome = ?", new String[] {nome});
if (cursor.getCount()>0){ //se o cursor tiver dados
long result=db.update("Registos", contentValues, "nome=?", new String [] {nome});
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}else {
return false;
}
}
//DELETEDATA
public Boolean deleteuserdata(String nome){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Registos where nome = ?", new String[] {nome});
if (cursor.getCount()>0){ //se o cursor tiver dados
long result=db.delete("Registos", "nome=?", new String [] {nome});
if (result==-1){ //se o insert falhar
return false;
}else{
return true;
}
}else {
return false;
}
}
public Cursor getuserdata(String email, String password){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from Registos", null);
return cursor;
}
Hi everyone!
I'm new in the world of Java and Android Studio. I don't know how to transmit data from the databse created in the second Activity to the first one. I need help checking if the email and password that the user puts on the first Activity (MainActivity) already exists in the database I created in the second Activity (BancoDados_Registo). Thank you for your attention in advance!

Here's a working example (but one that uses the deprecated startActivityForresult) based upon your code.
You should really look at https://developer.android.com/training/basics/intents/result for the non-deprecated way though.
When the App is started MainActivity displays the login/registo buttons:-
note hints added for email and password just to show where the TextViews.
Clicking the Registo button starts the Registo activity with empty EditTexts
for the nome,email,password morada and telemovel and a button to register (add) :-
Entering suitable data e.g. :-
And then clicking the Registo button, adds the user (if not a duplicate) and returns to MainActivity passing the nome and rowid which is then used to complete the email and password TextViews (not that you would do this, but rather to show extracting the data from the database) :-
The code:-
MainActivty
public class MainActivity extends AppCompatActivity {
private BancoDados_Registo dbManager;
TextView email; //<<<<< MOVED for full scope
TextView password; //<<<<< Moved for full scope
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new BancoDados_Registo(MainActivity.this);
email = (TextView) findViewById(R.id.id_email);
password = (TextView) findViewById(R.id.id_password);
Button BLogIn = (Button) findViewById(R.id.id_Blogin);
Button conta_btn = (Button) findViewById(R.id.id_criarconta);
//testing email e password
BLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ????
}
});
conta_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Registo.class);
startActivityForResult(intent,Registo.REGISTO_RESULTSCODE); // deprecated but works
}
});
}
#SuppressLint("Range")
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Registo.REGISTO_RESULTSCODE && resultCode == RESULT_OK) {
Toast.makeText(this,"Registered with ID " + data.getLongExtra(Registo.INTENTEXTRAKEY_REGISTOID,-1),Toast.LENGTH_LONG).show();
if (data.getLongExtra(Registo.INTENTEXTRAKEY_REGISTOID,-1) > 0) {
Cursor csr = dbManager.getUserDataByNome(data.getStringExtra(Registo.INTENTEXTRAKEY_REGISTONOME));
if (csr.moveToFirst()) {
password.setText(csr.getString(csr.getColumnIndex("password")));
email.setText(csr.getString(csr.getColumnIndex("email")));
}
}
}
}
}
BancoDados_Registo (changed/added methods only) :-
// INSERT DATA <<<<< CHANGED (to return rowid which can be more useful as it can be used to get the row)
public Long insertuserdata(String nome, String email, String password, String morada, String telemovel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nome", nome);
contentValues.put("email", email);
contentValues.put("password", password);
contentValues.put("morada", morada);
contentValues.put("telemovel", telemovel);
return db.insert("Registos", null, contentValues);
}
/* ADDED to get User just by nome */
public Cursor getUserDataByNome(String nome) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query("Registos",null,"nome=?",new String[]{nome},null,null,null);
}
Registo activity (note capitalised) :-
public class Registo extends AppCompatActivity {
private BancoDados_Registo dbManager;
public static final int REGISTO_REQUESTCODE = 98; //<<<
public static final String INTENTEXTRAKEY_REGISTOID = "ie_registo_id";
public static final String INTENTEXTRAKEY_REGISTONOME = "ie_registo_nome";
EditText nome;
EditText email;
EditText password;
EditText morada;
EditText telemovel;
Button registro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registo);
nome = this.findViewById(R.id.id_nome);
email = this.findViewById(R.id.id_email);
password = this.findViewById(R.id.id_password);
morada = this.findViewById(R.id.id_morada);
telemovel = this.findViewById(R.id.id_telemovel);
registro = (Button) findViewById(R.id.id_registro);
dbManager = new BancoDados_Registo(this);
registro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* Only insert in valid data - else Toast incomplete*/
if (
email.getText().length() > 0
&& password.getText().length() >= 8
&& morada.getText().length() > 0
&& telemovel.getText().length() > 0
) {
Long rowid = dbManager.insertuserdata(nome.getText().toString(),email.getText().toString(),password.getText().toString(),morada.getText().toString(),telemovel.getText().toString());
if (rowid > 0) {
Toast.makeText(view.getContext(),"Registered",Toast.LENGTH_LONG).show();
Intent resultIntent = new Intent();
resultIntent.putExtra(INTENTEXTRAKEY_REGISTOID,rowid);
resultIntent.putExtra(INTENTEXTRAKEY_REGISTONOME,nome.getText().toString());
setResult(RESULT_OK,resultIntent);
finish();
} else {
Toast.makeText(view.getContext(),"Not Registered (duplicate)",Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(view.getContext(),"Not Registered Incomplete input fields!!",Toast.LENGTH_LONG).show();
}
}
});
}
}

Related

How to show records from sqlite database on my app in a listview

I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???

Android Studio project

Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Try removing space from your column name's
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

signup button linked to sqlite database

public void onSignUpClick(View v){
if(v.getId() == R.id.btnRegister)
{
EditText name = (EditText)findViewById(R.id.TFname);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = name.getText().toString();
String pass1str = name.getText().toString();
String pass2str = name.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg:
Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
tpass.show();
}
else
{
//insert the details in DB:
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setPass(pass1str);
helper.insertContact(c);
}
}
}
I'm trying to make a signup form linked to sqlite database. the registraion button that's linked to onSignUpClick method doesn't work. any help to fix this error?
I have implemented a similar functionality to my app.. You can use this as a reference.You need to add whatever elements needed for your signup activity.
1. Create a database handler for your sqlite application.(DatabaseHandler.java)
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context, Object name,
Object factory, int version) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
String password;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Mydatabase.db";
// Contacts table name
private static final String TABLE_REGISTER= "register";
public static final String KEY_EMAIL_ID="email_id";
public static final String KEY_MOB_NO = "mobile_number";
public static final String KEY_PASSWORD = "password";
public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
+ KEY_EMAIL_ID+ " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
onCreate(db);
}
void addregister(UserRegister registerdata)
// code to add the new register
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
values.put(KEY_PASSWORD, registerdata.getPassword());
// Inserting Row
db.insert(TABLE_REGISTER, null, values);
db.close(); // Closing database connection
}
//code to get the register
String getregister(String username){
SQLiteDatabase db = this.getReadableDatabase();
//String selectquery="SELECT * FROM TABLE_REGISTER";
Cursor cursor=db.query(TABLE_REGISTER,null, "email_id=?",new String[]{username},null, null, null, null);
if(cursor.getCount()<1){
cursor.close();
return "Not Exist";
}
else if(cursor.getCount()>=1 && cursor.moveToFirst()){
password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
cursor.close();
}
return password;
}
public String getDatabaseName() {
return DATABASE_NAME;
}
public static String getTableContacts() {
return TABLE_REGISTER;
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
}
2. Create a modal class UserRegister
public class UserRegister {
//private variables
String email_id;
String mobile_number;
String password;
// Empty constructor
public UserRegister(){}
// constructor
public UserRegister( String email_id,String mobile_number, String password){
this.email_id=email_id;
this.mobile_number=mobile_number;
this.password = password;
}
public String getEmailId() {
return email_id;
}
public void setEmailId(String email_id){
this.email_id = email_id;
}
public String getMobNo() {
// TODO Auto-generated method stub
return mobile_number;
}
public void setMobNo(String mobile_number){
this.mobile_number=mobile_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.Create the RegistrationActivity
public class Registration_Activity extends AppCompatActivity {
EditText reg_email,reg_phone,reg_password;
Button reg_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final DatabaseHandler db = new DatabaseHandler(this, null, null, 2);
reg_email = (EditText)findViewById(R.id.reg_email);
reg_phone = (EditText)findViewById(R.id.reg_phone);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_button = (Button)findViewById(R.id.reg_button);
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = reg_email.getText().toString();
String phone = reg_phone.getText().toString();
String password = reg_password.getText().toString();
if (email.matches(emailPattern)) {
DatabaseHandler db = new DatabaseHandler(Registration_Activity.this, null, null, 2);
UserRegister userRegister = new UserRegister();
userRegister.setEmailId(email);
userRegister.setMobNo(phone);
userRegister.setPassword(password);
db.addregister(userRegister);
Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration_Activity.this, Login_Activity.class);
startActivity(intent);
Registration_Activity.this.finish();
}
else
{
Toast.makeText(getApplicationContext(),"Enter a valid Email Address",Toast.LENGTH_SHORT).show();
}
}
});
}
}
4. Login_Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login_Activity extends AppCompatActivity {
TextView signup;
String email,password;
EditText log_username,log_password;
Button login_button;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signup = (TextView)findViewById(R.id.signup);
String htmlString="<u>Signup</u>";
signup.setText(Html.fromHtml(htmlString));
log_username = (EditText)findViewById(R.id.log_username);
log_password = (EditText)findViewById(R.id.log_password);
login_button = (Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db=new DatabaseHandler(Login_Activity.this, null, null, 2);
email = log_username.getText().toString();
password = log_password.getText().toString();
String StoredPassword =db.getregister(email);
if(password.equals(StoredPassword)){
Toast.makeText(getApplicationContext(),"Login Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login_Activity.this,VideoActivity.class);
startActivity(intent);
Login_Activity.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
log_username.setText("");
log_password.setText("");
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login_Activity.this,Registration_Activity.class);
startActivity(intent);
Login_Activity.this.finish();
}
});
}
}

Hashing passwords in Java application

I have a Android application written in Java which utilises an SQLite database.
I want the passwords upon input on the sign up page to generate an MD5 or SHA1 hash which is stored in the database. Which can then be used when logging back into the application.
Can anyone offer any help?
Signup
package com.example.oliver.beckettreg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class SignUp extends Activity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
//if button clicked
public void onSignUpClick(View v) {
if (v.getId() == R.id.Bsignupbutton) {
EditText name = (EditText) findViewById(R.id.TFname);
EditText email = (EditText) findViewById(R.id.TFemail);
EditText uname = (EditText) findViewById(R.id.TFuname);
EditText pass1 = (EditText) findViewById(R.id.TFpass1);
EditText pass2 = (EditText) findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = email.getText().toString();
String unamestr = uname.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
//check passwords match
if(!pass1str.equals(pass2str))
{
//popup msg if fails
Toast pass = Toast.makeText(SignUp.this , "Passwords don't match!" , Toast.LENGTH_SHORT);
pass.show();
}
else
{
//validations for data input
if (name.getText().toString().length() == 0)
{name.setError("Name Required");}
else if (!email.getText().toString().matches("[a-z]{1}\\.[a-z]*[0-9]{4}#student\\.leedsbeckett\\.ac\\.uk"))
{email.setError("Incorrect Email Format");}
else if (!uname.getText().toString().matches("[cC][0-9]{7}"))
{uname.setError("Incorrect ID Format");}
else if (!pass1.getText().toString().matches("(?=.*[\\d])(?=.*[a-z])(?=.*[A-Z]).{8,}"))
{pass1.setError("Incorrect Password Format");}
else{
//insert the details in database
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setUname(unamestr);
c.setPass(pass1str);
helper.insertContact(c);
//popup if data passes validations
Toast pass = Toast.makeText(SignUp.this , "User Registered" , Toast.LENGTH_LONG);
pass.show();
}
}
}
}
public void onButtonClick(View v) {
if (v.getId() == R.id.Blogin2) {
Intent i = new Intent(SignUp.this, com.example.oliver.beckettreg.MainActivity.class);
startActivity(i);
}
}
}
Login
package com.example.oliver.beckettreg;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClick(View v)
{
//if button clicked
if(v.getId() == R.id.Blogin)
{
//check if passwords match
EditText a = (EditText)findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(MainActivity.this, NFC.class);
i.putExtra("Username",str);
startActivity(i);
}
else
{å
Toast temp = Toast.makeText(MainActivity.this , "Username and password don't match!" , Toast.LENGTH_SHORT);
temp.show();
}
}
//sign up button if data passes
if(v.getId() == R.id.Bsignup)
{
Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.SignUp.class);
startActivity(i);
}
if(v.getId() == R.id.Bnfc)
{
Intent i = new Intent(MainActivity.this, com.example.oliver.beckettreg.AttendanceRegistration.class);
startActivity(i);
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Database Helper
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
public class
DatabaseHelper extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "contacts.db";
//Table Names
private static final String REGISTER_TABLE_NAME = "register";
private static final String CONTACTS_TABLE_NAME = "contacts";
//Contacts Column Names
private static final String CONTACTS_COLUMN_ID = "id";
private static final String CONTACTS_COLUMN_NAME = "name";
private static final String CONTACTS_COLUMN_EMAIL = "email";
private static final String CONTACTS_COLUMN_UNAME = "uname";
private static final String CONTACTS_COLUMN_PASS = "pass";
//Register Column Names
private static final String REGISTER_COLUMN_ID = "id";
private static final String REGISTER_COLUMN_SEMINAR = "seminar";
private static final String REGISTER_COLUMN_LECTURE = "lecture";
SQLiteDatabase db;
//Table Create Statements
private static final String CONTACTS_TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null , email text not null , uname text not null , pass text not null);";
private static final String REGISTER_TABLE_CREATE = "create table register (id integer primary key not null , " +
" time DATETIME DEFAULT CURRENT_TIMESTAMP, seminar text not null , lecture text not null, );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Creating Required Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(REGISTER_TABLE_CREATE);
db.execSQL(CONTACTS_TABLE_CREATE);
this.db = db;
}
public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query , null);
int count = cursor.getCount();
values.put(CONTACTS_COLUMN_ID, count);
values.put(CONTACTS_COLUMN_NAME, c.getName());
values.put(CONTACTS_COLUMN_EMAIL, c.getEmail());
values.put(CONTACTS_COLUMN_UNAME, c.getUname());
values.put(CONTACTS_COLUMN_PASS, c.getPass());
db.insert(CONTACTS_TABLE_NAME, null, values);
db.close();
}
public void insertRegister(Register r) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from register";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(REGISTER_COLUMN_ID, count);
values.put(REGISTER_COLUMN_SEMINAR, r.getSeminar());
values.put(REGISTER_COLUMN_LECTURE, r.getLecture());
db.insert(REGISTER_TABLE_NAME, null, values);
db.close();
}
public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select uname, pass from "+CONTACTS_TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(uname))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
//On Upgrade Drop Older Tables
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + REGISTER_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);
//Create New Tables
this.onCreate(db);
}
}
You can implement this method, which will return the hash as a string.
private String hashMe(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1"); //could also be MD5, SHA-256 etc.
md.reset();
md.update(password.getBytes("UTF-8"));
byte[] resultByte = md.digest();
password = String.format("%01x", new java.math.BigInteger(1, resultByte));
} catch (NoSuchAlgorithmException e) {
//do something.
} catch (UnsupportedEncodingException ex) {
//do something
}
return password;
}
Since you are dealing with passwords, you should also salt the hash, and save them both in your Db.

Query Database using selected item from drop down spinner

I have an app that writes to and deletes from a database. I have a 2 spinners that are generated from 2 different columns in that database. I want to run a query for all records matching the selected item from the given drop down spinner. As of right now everything works fine however when I select an item from the drop down, nothing happens. I know I'm missing something just not sure what or where. Please help
Here is my Dbhelper.Java
package com.gamingbrothers.pat.passwordencrypter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//table structure
public class Dbhelper extends SQLiteOpenHelper {
public static final String DB_NAME = "LogInInfo.db";
public static final String TABLE_NAME = "LogInInfo_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "USER_NAME";
public static final String COL_3 = "USER_PASSWORD";
public static final String COL_4 = "APPLICATION";
public static final String COL_5 = "CUSTOMER";
public Dbhelper(Context context) {
super(context, DB_NAME, null, 1);
}
c.close();
return notes_array;
}
#Override
public void onCreate (SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"USER_NAME TEXT,USER_PASSWORD TEXT," +
"APPLICATION TEXT,CUSTOMER TEXT)");
}
//Query Database with item selected from drop down
public Cursor getChoiceData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from LogInInfo_table where CUSTOMER = ?",null);
return result;
}
//Gather Data
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from LogInInfo_table",null);
return result;
}
//getting customers for drop down
public List<String> getAllCustomers(){
List<String> customers = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToPosition(0)) {
do {
customers.add(cursor.getString(4));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning customers
return customers;
}
//getting apps for drop down
public List<String> getAllApps(){
List<String> apps = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToPosition(0)) {
do {
apps.add(cursor.getString(3));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning apps
return apps;
}
//creating update data function
public boolean updateData(String ID,String User_Name,String Password,String Application,String Customer){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,ID);
contentValues.put(COL_2,User_Name);
contentValues.put(COL_3,Password);
contentValues.put(COL_4, Application);
contentValues.put(COL_5,Customer);
db.update(TABLE_NAME,contentValues, "ID = ?",new String[] {ID});
return true;
}
//deleting data
public Integer deleteData (String ID){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[]{ID});
}
}
Here is my MainActivity.Java
package com.gamingbrothers.pat.passwordencrypter;
//Created by Pat 8/6/15
import android.app.AlertDialog;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Dbhelper myDB;
Button btnAdd;
Button btnDelete;
Button btnView;
Button btnUpdate;
Spinner spinner;
Spinner spinner2;
String itemSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new Dbhelper(this);
//initializing objects
editUserName = (EditText) findViewById(R.id.editText_user);
editPassword = (EditText) findViewById(R.id.editText_pass);
editApplication = (EditText) findViewById(R.id.editText_app);
editID = (EditText) findViewById(R.id.editText_id);
editCustomer = (EditText) findViewById(R.id.editText_customer);
btnAdd = (Button) findViewById(R.id.button_Add);
btnDelete = (Button) findViewById(R.id.button_Delete);
btnView = (Button) findViewById(R.id.button_View);
btnUpdate = (Button) findViewById(R.id.button_update);
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
AddData();
viewAll();
UpdateData();
DeleteData();
loadSpinnerData();
loadSpinner2Data();
}
public void loadSpinner2Data() {
//db handler
Dbhelper db2 = new Dbhelper(getApplicationContext());
//Spinner drop elem.
List<String> apps = db2.getAllApps();
//Create adapter for spinner
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, apps);
// Drop down layout style - list view with radio button
dataAdapter2
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching data adapter
spinner2.setAdapter(dataAdapter2);
}
private void loadSpinnerData() {
// database handler
Dbhelper db = new Dbhelper(getApplicationContext());
// Spinner Drop down elements
List<String> customers = db.getAllCustomers();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, customers);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deletedRows = myDB.deleteData(editID.getText().toString());
if(deletedRows >0)
Toast.makeText(MainActivity.this, "Data Deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Deleted", Toast.LENGTH_LONG).show();
}
}
);
}
//creating update data function
public void UpdateData() {
btnUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdated = myDB.updateData(editID.getText().toString(),
editUserName.getText().toString(),
editPassword.getText().toString(),
editApplication.getText().toString(),
editCustomer.getText().toString());
//Parse update completion
if (isUpdated == true)
Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Updated", Toast.LENGTH_LONG).show();
}
});
}
//add data to database
public void AddData() {
btnAdd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(editUserName.getText().toString(),
editPassword.getText().toString(),
editApplication.getText().toString(),
editCustomer.getText().toString());
//parse add completion
if (isInserted == true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
});
}
//Get results from database when button is clicked
public void viewAll() {
btnView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = myDB.getAllData();
//Check if database is empty
if (result.getCount() == 0) {
//Show Message
showMessage("Error", "No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
buffer.append("ID:" + result.getString(0) + "\n");
buffer.append("User Name:" + result.getString(1) + "\n");
buffer.append("Password:" + result.getString(2) + "\n");
buffer.append("App:" + result.getString(3) + "\n");
buffer.append("Customer:" + result.getString(4) + "\n\n");
}
//Show all data
showMessage("Data", buffer.toString());
}
}
);
}
//show data
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String label = parent.getItemAtPosition(position).toString();
myDB.getChoiceData().toString();
Toast.makeText(parent.getContext(), "Here is your information: "+ label,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
If you need me to post my XML just ask, but I didn't think it was neccessary and I didn't post my logcat because it doesn't give me an error.
From the code you posted you seem to be missing the selected item listener, add the following, for example, to your onCreate:
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);

Categories