Populate Android Listview with data extracted from a database - java

I am a newbie to Android programming.I want to use data inputted into an SQLite database to populate an Android Listview. However, Android keeps highlighting the SimpleCursorAdapter below as error. Can anyone help?
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
Below is the full code:
package com.allmycode.databaseinsertwithlistview;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText GetName,GetPhoneNumber,GetSubject ;
Button Submit ;
String Name, PhoneNumber, Subject ;
Boolean CheckEditTextEmpty ;
String SQLiteQuery;
SQLiteDatabase SQLITEDATABASE;
TextView display;
Cursor cursor;
ListView listView;
//Make these declarations to enable the fetchallitems() method work
public static final String name = "name";
public static final String phone_number = "Phone_number";
public static final String subject = "subject";
private SimpleCursorAdapter dataAdapter;
private static final String demoTable = "demoTable";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);GetName = (EditText)findViewById(R.id.editText1);
GetPhoneNumber = (EditText)findViewById(R.id.editText2);
GetSubject = (EditText)findViewById(R.id.editText3);
listView = (ListView) findViewById(R.id.ListVw);
//display= (TextView) findViewById(R.id.textView) ;
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBCreate();
SubmitData2SQLiteDB();
displayListView();
}
});
}
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("DemoDataBase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS demoTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name String, phone_number String, subject String);");
}
public void SubmitData2SQLiteDB(){
Name = GetName.getText().toString();
PhoneNumber = GetPhoneNumber.getText().toString();
Subject = GetSubject.getText().toString();
CheckEditTextIsEmptyOrNot( Name,PhoneNumber, Subject);
if(CheckEditTextEmpty == true)
{
SQLiteQuery = "INSERT INTO demoTable (name,phone_number,subject) VALUES('"+Name+"', '"+PhoneNumber+"', '"+Subject+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(MainActivity.this,"Data Submit Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
// addtoTextView();
}
else {
Toast.makeText(MainActivity.this,"Please Fill All the Fields", Toast.LENGTH_LONG).show();
}
}
public void CheckEditTextIsEmptyOrNot(String Name,String PhoneNumber, String subject ){
if(TextUtils.isEmpty(Name) || TextUtils.isEmpty(PhoneNumber) || TextUtils.isEmpty(Subject)){
CheckEditTextEmpty = false ;
}
else {
CheckEditTextEmpty = true ;
}
}
public void ClearEditTextAfterDoneTask(){
GetName.getText().clear();
GetPhoneNumber.getText().clear();
GetSubject.getText().clear();
}
/* void addtoTextView(){
cursor= SQLITEDATABASE.rawQuery("SELECT * FROM demoTable;",null);
if (cursor !=null && cursor.moveToFirst()){
String name;
do{
name = cursor.getString(0);
String pnone_number=cursor.getString(1);
String test2=cursor.getString(2);
String test3 = cursor.getString(3);
display.append(name + " " + pnone_number +" "+test2 +" "+ test3 +"\n");
} while (cursor.moveToNext());
}
display.append("-------------\n");
} */
public Cursor fetchAllItems() {
Cursor mCursor = SQLITEDATABASE.query(this.demoTable, new String[] {this.name,
this.phone_number, this.subject},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private void displayListView()
{
Cursor cursor= fetchAllItems();
//The desired columns to be bound
String[] columns=new String[]{
this.name,
this.phone_number,
this.subject
};
//The XML defined views which the data will be bound to
int[] to = new int[] {
R.id.name,
R.id.phone_number,
R.id.subject,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
}

Related

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.

SQLite database in android studio, second activity is returning an empty table

i have searched all over but no answer is working in my case, i am developing an app where i need to have:
a database
an activity that imports a csv file into that database and displays
it in a ListView
and another activity that onClick of a button runs a cursor on the
values of one column in that database and compares it to a string and
as a result returns a toast that says a match has been found.
I have a DBController class that extends SQLiteOpenHelper and when i call this class in the other activities, it connects perfectly well in the first activity, it imports the csv file and displays it in the listview, but in the second activity its not doing anything, i don't know if the problem is that its not connecting or whether it's returning an empty table.
Here is my code:
DBController class:
package org.opencv.javacv.facerecognition;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public DBController(Context applicationcontext) {
super(applicationcontext, "classes.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS course1 ( Id INTEGER PRIMARY KEY, student_number TEXT UNIQUE, student_fn TEXT, student_ln TEXT, attended INTEGER DEFAULT 0, time_attended TEXT)";
database.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query;
query = "DROP TABLE IF EXISTS course1";
database.execSQL(query);
onCreate(database);
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> studentList;
studentList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM course1";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("student_number", cursor.getString(1));
map.put("student_fn", cursor.getString(2));
map.put("student_ln", cursor.getString(3));
map.put("attended", cursor.getString(4));
map.put("time_attended", cursor.getString(5));
studentList.add(map);
} while (cursor.moveToNext());
}
return studentList;
}
}
DBActivity which imports csv file and displays it in listview:
package org.opencv.javacv.facerecognition;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class DBActivity extends ListActivity {
TextView lbl;
DBController controller = new DBController(this);
Button btnimport;
ListView lv;
final Context context = this;
ListAdapter adapter;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database_view);
lbl = (TextView) findViewById(R.id.txtresulttext);
btnimport = (Button) findViewById(R.id.btnupload);
lv = getListView();
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("gagt/sdf");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity can handle picking a file. Showing alternatives.");
}
}
});
myList= controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(DBActivity.this, myList,
R.layout.v, new String[]{"student_number", "student_fn", "student_ln" , "attended" , "time_attended"}, new int[]{
R.id.studentnumber, R.id.studentfn, R.id.studentln, R.id.attended, R.id.timeattended});
setListAdapter(adapter);
lbl.setText("");
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "course1";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransactionNonExclusive();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 5); // defining 3 columns with null or blank field //values acceptance
//Id, Company,Name,Price
String student_number = str[0].toString();
String student_fn = str[1].toString();
String student_ln = str[2].toString();
String attended = str[3].toString();
String time_attended = str[4].toString();
contentValues.put("student_number", student_number);
contentValues.put("student_fn", student_fn);
contentValues.put("student_ln", student_ln);
contentValues.put("attended", attended);
contentValues.put("time_attended", time_attended);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
// db.endTransaction();
}
} else {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
// db.endTransaction();
}
db.close();
}
myList= controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(DBActivity.this, myList,
R.layout.v, new String[]{"student_number", "student_fn", "student_ln" , "attended" , "time_attended"}, new int[]{
R.id.studentnumber, R.id.studentfn, R.id.studentln, R.id.attended, R.id.timeattended});
setListAdapter(adapter);
lbl.setText("Data Imported");
}
}
}
And here is how im comparing a string to a column in the table in the second class (this is just a part of the activity):
first i added this at the top:
DBController controller = new DBController(this);
String number = "200910772";
and here is the onClick code in the onCreate method:
buttonSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String query = "SELECT * FROM course1 WHERE student_number=" + number;
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Toast.makeText(getApplicationContext(), "match found!", Toast.LENGTH_LONG).show();
cursor.moveToNext();
}
}
}
});
I just can't figure out what the problem might be..
I'm rather new in android so any help will be highly appreciated.
I solved it, it was a silly mistake really, the csv file when imported was putting double quotations around the text, so a match was never being found because it was considering the double quotations to be part of the string. Once removed a matched was found.

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);

Repeated data in my spinner and ListView

I have a problem receiving data from my database. As determined in my codes, my database (TBL_MAHRIE) contains three columns (ID , COL_SAL , COL_NERKH). Running my project, I received repeated data in both of spinner and ListView.
Mahrie.java (MY SPINNER LOAD HERE)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Mahrie extends Activity {
private Spinner spinner_sal1, spinner_sal2;
private Button btn_calc;
EditText ed_shakhes_Nekah, ed_shakhes_Motalebe;
TextView tv_res;
float shakhes_Nekah, shakes_Motalebe, final_Res;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie);
ed_shakhes_Motalebe = (EditText) findViewById(R.id.ed_shakhes_Motalebe);
ed_shakhes_Nekah = (EditText) findViewById(R.id.ed_shakes_Nekah);
tv_res = (TextView) findViewById(R.id.tv_res);
// DATABASE
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("1392", "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("1391", "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("1390", "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("1389", "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("1388", "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("1387", "25");
databaseAdapter.insertShakhes(shakhes6);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
List<String> list = new ArrayList<String>();
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
List<Shakhes> data_shakhes = null;
data_shakhes = databaseAdapter.getAllShakhes();
Context context = getApplicationContext();
for (int i = 0; i < data_shakhes.size(); i++) {
list.add((data_shakhes.get(i).getSal()));
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_sal2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner_sal1 = (Spinner) findViewById(R.id.spinner_Sal1);
spinner_sal1
.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner_sal1 = (Spinner) this.findViewById(R.id.spinner_Sal1);
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
btn_calc = (Button) findViewById(R.id.btn_calc);
btn_calc.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shakhes_Nekah = Float.parseFloat(ed_shakhes_Nekah.getText()
.toString());
shakes_Motalebe = Float.parseFloat(ed_shakhes_Motalebe
.getText().toString());
final_Res = shakes_Motalebe / shakhes_Nekah;
tv_res.setText(final_Res + "");
}
});
}
}
2.DataBase Handler.java
package ir.dadpardaz.mahrie_dadpardaz;
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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ToggleButton;
public class DataBaseHandler {
SQLiteDatabase database;
public DataBaseHandler(Context context) {
ShakhesDatabaseOpenHelper shakhesDatabaseOpenHelper = new ShakhesDatabaseOpenHelper(
context, "shakhsdb.db", null, 1);
database = shakhesDatabaseOpenHelper.getWritableDatabase();
}
public class ShakhesDatabaseOpenHelper extends SQLiteOpenHelper {
public ShakhesDatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
String query = "create table IF NOT EXISTS TBL_MAHRIE (ID INTEGER PRIMARY KEY, COL_SAL TEXT, COL_NERKH TEXT)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
}
}
public long insertShakhes(Shakhes shakhes) {
ContentValues values = new ContentValues();
values.put("COL_SAL", shakhes.getSal());
values.put("COL_NERKH", shakhes.getNerkh());
return database.insert("TBL_MAHRIE", null, values);
}
boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen()) {
return false;
}
Cursor cursor = db
.rawQuery(
"SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?",
new String[] { "table", tableName });
if (!cursor.moveToFirst()) {
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
Shakhes p = new Shakhes();
if (c.moveToFirst()) {
do {
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
Mahrie_JadvalActivity (My ListView inflate here)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Mahrie_JadvalActivity extends Activity {
ListView personListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie__jadval);
personListView = (ListView) findViewById(R.id.personListView);
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("2392" , "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("2391" , "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("2390" , "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("2389" , "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("2388" , "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("2387" , "25");
databaseAdapter.insertShakhes(shakhes6);
List<Shakhes> shakhes =
databaseAdapter.getAllShakhes() ;
ShakhesListViewAdapter shakhesListViewAdapter = new ShakhesListViewAdapter(this, R.layout.mahrie_list_view_item, shakhes);
personListView.setAdapter(shakhesListViewAdapter);
}
public class ShakhesListViewAdapter extends ArrayAdapter<Shakhes> {
List<Shakhes> data;
Context context;
public ShakhesListViewAdapter(Context context, int resourceId, List<Shakhes> data) {
super(context, resourceId, data);
this.data = data;
this.context = context;
}
#Override
public View getView(final int position, View item, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
item = inflater.inflate(R.layout.mahrie_list_view_item, parent , false);
TextView familyTextView = (TextView) item.findViewById(R.id.familyTextView);
familyTextView.setText(data.get(position).getSal()) ;
//familyTextView.setTypeface(bYekan);
TextView nameTextView = (TextView) item.findViewById(R.id.nameTextView);
nameTextView.setText(data.get(position).getNerkh()) ;
//nameTextView.setTypeface(bYekan);
Button detailsButton = (Button) item.findViewById(R.id.detailsButton);
detailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,
// data.get(position).getSal() + " " + data.get(position).getNerkh(),
// Toast.LENGTH_LONG).show();
Toast.makeText(context,
data.size()+"" + " and ID is " + position + "" ,
Toast.LENGTH_LONG).show();
}
});
//item.startAnimation(animation);
return item;
}
} }
4.Shakhes.java
package ir.dadpardaz.mahrie_dadpardaz;
public class Shakhes {
public int id ;
public static String sal ;
public static String nerkh ;
public Shakhes(int id, String sal, String nerkh) {
super();
this.id = id;
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes(String sal, String nerkh) {
super();
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getNerkh() {
return nerkh;
}
public void setNerkh(String nerkh) {
this.nerkh = nerkh;
}
}
Inside your DataBaseHandler.java , Make the following change
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
if (c.moveToFirst()) {
do {
Shakhes p = new Shakhes();
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
code the line Shakhes p = new Shakhes(); inside do-while loop. Otherwise it will overwrite the old one, and the same will be added in arraylist.

Cant validate Login on Android app using a SQLite db

I am having a problem validating my login for my android app. I have 2 fields that require user to enter email and password, if both exist in db then they will be taken to mainscreen (log in successful) if incorrect error will appear. I have tried everything but still doesnt work! Please help I have posted my code below.
package com.example.finalproject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener{
EditText mEmailAdd;
EditText mPassword;
private SQLiteAdapter mydb = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogMain:
mEmailAdd = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mEmailAdd.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, LoginActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteAdapter db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
DATABASE CLASS
package com.example.finalproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "MY_PROJECT_DATABASE";
public static final String MYDATABASE_TABLE = "MY_USERS_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_EMAIL + " text not null, "
+ KEY_PASSWORD + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String name, String email, String password){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_EMAIL, email);
contentValues.put(KEY_PASSWORD, password);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_NAME, KEY_EMAIL,KEY_PASSWORD};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
not your error, but change
if(uname.equals("") || uname == null){ // throws nullpointerexception if uname == null
to
if(uname == null || uname.length() == 0 ){ // throws no exception and also checks the " "
Not sure if this was just a copy-paste error but the code as provided not only doesn't compile, but never sets up the click listener for the login button either. Here's what I modified to make it both compile and query the database.
In SQLiteAdapter:
public SQLiteDatabase openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return sqLiteDatabase;
}
In LoginActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteDatabase db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
Note also that this code will never insert anything into the database, either. I assume this will be done elsewhere. Further there are many naming convention and general good practices being broken here.
A few issues:
Never do database work on the main thread.
Variables prefixed with 'm' indicate they are member variables of the class.
Be sure to use the #Override notation when appropriate.

Categories