Verifying username and password in SQLite - android

I'm creating a login connected to SQLite in an Android Studio. I want to proceed to my second activity if the username and the password are correct (Of course both are stored in the database). The users can be added from my admin page, which is working fine. How can I check if the username and the password are stored in database?
Here is my code so far:
Main Activity:
package com.example.schoolapp;
import android.content.Intent;
import android.se.omapi.Session;
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.TextView;
import android.widget.Toast;
import com.example.schoolapp.Admin.DBHelper;
import com.example.schoolapp.Admin.ThirdActivity;
import com.example.schoolapp.Eleve.SecondActivity;
public class MainActivity extends AppCompatActivity {
DBHelper SchoolAppDB;
//Initialisation des variables
private EditText Name;
private EditText Password;
private Button Login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Mise en relation des variables a leurs correspondants dans le fichier XML par leur ID
Name = (EditText) findViewById(R.id.etNewName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//getting Edit Text values and stores it into string
String username = Name.getText().toString();
String password = Password.getText().toString();
//check authorized user or not
if (SchoolAppDB.checkUser(username, password)) {
Intent intent =new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Login Successfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong Username or Password", Toast.LENGTH_LONG).show();
}
}
});
}
}
DBHelper checkUserLogin method :
public boolean checkUserLogin(String username,String password){
SQLiteDatabase db=this.getWritableDatabase();
String Query = "select USER_NAME, USER_PASSWORD from USER where USER_NAME='"+ username +"' and USER_PASSWORD='"+ password+"'";
Cursor cursor = null;
try {
cursor = db.rawQuery(Query, null);//raw query always holds rawQuery(String Query,select args)
} catch (Exception e) {
e.printStackTrace();
}
if(cursor!=null && cursor.getCount()>0){
cursor.close();
return true;
}
else{
cursor.close();
return false;
}
}

You are likely getting a null-pointer exception as you don't appear to have instantiated SchoolAppDB.
I'd suggest changing :-
setContentView(R.layout.activity_main);
to be :-
setContentView(R.layout.activity_main);
SchoolAppDB = new DBHelper(this); //<<<<<<<<<< assuming the DBHelper constructor only requires the Context.
I believe you then want if (SchoolAppDB.checkUserLogin(username, password)) { rather than if (SchoolAppDB.checkUser(username, password)) {.
Additional
Directly placing user inputted data into SQL makes the App open to SQL Injection.
Checking a Cursor for null, when the Cursor is returned from an SQliteDatabase method such as rawQuery, is useless. The Cursor will never be null, if there are no rows returned it will be empty.
It is inadvisable to place calls to SQLiteDatabase methods in try/catch clauses as a serious issue could be hidden.
There are convenience methods, for commonly used SQL, that make life easier than using rawQuery and execSQL. They build the underlying SQL, the protect against SQL Injection (rawQuery also does if you use the 2nd parameter to provide a String[] of the arguments to replace ? placehoders).
As such it is suggested that you consider the following checkUserLogin method which utilises the query convenience method :-
public boolean checkUserLogin(String username,String password){
SQLiteDatabase db=this.getWritableDatabase();
String whereclause = "USER_NAME=? and USER_PASSWORD=?"; //<<<<<<<<<< ?'s will be replaced according to whereargs on a 1 by 1 basis
String[] whereargs = new String[]{username,password};
Cursor cursor = db.query(
"USER",
new String[]{"USER_NAME","USER_PASSWORD"},
whereclause,
whereargs,
null,null,null
);
int count = cursor.getCount();
cursor.close();
return count > 0;
}

Related

How to add row dynamically in table layout or How to show full db Records in single table Layout

Hello Techie :) i am new to android . i'm developing one app where user is registering with all personal detail and mobile device detail and after user login all the things working fine and met with result but when i'm moving to admin section here i have issue and i'm not getting any idea about this .
Parts of Admin section where i am stuck :-
1) after admin login , all table records should be shown in one table layout here u can say i want to populate all table records in Table Layout .
i try with specific user name and its showing in the table layout but it's not my requirement , i have to show all users in Table layout .
i'm sharing my code here , will u all suggest me what to do next and how can i achieve my requirement.
Thanks for your valuable time :)
//MainActivity.java
package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.VectorEnabledTintResources; import android.telephony.TelephonyManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;
/** * Created by yadapras on 6/26/2016. */ public class MainActivity extends AppCompatActivity {
EditText a,b;
String usr,pass;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v)
{
if (v.getId() == R.id.BLogin)
{
a = (EditText)findViewById(R.id.userName);
usr = a.getText().toString();
b = (EditText)findViewById(R.id.userPassword);
pass = b.getText().toString();
String password = null;
if( a.getText().toString().length() == 0 || usr == "" || usr == null)
a.setError( " User name is required!" );
if( b.getText().toString().length() == 0 || pass =="" || pass == null)
b.setError( "Password is required!" );
else{
password = helper.searchPass(usr);
}
if (a.getText().toString().equals("admin") && b.getText().toString().equals("admin"))
{
Intent intent = new Intent(getApplicationContext(), AdminDisplay.class);
startActivity(intent);
}else{
if (pass.equals(password) && password != null) {
Intent intent = new Intent(getApplicationContext(), EmpDetail.class);
intent.putExtra("usr", usr);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String uid = telephonyManager.getDeviceId();
String manufacturer = Build.MANUFACTURER; // Not used in current scenario
String model = Build.MODEL;
int version = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE; // not used in current scenario
String msg = "IMEI No: " + uid + "\n" + "Manufacturer is :" + manufacturer + "\n" + "Model is :" + model + "\n" + "Os Version is :" + version + "\n" + "VersionRelease is :" + versionRelease;
Toast toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG);
toast.show();
Register r = new Register();
r.setImei_no(uid);
r.setDev_model(model);
r.setOs_version(version);
r.setUname(usr);
helper.updateTable(r); /*For updating table with new Coloumn*/
startActivity(intent);
}
else
{
Toast err_pass = Toast.makeText(MainActivity.this,"UserName and Password don't Match",Toast.LENGTH_SHORT);
err_pass.show();
}
}
}
if (v.getId() == R.id.BSignup)
{
Intent intent = new Intent(getApplicationContext(), Registration.class);
startActivity(intent);
}
}
}
//DatabaseHelper.java
package com.example.yadapras.mobiltyemp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.ArrayMap;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by yadapras on 7/8/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "registrationDB.db";
public static final String TABLE_NAME = "registrations";
public static final String COLUMN_ID = "id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD= "password";
public static final String COLUMN_RE_PASSWORD= "re_password";
public static final String COLUMN_NAME= "name";
public static final String COLUMN_EMAIL= "email";
public static final String COLUMN_PHONE_NO= "phone_no";
/*Adding three coloumn IMEI_NO,OS_Version,Model_Device Respectively*/
public static final String COLUMN_IMEI_NO = "imei_no";
public static final String COLUMN_DEV_MODEL = "dev_model";
public static final String COLUMN_OS_VERSION = "os_version";
SQLiteDatabase sqLiteDatabase;
private static final String TABLE_CREATE = "create table registrations(id integer primary key not null, " +
"username text not null, password text not null, re_password text not null, name text not null, email text not null," +
"phone_no number not null,imei_no text, dev_model text, os_version text);";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
this.sqLiteDatabase=sqLiteDatabase;
Log.d("#####Table Value",TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS " +TABLE_NAME ;
sqLiteDatabase.execSQL(query);
this.onCreate(sqLiteDatabase);
}
public void registerUser(Register r) {
/*Inserting anything in to the dataBase make sure it should be writable*/
sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
int count = cursor.getCount();
Log.d("##count",""+count);
values.put(COLUMN_ID,count);
Log.d("##id",r.getUname());
values.put(COLUMN_USERNAME,r.getUname());
values.put(COLUMN_PASSWORD,r.getPassword());
values.put(COLUMN_RE_PASSWORD,r.getRe_password());
values.put(COLUMN_NAME,r.getName());
values.put(COLUMN_EMAIL, r.getEmail());
values.put(COLUMN_PHONE_NO, r.getPhone_no());
sqLiteDatabase.insert(TABLE_NAME, null,values); /*this will insert Register object in to the Database*/
sqLiteDatabase.close();
}
public String searchPass(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query = "select username,password from "+TABLE_NAME;
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
String a,b ; // a and b will be userName and Password respectively
b = "Not Found";
if (cursor.moveToFirst())
{
do {
a = cursor.getString(0);
Log.d("##username from db",a);
if (a.equals(usr))
{
b = cursor.getString(1);
break;
}
}while (cursor.moveToNext());
}
return b;
}
public JSONObject showDetail(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
// String query = "SELECT * FROM registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
public void updateTable(Register r) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
db.update(TABLE_NAME,cv,"username = ?",new String[]{r.getUname()});; /*Working for all fields*/
/*SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
String updateQuery = "Update registrations set " + COLUMN_IMEI_NO + " = '"+ r.getImei_no() +"' where " + COLUMN_USERNAME + "="+"'"+ r.getUname() +"'";
db.execSQL(updateQuery);
db.close();*/
}
}
//AdminDisplay.java
package com.example.yadapras.mobiltyemp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class AdminDisplay extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
TextView id,name,email,mobileno,imei_no,dev_model ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
TableLayout table = (TableLayout)findViewById(R.id.tableLayout1) ;
id = (TextView)findViewById(R.id.admin_usr_id);
name = (TextView)findViewById(R.id.admin_Uname);
email = (TextView)findViewById(R.id.admin_usr_email);
mobileno = (TextView)findViewById(R.id.admin_usr_phone);
imei_no = (TextView)findViewById(R.id.admin_usr_imeiNo);
dev_model = (TextView)findViewById(R.id.admin_usr_dev_model);
JSONObject details = helper.showDetail("pcu9044"); // ***Here i'm trying registered user so i'm getting only this user field in TableLayout .***
for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);
try {
table.removeView(row);
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i'm attaching screen shot of my output, if yup people have nay doubt please feel free to ask . Thank u in advance .
Result output with my code
The problem that I see here is that when you say:
"i try with specific user name and its showing in the table layout but
it's not my requirement , i have to show all users in Table layout".
By searching for one single user from the database, you are only retrieving a single record in the database that is associated with the username you are searching for. Your method helper.showDetail() returns a single JSONObject - this object corresponds to the record in the database where username = pcu9044.
If I am understanding your situation correctly, you need to call a method that selects ALL of the records from the database in order to display what you want on the screen. Your helper.showDetail() will be a good start, but you can modify code slightly to achieve what you'd like.
I would recommend using either a list or array of JSONObjects instead of a single JSONObject. Initialize your data structure before you enter the if (cursor.moveToFirst()) conditional (like you have it now), but within each iteration of the loop, you create a new object, fill it with what the cursor returns for that row, and then add it to the structure. The code would look something like this:
public JSONArray showDetail() {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations";// * THIS WILL RETURN ALL RECORDS IN REGISTRATIONS
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
//JSONObject data = new JSONObject(); *change this to an array
JSONArray data = new JSONArray();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
// Must create a new object each time you iterate to a new row to add to the array
JSONObject record = new JSONObject();
for (int idx=0; idx<columnsQty; ++idx) {
try {
// Fill the object
record.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
// Add the object to the array and repeat
data.put(record);
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
If you do it this way, your helper.showDetail() will return an array filled with objects that each symbolize a row. From there, your AdminDisplay.java should then cycle through the array, grab each object, and fill a new row with the information you need.
Hope this helps!
Hello Techie :) I solved my problem after reading many articles on Table Layout over Internet. i'm giving this problems solution with Table-Layout hope this will help others .
AdminDisplay.java # Editable Version
package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class AdminDisplay extends AppCompatActivity {
TableLayout tableLayout;
private SQLiteDatabase db;
private Context context ;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
context = this;
DatabaseHelper helper = new DatabaseHelper(this);
tableLayout = (TableLayout)findViewById(R.id.tableLayout1) ;
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText={"ID","USERNAME","EMAIL","PHONE_NO","IMEI_NO","DEV_MODEL"};
for(String c:headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
SQLiteDatabase db = helper.getReadableDatabase();
db.beginTransaction();
try
{
String selectQuery = "SELECT * FROM "+ DatabaseHelper.TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.getCount() >0)
{
while (cursor.moveToNext()) {
// Read columns data
int id = cursor.getInt(cursor.getColumnIndex("id"));
String user_name= cursor.getString(cursor.getColumnIndex("username"));
String email= cursor.getString(cursor.getColumnIndex("email"));
String phone_no = cursor.getString(cursor.getColumnIndex("phone_no"));
String imei_no = cursor.getString(cursor.getColumnIndex("imei_no"));
String dev_model = cursor.getString(cursor.getColumnIndex("dev_model"));
// dara rows
TableRow row = new TableRow(context);
row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] colText={id+"",user_name,email,phone_no,imei_no,dev_model};
for(String text:colText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(text);
row.addView(tv);
}
tableLayout.addView(row);
}
}
db.setTransactionSuccessful();
}
catch (SQLiteException e)
{
e.printStackTrace();
}
finally
{
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
}
Remove table.removeView(row); from the loop, if not you will get only one row at the end of the loop as it removes the previous row when a new row is added
for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);
try {
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}
}
Hi try this method i have just updated a method of your code, You can replace with your own method by.
Valiable isAdmin is true when admin get detail and false when user.
public JSONObject showDetail(String usr, boolean isAdmin)
{
sqLiteDatabase = this.getReadableDatabase();
String query = "";
if (isAdmin)
query = "SELECT * FROM registrations";
else
query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {
int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}
}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}
It may help you and Let me know if any query you have.

(1) near null syntax error

04-24 12:15:21.671: E/AndroidRuntime(26419):java.lang.RuntimeException: Unable to start activity ComponentInfo{com.flocator/com.flocater.Friendfinderactivity}:android.database.sqlite.SQLiteException: near "null": syntax error(code 1): , while compiling: select * from null
This is the error I am getting every time I am trying to compile..I am a learning android so I don't know much about this...so can anyone help me to fix this issue..
and I am also getting error Source not found
so can you help me to sort out with these two problems.
The codes are In Friendfnderactivity.java
package com.flocater;
import com.flocator.R;
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.telephony.TelephonyManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Friendfinderactivity extends Activity {
/** Called when the activity is first created. */
public static String deviceid = "deviceid";
public static String device_id = "device_id";
public static String user_id = "user_id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBHelper dbhelper = new DBHelper(this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
TelephonyManager tm = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
deviceid = tm.getDeviceId();
Cursor cursor = db.rawQuery("select * from "
+ Database.SUBSCRIBE_TABLE_NAME, null);
int rows = cursor.getCount();
if (rows > 0) {
cursor.moveToFirst();
user_id = cursor.getString(0);
device_id = cursor.getString(3);
}
db.close();
if (device_id.equals(deviceid)) {
setContentView(R.layout.subscriber);
} else
setContentView(R.layout.subscribe);
}
public void subscribeUser(View v) {
// get access to views
EditText editName = (EditText) this.findViewById(R.id.editName);
EditText editPhone = (EditText) this.findViewById(R.id.editPhone);
EditText editArea = (EditText) this.findViewById(R.id.editArea);
EditText editCity = (EditText) this.findViewById(R.id.editCity);
boolean done = Database.addUser(this, editName.getText().toString(),
editPhone.getText().toString(), deviceid, editArea.getText()
.toString(), editCity.getText().toString());
if(done) {
Toast.makeText(this, "Subscribed Successfully!", Toast.Length_Long).show();
Intent intent = new Intent(this,Friendfinderactivity.class);
startActivity(intent);
}
else
Toast.makeText(this, "Sorry! Could not subscribe!", Toast.LENGTH_LONG).show();
}
public void addFriends(View v) {
Intent intent = new Intent(this,AddFriends.class);
startActivity(intent);
}
public void viewFriends(View v) {
Intent intent = new Intent(this,SeeFriends.class);
startActivity(intent);
}
}
The error is clear "select * from null" That is your SQL query
Here the table name is null.
You just needs to add the table name.
For example
replace the following line with
Cursor cursor = db.rawQuery("select * from "
+ Database.SUBSCRIBE_TABLE_NAME, null);
this
Cursor cursor = db.rawQuery("select * from your_table_name", null);
I am just telling the error you modify for your need.

Passing cursor values to ArrayList

This is my problem: I have an SQLite DB set up to store some values. In this case, its pretty simple. Two columns (_id, name). I know data is getting stored in the database and I know the cursor I am using to pass that information is also populating. However, when I try to add a cursor value to an ArrayList, I get an error. This is the code for my problem method:
public void sqltest(LDatabase LConnector){
cursor = LConnector.getAllRecords(); //gets the cursor from my db
try{
cursor.moveToFirst();}
catch (Exception e){
log.i("Failed", "Couldn't moveToFirst"); //I get a successful moveToFirst
}
while(cursor.moveToNext()){
try{
getWork.add(cursor.getString(cursor.getColumnIndex("name")));
} catch (Exception h){
Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
}
}
I set up that last log to tell me the value of the cursor at that position. The values entered for the DB always print out so I know the cursor is being populated. Anyone have any idea what I am doing wrong here?
EDIT: LogCat shows these two lines after this is called when an activity starts:
04-12 23:26:26.606: I/MOVED(9478): MOVED TO FIRST
04-12 23:26:26.606: I/FAILED(9478): test1
There are no more verbose errors that describe it better, that is why I am so confused. It just doesn't get stored to the AssetList at all.
This is the code for the getAllRecords() mehod:
public Cursor getAllLifts() throws SQLiteException
{
open();
return database.rawQuery("SELECT * FROM contacts"+";", null);
}
Additionally, here is the create code + the code used for inserting:
Create:
String createQuery = "CREATE TABLE contacts" +
"(_id auto_increment integer primary key," +
"name text);";
db.execSQL(createQuery); // execute the query
Insert:
open(); // open the database
try{
//add more later to get data to insert from usr, just for testing
database.execSQL("INSERT INTO contacts(name) VALUES('test1')");
database.execSQL("INSERT INTO contacts(name) VALUES('test2')");}
catch (Exception insert){
Log.i("INSERT", "INSERT FAILED");
}
close(); // close the database
EDIT: rest of the activity w/ imports
package com.jydev.llogger2;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.database.Cursor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity implements OnClickListener {
Button buttonNext; //continue button
Button buttonBack; //back button
EditText nameEditText; //editText w/ workout name
EditText commentEditText; //editText w/ comments
Intent info; //intent used to pass extras
String wName = null;
String wComments = null;
ArrayList<String> getWork;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
commentEditText = (EditText)findViewById(R.id.commentEditText);
buttonBack = (Button)findViewById(R.id.create_back);
buttonNext = (Button)findViewById(R.id.create_continue);
nameEditText = (EditText)findViewById(R.id.nameEditText);
LtDatabase LConnector = new LDatabase(this);
LConnector.insert();
sqltest(LConnector);
}
There are several wrong things. First moveToFirst() returns a boolean so you will never get an exception thrown. Second the while statement will skip one row since you call moveToNext(), thus the first row is skipped. Finally, you get an exception because you did not initialize getwork.
public void sqltest(LDatabase LConnector)
{
cursor = LConnector.getAllRecords(); //gets the cursor from my db
if (cursor.moveToFirst())
{
do
{
try{
getWork.add(cursor.getString(cursor.getColumnIndex("name")));
} catch (Exception h){
Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
}
while (cursor.moveToNext());
}
}
}
In your declaration of getWork
ArrayList<String> getWork = new ArrayList<String>();
for my queries i'm using the following
public ArrayList<T> findAllBy(String selection) {
final SQLiteDatabase db = HELPER.getReadableDatabase();
final ArrayList<T> result = new ArrayList<T>();
final Cursor cursor = db.query(TABLE_NAME, SELECTED_COLS, WHERE, null, null, null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
T model = CREATEOBJECT(cursor);
result.add(model);
cursor.moveToNext();
}
return result;
} finally {
cursor.close();
db.close();
}
}
Where:
HELPER is a instance extendes from SQLiteOpenHelper
TABLE_NAME is a string with the name of the table
SELECTED_COLS is a String[] array with the columns names i want get
WHERE is a string like "COL_NAME = 'value'" or null
CREATEOBJECT is a method for create Object of type T want in my ArrayList<T>
Example CREATEOBJECT
public T CREATEOBJECT(Cursor cursor) {
new T(
cursor.getInt(0), cursor.getString(1)
);
}
public class T {
private long id;
private String name;
T(int id, String name) {
this.id = id;
this.name = name;
}
//...
}

How to display data from hashmap in android?

I have a hashmap which i would like to display. The user will input a name into an editText and when they click the search button, it should go through the hashmap and show the entry that matches the text in edittext with the key.
HashMap<String, Staff> h = new HashMap<String, Staff>();
Staff staff = new Staff("Thomas", "133", "thomas133#email.com");
h.put("Thomsas", staff);
I have tried to adapt the notepad app
package android;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.project.R;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
public class SingleStaff extends ListActivity {
private DBAdapter mDbHelper;
private EditText staffName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchstaff);
staffName = (EditText) findViewById(R.id.staffname);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
registerForContextMenu(getListView());
Button search = (Button) findViewById(R.id.confirm);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a = staffName.getText().toString();
fillData(a);
}
});
}
private void fillData(String staffName) {
Cursor notesCursor = mDbHelper.fetchSingleStaff(staffName);
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{ DBAdapter.STAFF_NAME, DBAdapter.STAFF_ROOM, DBAdapter.STAFF_EMAIL};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1, R.id.text2, R.id.text3};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.note_row_staff, notesCursor, from, to);
setListAdapter(notes);
}
}
When i run the application and have typed in for example "Thomas" in the edittext and clicked search i get an error message,
android.database.sqlite.SQLiteException: no such column: Thomas: , while compiling: SELECT
DISTINCT _id, name, room, email FROM staff WHERE name=Thomas
You can change your query line to (notice the single quote around staffName:
Cursor mCursor = mDb.query(true, STAFF_TABLE, new String[] {STAFF_ROWID, STAFF_NAME, STAFF_ROOM, STAFF_EMAIL}, STAFF_NAME + "='" + staffName + "'", null, null, null, null, null);
It is better to use ? placeholders to avoid that kind of problem (untested)
public Cursor fetchSingleStaff(String staffName) throws SQLException {
String[] arg = new String[] { staffName };
Cursor mCursor = mDb.query(true, STAFF_TABLE, new String[] {STAFF_ROWID, STAFF_NAME, STAFF_ROOM, STAFF_EMAIL}, STAFF_NAME + "=?", arg , null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
If you want to use a map, you can overload the above method and set the staffName with the corresponding value in your map
public Cursor fetchSingleStaff(Map<String, Staff> m) throws SQLException {
return fetchSingleStaff(m.getFirstName); // m.getFirstName() should be mapped the `Thomas` in `Staff` - Update according to your implementation
}

Using SQlite to validate Logins in Android

I'm trying to create a Log in screen for an app in Android. I have stored information about users in a 'users' table in a database.
I'm trying to match the username and password entered at the log in screen with the values in the database using the cursor object but it doesnt work , causing the app to crash.
Can someone please recommend or revise the approach, if possible with some code snippets.
Will appreciate it big time, thanks.
Below is the code for the LoginForm class. (it uses a DBAdapter class to connect to the database)
package com.androidbook.LoginForm;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginForm extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DBAdapter db = new DBAdapter(getBaseContext());
final AutoCompleteTextView username = (AutoCompleteTextView)this.findViewById(R.id.AutoComUsernameLogin);
final AutoCompleteTextView password = (AutoCompleteTextView)this.findViewById(R.id.AutoComPasswordLogin);
Button Register = (Button) findViewById(R.id.ClicktoRegister);
Register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), RegistrationForm.class);
startActivityForResult(myIntent, 0);
}
});
//************************** LOG IN LOGIC******************************//
Button Login = (Button) findViewById(R.id.LoginButton);
Login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String Username = username.getText().toString();
final String Password= password.getText().toString();
db.open();
Cursor c = db.getAllTitles();
while(c.moveToNext())
{
String c1=c.getString(2);
String c2=c.getString(3);
if(c1 == Username)
{
if(c2 == Password)
{
Toast.makeText(LoginForm.this,
"You are succesfully logged in.",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(view.getContext(), Menu.class);
startActivityForResult(myIntent, 0);
}
else
{
Toast.makeText(LoginForm.this, "Incorrect password",Toast.LENGTH_LONG).show();
}
Intent myIntent = new Intent(view.getContext(), LoginForm.class);
startActivityForResult(myIntent, 0);
}
else
Toast.makeText(LoginForm.this, "Incorrect",Toast.LENGTH_LONG).show();
}
db.close();
}
});
}
}
The answer by Chirag Raval above functions but is vulnerable to SQL injection. A malicious user could easily bypass the authentication mechanism with a basic SQLi payload (as long as there were at least a single entry in the database being checked against).
A parameterized query with bounded values is the more secure approach.
Fixing the code snippet:
public int Login(String username,String password)
{
String[] selectionArgs = new String[]{username, password};
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username=? and password=?", selectionArgs);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}
This simple improvement is more secure and easier to code.
You can make one function in database class that will return the int number . if integer number is 1 then we can say that the user name and password is match other wise we can say login failed . There is no need to write complex code.
public int Login(String username,String password)
{
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username =" + "\""+ username.trim() + "\""+" and password="+ "\""+ password.trim() + "\""+, null);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}
When we try this code it asks to change type to boolean...
public int Login(String username,String password)
{
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username =" + "\""+ username.trim() + "\""+" and password="+ "\""+ password.trim() + "\""+, null);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}

Categories

Resources