Check if value entered exists in database android - java

I want to check if the Username&Password that the user entered exists in the database
I have tried this code, but i don't get it how to work with the cursor and what I'm doing wrong.
package com.example.nir.nestleapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 org.w3c.dom.Text;
import java.util.ArrayList;
public class LoginActivity extends AppCompatActivity {
MyDBHandler Newdb;
private SQLiteDatabase _database = null;
private MyDBHandler _dbHelper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Newdb = new MyDBHandler(this);
_dbHelper = new MyDBHandler(getApplicationContext());
_database = this.openOrCreateDatabase(MyDBHandler.DATABASE_NAME, MODE_PRIVATE, null);
SQLiteDatabase database=_dbHelper.getReadableDatabase();
final ArrayList list = new ArrayList();
final TextView RegisterPage=(TextView)findViewById(R.id.textView4);
TextView Text1=(TextView)findViewById(R.id.textView3);
Button Login=(Button)findViewById(R.id.LoginBtn);
Button GuestLogin=(Button)findViewById(R.id.LoginGuestBtn);
final EditText LoginUser=(EditText)findViewById(R.id.LoginUser);
final EditText LoginPass=(EditText)findViewById(R.id.LoginPassword);
RegisterPage.setTextSize(17);
Text1.setTextSize(17);
RegisterPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
});
GuestLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,MainPageActivity.class));
}
});
Cursor c = database.rawQuery("SELECT * FROM " + MyDBHandler.Table_Name, null);
if (c == null) return;
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
list.add(c.getString(0));
list.add(c.getString(1));
c.moveToNext();
}
}
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(LoginUser.getText().toString().isEmpty()||LoginPass.getText().toString().isEmpty())
{
Toast.makeText(LoginActivity.this, "", Toast.LENGTH_SHORT).show();
}
if(list.contains(LoginUser.getText().toString())&&list.contains(LoginPass.getText().toString()))
{
Toast.makeText(LoginActivity.this, "!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainPageActivity.class));
}
else
{
Toast.makeText(LoginActivity.this, "wrong", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is my DBHelper:
package com.example.nir.nestleapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UsersTable.db";
public static final String Table_Name = "UsersTable";
public static final String KEY_User = "User";
public static final String KEY_Password = "Password";
public static final String KEY_FullName = "FullName";
public static final String KEY_PhoneNumber="PhoneNumber";
public static final String KEY_IDNUMBER="IDNumber";
public static final String[] DB_COL = new String[]{KEY_User,KEY_Password,KEY_FullName,KEY_PhoneNumber,KEY_IDNUMBER};
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CreateTableSql = "Create Table " + Table_Name + " ( " +
KEY_User + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
KEY_Password + " TEXT , " +
KEY_FullName + " TEXT , "+
KEY_PhoneNumber+" TEXT , "+
KEY_IDNUMBER+ " ) ";
db.execSQL(CreateTableSql);
}#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table_Name);
onCreate(db);
}
public void Add(UserTable NewUser) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_User,NewUser.GetUserName() );
values.put(KEY_Password, NewUser.GetPassword());
values.put(KEY_FullName,NewUser.GetFullName());
values.put(KEY_PhoneNumber,NewUser.GetPhoneNumber());
values.put(KEY_IDNUMBER,NewUser.GetID());
db.insert(Table_Name, null, values);
db.close();
}
}
Updated LoginActivity
package com.example.nir.nestleapp;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity {
MyDBHandler Newdb;
private SQLiteDatabase _database = null;
private MyDBHandler _dbHelper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Newdb = new MyDBHandler(this);
_dbHelper = new MyDBHandler(getApplicationContext());
_database = this.openOrCreateDatabase(MyDBHandler.DATABASE_NAME, MODE_PRIVATE, null);
final TextView RegisterPage=(TextView)findViewById(R.id.textView4);
TextView Text1=(TextView)findViewById(R.id.textView3);
Button Login=(Button)findViewById(R.id.LoginBtn);
Button GuestLogin=(Button)findViewById(R.id.LoginGuestBtn);
final EditText LoginUser=(EditText)findViewById(R.id.LoginUser);
final EditText LoginPass=(EditText)findViewById(R.id.LoginPassword);
RegisterPage.setTextSize(17);
Text1.setTextSize(17);
RegisterPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
});
GuestLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,MainPageActivity.class));
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(LoginUser.getText().toString().isEmpty()||LoginPass.getText().toString().isEmpty())
{
Toast.makeText(LoginActivity.this, "!", Toast.LENGTH_SHORT).show();
}
if(_dbHelper.getUserRow(LoginUser.getText().toString(),LoginPass.getText().toString())>0)
{
Toast.makeText(LoginActivity.this, "good!", Toast.LENGTH_SHORT).show();
HashMap<String,String> userInfo = _dbHelper.getUserInfo(LoginUser.getText().toString(),LoginPass.getText().toString());
Intent intent = new Intent(LoginActivity.this,MainPageActivity.class);
intent.putExtra("userInfo",userInfo);
startActivity(intent);
}
else
{
Toast.makeText(LoginActivity.this, "wrong", Toast.LENGTH_SHORT).show();
}
}
});
}
}

I think your problem is on your c.getString() in your whole loop. The first index should be ID and it might not be ID as well so the proper way is to using
c.getString(c.getColumnIndex("yourkey"));
Another tips try to not use rawQuery unless you really got no option. You could easily just do a check something like this.
Put this code inside your handler. It might have some syntax error you could try to fix it.
public int getUserRow(String username,String password){
SQLiteDatabase db = this.getReadableDatabase();
String[] column = {"id"};
Cursor cursor = db.query(handler.TABLE_USER,column,"User = ? AND Password = ?",new String[]{username,password},null,null,null);
int row = cursor.getCount();
return row;
}
When you check for login just simply so you don't have actually get the all user from the database to check wether this user is actually exists.
if(_dbHelper.getUserRow(yourUsername,yourPassword)){
//Login here
}
One more thing try to keep all database related code inside database class which it is very good pratice and you won't get any confusion after looking back the code.
Updated:
Here is the code when you wan to get the login user info add it inside your database helper as well you need to edit the column to match your column
public HashMap<String,String> getUserInfo(String username,String password){
HashMap<String,String> user = new HashMap<String,String>();
SQLiteDatabase db = this.getReadableDatabase();
String[] column = {"usernam","password","rest","of","your","key"};
Cursor cursor = db.query(handler.TABLE_USER,column,"User = ? AND Password = ?",new String[]{username,password},null,null,null);
int usernameIndex = cursor.getColumnIndex("username");
int passwordIndex = cursor.getColumnIndex("password");
int restIndex = cursor.getColumnIndex("rest");
int ofIndex = cursor.getColumnIndex("of");
int keyIndex = cursor.getColumnIndex("key");
if(cursor.getCount() > 0){
user.put("username",cursor.getString(usernameIndex));
user.put("password",cursor.getString(passwordIndex));
user.put("username",cursor.getString(restIndex));
user.put("of",cursor.getString(ofIndex));
user.put("key",cursor.getString(keyIndex));
}
return user;
}
So in your if statement try to add this. This code basically help you get user data and pass all the data to your user info activity.
if(_dbHelper.getUserRow(yourUsername,yourPassword)){
HashMap<String,String> userInfo = _dbHelper.getUserInfo(username,password);
Intent intent = new Intent(yourContext,YourActivity.class);
intent.putExtra("userInfo",userInfo);
startActivity(intent);
}
So now you pass all the data to the other activity you could grab it inside your onCreate.
userInfo = (HashMap<String, String>) getIntent().getSerializableExtra("userInfo");
Log.d("user",userInfo.get("your key"));

Related

Android Studio Login with SQLite database

Currently I am developing a personal software that is able to use the database to store the registered accounts and when logging in will retrieve the data from the database to compare with the characters been entered by the user.
But for some reason, even though I entered it correctly, I can't log in successfully
This is SQLite java file
package anhtuan.example.sample.SQLite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class SQLite extends SQLiteOpenHelper {
public SQLite(#Nullable Context context) {
super(context, "System", null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String account = "create table accounts " +
"(" +
"_id integer primary key autoincrement, " +
"user text," +
"password text" +
")";
sqLiteDatabase.execSQL(account);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists accounts");
onCreate(sqLiteDatabase);
}
}
Here are DAO java file
package anhtuan.example.sample.DAO;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import java.util.ArrayList;
import anhtuan.example.sample.Log.SignUp;
import anhtuan.example.sample.Model.AccountModel;
import anhtuan.example.sample.SQLite.SQLite;
public class DAO {
SQLite sqLite;
ArrayList<AccountModel> ds = new ArrayList<>();
public DAO(Context context) {
sqLite = new SQLite(context);
}
public void addUser(String acc, String pass) {
SQLiteDatabase sqLiteDatabase = sqLite.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("user",acc);
values.put("password",pass);
sqLiteDatabase.insert("accounts", null, values);
}
public ArrayList<AccountModel> getDSAccount(){
SQLiteDatabase sqLiteDatabase = sqLite.getReadableDatabase();
Cursor c = sqLiteDatabase.rawQuery("select * from accounts", null);
if(c.getCount()>0){
c.moveToFirst();
do {
ds.add(new AccountModel(c.getString(1),c.getString(2)));
}while (c.moveToNext());
}
return ds;
}
public boolean checkLogin(Context context,String users,String passwords){
ds = getDSAccount();
for(int i = 0; i < ds.size();i++){
if(ds.get(i).getUser().equals(users)){
if(passwords.equals(ds.get(i).getPassword())){
return true;
}
}
};
return false;
}
public boolean changePass(String user,String password){
return true;
}
}
And lastly the signin java file
package anhtuan.example.sample.Log;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import java.util.ArrayList;
import anhtuan.example.sample.DAO.DAO;
import anhtuan.example.sample.Home;
import anhtuan.example.sample.Model.AccountModel;
import anhtuan.example.sample.R;
public class SignIn extends AppCompatActivity {
TextInputEditText user,pass;
TextView signup;
Button Login;
DAO dao;
ArrayList<AccountModel> ds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
setTitle("Sign In");
user = findViewById(R.id.SIuser);
pass = findViewById(R.id.SIpass);
Login = findViewById(R.id.SIbtn);
signup = findViewById(R.id.SItv);
dao = new DAO(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(SignIn.this,ForgotPass.class);
startActivity(i);
}
});
String Loginuser = user.getText().toString();
String Loginpasse = pass.getText().toString();
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user.getText().length() == 0 || pass.getText().length() == 0){
AlertDialog.Builder builder = new AlertDialog.Builder(SignIn.this);
builder.setTitle("You haven't insert all the blank");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}else{
if(dao.checkLogin(SignIn.this,Loginuser,Loginpasse)){
Intent i = new Intent(SignIn.this,Home.class);
startActivity(i);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(SignIn.this);
builder.setTitle("Check again !");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
}
}
});
}
}
I had try to use contain and indexOf with arrayList to find the data without using for loop but it always come out false so i decide to use for loop again.

Inserting or Reading values in an SQLite database doesn't yield any results

Started with SQLite in Android this evening. Practiced all the code from the Google documentation but it's still going wrong and I can't figure out where I'm going wrong. Take a look and see if you can find out any details.
DatabaseHelperContract.java
package com.practice.sqlitepractice;
import android.provider.BaseColumns;
//final class to prevent inheritance
public final class DatabaseHelperContract {
//Create Entry String
public static final String CREATE_ENTRY = "CREATE TABLE " + DatabaseSchema.TABLE_NAME + " (" +
DatabaseSchema._ID + " INTEGER PRIMARY KEY, " + DatabaseSchema.COLUMN_NAME + " TEXT)";
//private constructor to prevent accidental instantiation
private DatabaseHelperContract(){
}
/*Inner class that defines individual table contents*/
public static class DatabaseSchema implements BaseColumns{
public static final String TABLE_NAME = "details";
public static final String COLUMN_NAME = "name";
}
}
DatabaseHelper.class
package com.practice.sqlitepractice;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "table.db";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DatabaseHelperContract.CREATE_ENTRY);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
MainActivity.java
package com.practice.sqlitepractice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText nameEditText;
private Button insertButton;
private Button readButton;
private ListView detailsListView;
private DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgetsMethod();
}
#Override
protected void onDestroy() {
super.onDestroy();
databaseHelper.close();
}
private void insertionMethod(String name) {
//gets the data repository in write mode
SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();
//create a new map of values, where the columns are the keys
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelperContract.DatabaseSchema.COLUMN_NAME, name);
try {
long newRowID = sqLiteDatabase.insert(DatabaseHelperContract.DatabaseSchema.TABLE_NAME, null, contentValues);
Toast.makeText(this, "ID for newly created row: " + newRowID, Toast.LENGTH_SHORT).show();
} catch (SQLException exception) {
exception.printStackTrace();
}
}
private void readMethod() {
SQLiteDatabase sqLiteDatabase = databaseHelper.getReadableDatabase();
String[] projection = {DatabaseHelperContract.DatabaseSchema.COLUMN_NAME};
try {
Cursor cursor = sqLiteDatabase.query(
DatabaseHelperContract.DatabaseSchema.TABLE_NAME,
projection,
null,
null,
null,
null,
null);
List<String> itemIDs = new ArrayList<>();
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelperContract.DatabaseSchema.COLUMN_NAME));
itemIDs.add(name);
}
cursor.close();
displayMethod(itemIDs);
} catch (SQLiteException exception) {
exception.printStackTrace();
}
}
private void displayMethod(List<String> list) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, R.id.details_list_view, list);
detailsListView.setAdapter(arrayAdapter);
}
#Override
public void onClick(View view) {
if (view == readButton) {
readMethod();
}
if (view == insertButton) {
String name = nameEditText.getText().toString();
insertionMethod(name);
}
}
private void initializeWidgetsMethod() {
nameEditText = findViewById(R.id.name_edit_text);
insertButton = findViewById(R.id.insert_button);
readButton = findViewById(R.id.read_button);
detailsListView = findViewById(R.id.details_list_view);
databaseHelper = new DatabaseHelper(getApplicationContext());
}
}
Note: I know that database transactions are expensive and should always be performed asynchronously. This code is just for practice and I will be performing all those at a later stage.
The problem with your code is the way that you initialize the ArrayAdapter in displayMethod().
The 3d argument of this definition:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
R.id.details_list_view,
list
);
is R.id.details_list_view which is the ListView resource id, while you should have used a TextView resource id but only if you have created one to use inside the ListView.
Did you create such a TextView?
If not then you can use the default TextView, by not passing this argument.
So change the code to this:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);

How to read and display user's rank which is set as default in the beginning

I added a new column COL_5 to my SQLite database and it's called "rank". Every user registered starts with rank set as "Australopithecus afarensis" which should be displayed in UserPanelActivity.java. What I did is I managed to display nickname of user (SignInActivity) but I have trouble with checking current rank and then display it on the screen.
Code looks like this:
DatabaseHelper:
package com.pracainzynierska.inzynierka;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="register.db";
public static final String TABLE_NAME="registeruser";
public static final String COL_1 ="ID";
public static final String COL_2 ="username";
public static final String COL_3 ="mail_address";
public static final String COL_4 ="password";
public static final String COL_5 = "rank";
//public static final String COL_6 = "dailytip";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME,null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT, mail_address TEXT, password TEXT, rank TEXT DEFAULT 'Australopithecus afarensis')");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addUser(String user, String password, String mail_address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", user);
contentValues.put("password", password);
contentValues.put("mail_address", mail_address);
long res = db.insert("registeruser", null, contentValues);
db.close();
return res;
}
public boolean checkUser(String username, String password)
{
String[] columns = {COL_1};
SQLiteDatabase db = getReadableDatabase();
String selection = COL_2 + "=?" + " and " + COL_4 + "=?";
String[] selectionArgs = {username, password};
Cursor cursor = db.query(TABLE_NAME, columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if(count>0)
return true;
else
return false;
}
}
SignInActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
public class SignInActivity extends AppCompatActivity {
private TextView register_text;
public static CallbackManager callbackManager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
db = new DatabaseHelper(this);
callbackManager = CallbackManager.Factory.create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
usernameEditText.requestFocus();
register_text = findViewById(R.id.register_text);
register_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(SignInActivity.this, RegisterActivity.class);
startActivity(registerIntent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = usernameEditText.getText().toString().trim();
String pwd = passwordEditText.getText().toString().trim();
Boolean res = db.checkUser(user,pwd);
if(res == true)
{
Intent intent = new Intent(SignInActivity.this,UserPanelActivity.class);
Intent intentPopUp = new Intent(SignInActivity.this, PopUpActivity.class);
intent.putExtra("username",user);
startActivity(intent);
startActivity(intentPopUp);
Toast.makeText(SignInActivity.this,"Welcome " + user + "!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"There is a problem with singing in!", Toast.LENGTH_SHORT).show();
usernameEditText.setText("");
passwordEditText.setText("");
usernameEditText.requestFocus();
}
}
});
}
}
UserPanelActivity:
package com.pracainzynierska.inzynierka;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserPanelActivity extends AppCompatActivity {
private Button settings_btn, progress_btn, dailychallenge_btn, premium_btn, logout_btn, training_btn;
private TextView NickNameText, rankText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_panel);
String username = getIntent().getStringExtra("username");
//String rank = getIntent().getStringExtra("rank");
NickNameText = findViewById(R.id.nickname);
NickNameText.setText(username);
//here I'd like to display rank
rankText = findViewById(R.id.rank);
rankText.setText(rank);
settings_btn = findViewById(R.id.settings_user_panel_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Settings();
}
});
progress_btn = findViewById(R.id.progress_button);
progress_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyProgress();
}
});
dailychallenge_btn = findViewById(R.id.challenge_button);
dailychallenge_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DailyChallenge();
}
});
premium_btn = findViewById(R.id.premium_button);
premium_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Premium();
}
});
logout_btn = findViewById(R.id.logout_button);
logout_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackToMenu();
finish();
}
});
training_btn = findViewById(R.id.start_freetraining_button);
training_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Training();
}
});
}
private void Training() {
Intent intent = new Intent(this, FillTheTextActivity.class);
startActivity(intent);
}
private void BackToMenu() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void Premium() {
Intent intent = new Intent(this,PremiumActivity.class);
startActivity(intent);
}
private void DailyChallenge() {
Intent intent = new Intent(this,DailyChallengeActivity.class);
startActivity(intent);
}
private void MyProgress() {
Intent intent = new Intent(this,MyProgressActivity.class);
startActivity(intent);
}
private void Settings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
Every help is kindly seen, thanks in advance :)
Create a method like this in your DatabaseHelper class:
public String getRank(int id) {
String query = "SELECT rank from " + TABLE_NAME + " where ID = " + id;
SQLiteDatabase db = getReadableDatabase();
try {
return db.rawQuery(query, null).getString(cursor.getColumnIndex(rank));
} catch (Exception e) {
return "";
}
}
Source

Android cart button not working with database

I really need help while whenever I press cart button to add food to basket app stop working and can't submit my assignment when cart button doesn't work. I use Firebase which is working and DB browser for SQLite. I triple - quatrocheck the names in databases with the names in code and still I don't know why it doesn't work. Would appreciate any help.
error in picture (LogCat): https://ibb.co/n4bMWb
Code of Databases.
package com.example.onix.AndroEat.Database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import java.util.ArrayList;
import java.util.List;
import com.example.onix.AndroEat.Model.Order;
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="Eat.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME,null, DB_VER);
}
public List<Order> getCarts()
{
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect={"ID","ProductName","ProductId","Quantity","Price",};
String sqlTable="OrderDetail";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<Order> result = new ArrayList<>();
if(c.moveToFirst())
{
do{
result.add(new Order(
c.getInt(c.getColumnIndex("ID")),
c.getString(c.getColumnIndex("ProductId")),
c.getString(c.getColumnIndex("ProductName")),
c.getString(c.getColumnIndex("Quantity")),
c.getString(c.getColumnIndex("Price"))
));
}while (c.moveToNext());
}
return result;
}
public void addToCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,)VALUES('%s','%s','%s','%s');",
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice());
db.execSQL(query);
}
public void cleanCart()
{
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM OrderDetail");
db.execSQL(query);
}
public int getCountCart() {
int count=0;
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT COUNT(*) FROM OrderDetail");
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst())
{
do{
count = cursor.getInt(0);
}while (cursor.moveToNext());
}
return count;
}
public void updateCart(Order order) {
SQLiteDatabase db = getReadableDatabase();
String query = String.format("UPDATE OrderDetail SET Quantity= %s WHERE ID = %d",order.getQuantity(),order.getID());
db.execSQL(query);
}
}
Code of FoodDetail:
package com.example.onix.AndroEat;
import android.content.Context;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.andremion.counterfab.CounterFab;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.example.onix.AndroEat.Common.Common;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.stepstone.apprating.AppRatingDialog;
import com.stepstone.apprating.listener.RatingDialogListener;
import java.util.Arrays;
import com.example.onix.AndroEat.Model.Food;
import com.example.onix.AndroEat.Model.Order;
import com.example.onix.AndroEat.Model.Rating;
import com.example.onix.AndroEat.Database.Database;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class FoodDetail extends AppCompatActivity implements RatingDialogListener {
TextView food_name,food_price,food_description;
ImageView food_image;
CollapsingToolbarLayout collapsingToolbarLayout;
FloatingActionButton btnRating;
CounterFab btnCart;
ElegantNumberButton numberButton;
RatingBar ratingBar;
String foodId="";
FirebaseDatabase database;
DatabaseReference foods;
DatabaseReference ratingTbl;
Food currentFood;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/restaurant_font.otf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_food_detail);
//Firebase
database = FirebaseDatabase.getInstance();
foods = database.getReference("Foods");
ratingTbl = database.getReference("Rating");
//Init view
numberButton = (ElegantNumberButton)findViewById(R.id.number_button);
btnCart = (CounterFab) findViewById(R.id.btnCart);
btnRating = (FloatingActionButton)findViewById(R.id.btn_rating);
ratingBar = (RatingBar)findViewById(R.id.ratingBar);
btnRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRatingDialog();
}
});
btnCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Database(getBaseContext()).addToCart(new Order(
foodId,
currentFood.getName(),
numberButton.getNumber(),
currentFood.getPrice()
));
Toast.makeText(FoodDetail.this, "Added to Cart", Toast.LENGTH_SHORT).show();
}
});
btnCart.setCount(new Database(this).getCountCart());
food_description = (TextView)findViewById(R.id.food_description);
food_name = (TextView)findViewById(R.id.food_name);
food_price = (TextView)findViewById(R.id.food_price);
food_image = (ImageView)findViewById(R.id.img_food);
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppbar);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppbar);
//Get Food Id from Intent
if(getIntent() != null)
foodId = getIntent().getStringExtra("FoodId");
if(!foodId.isEmpty())
{
if(Common.isConnectedToInterner(getBaseContext()))
{
getDetailFood(foodId);
getRatingFood(foodId);
}
else
{
Toast.makeText(FoodDetail.this, "Please check your connection !!", Toast.LENGTH_SHORT).show();
return;
}
}
}
private void getRatingFood(String foodId) {
com.google.firebase.database.Query foodRating = ratingTbl.orderByChild("foodId").equalTo(foodId);
foodRating.addValueEventListener(new ValueEventListener() {
int count=0,sum=0;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Rating item = postSnapshot.getValue(Rating.class);
sum+=Integer.parseInt(item.getRateValue());
count++;
}
if(count != 0)
{
float average = sum/count;
ratingBar.setRating(average);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showRatingDialog() {
new AppRatingDialog.Builder()
.setPositiveButtonText("Submit")
.setNegativeButtonText("Cancel")
.setNoteDescriptions(Arrays.asList("Very Bad","Not Good","Quite Ok","Very Good","Excellent"))
.setDefaultRating(1)
.setTitle("Rate this food")
.setDescription("Please select some stars and give your feedback")
.setTitleTextColor(R.color.colorPrimary)
.setDescriptionTextColor(R.color.colorPrimary)
.setHint("Please write your comment here...")
.setHintTextColor(R.color.colorAccent)
.setCommentTextColor(android.R.color.white)
.setCommentBackgroundColor(R.color.colorPrimaryDark)
.setWindowAnimation(R.style.RatingDialogFadeAnim)
.create(FoodDetail.this)
.show();
}
private void getDetailFood(String foodId) {
foods.child(foodId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentFood = dataSnapshot.getValue(Food.class);
//Set Image
Picasso.with(getBaseContext()).load(currentFood.getImage())
.into(food_image);
collapsingToolbarLayout.setTitle(currentFood.getName());
food_price.setText(currentFood.getPrice());
food_name.setText(currentFood.getName());
food_description.setText(currentFood.getDescription());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onPositiveButtonClicked(int value, String comments) {
//Get Rating and upload to firebase
final Rating rating = new Rating(Common.currentUser.getPhone(),
foodId,
String.valueOf(value),
comments);
ratingTbl.child(Common.currentUser.getPhone()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(Common.currentUser.getPhone()).exists())
{
//Remove old value (you can delete or let it be - useless function :D)
ratingTbl.child(Common.currentUser.getPhone()).removeValue();
//Update new value
ratingTbl.child(Common.currentUser.getPhone()).setValue(rating);
}
else
{
//Update new value
ratingTbl.child(Common.currentUser.getPhone()).setValue(rating);
}
Toast.makeText(FoodDetail.this, "Thank you for submit rating !!!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onNegativeButtonClicked() {
}
}
Will post more code IF needed.
Thank you very much.
"," should be removed after price in the above code. Below is the rite code
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price)VALUES('%s','%s','%s','%s');",
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice());
Also remove "," from below code above
String[] sqlSelect={"ID","ProductName","ProductId","Quantity","Price"};

I don't know how to verify if the phone number already exist. I'm just a newbie and i don't know what to do now

I an newbie to android studio and sq lite database, i am developing a login page for an application like the login in gmail. Here i am taking user phone number as primary key.when the user enter his phone number it will redirect to password screen if already exist. I don't know how to checked whether the phone number is already exist or not.
This my code.
PhoneNumber.java
package com.hernaezchristophergmail.projectitrack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 PhoneNumber extends AppCompatActivity {
EditText Pnum;
Button Con;
UserDBHelper userDBHelper;
SQLiteDatabase sqLiteDatabase;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_number);
Pnum = (EditText) findViewById(R.id.tbPnumber);
Con = (Button) findViewById(R.id.btbCon);
Con.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String pnumber = Pnum.getText().toString().trim();
String storedPassword = UserDBHelper.getSingleEntry(pnumber,sqLiteDatabase);
/* if(pnumber.equals("")||pnumber1.equals("")){
Toast.makeText(PhoneNumber.this, "Please", Toast.LENGTH_LONG).show();
return;
}*/
if(!pnumber.equals(storedPassword)){
Toast.makeText(PhoneNumber.this, "Invalid Login details", Toast.LENGTH_LONG).show();
return;
}
else{
Intent intent = new Intent(PhoneNumber.this,PasswordScreen.class);
startActivity(intent);
}
}
});
}
/* public void add(View view){
String pnumber = Pnum.getText().toString();
Intent intent = new Intent(PhoneNumber.this, PasswordScreen.class);
startActivity(intent);
}
*/
public void create(View view) {
Intent intent = new Intent(PhoneNumber.this, SignUp.class);
startActivity(intent);
}
#Override
public void onBackPressed(){
}
}
UserDBHelper.java
package com.hernaezchristophergmail.projectitrack;
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;
/**
* Created by Christopher on 4/26/2016.
*/
public class UserDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ITRACK_USER.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATEINFO_QUERY=
"CREATE TABLE "+ UserContact.UserInformation.TABLE_NAME+"("+ UserContact.UserInformation.User_Password+" TEXT," +
UserContact.UserInformation.User_PhoneNumber+" TEXT," + UserContact.UserInformation.User_Firstame+" TEXT," + UserContact.UserInformation.User_LastName+" TEXT);";
public UserDBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS","DATABASE CREATED / OPENED ...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATEINFO_QUERY);
Log.e("DATABASE OPERATION", "TABLE CREATED ...");
}
public void saveInfo(String first,String last,String pnum, String pass, SQLiteDatabase db){
ContentValues contentvalues = new ContentValues();
contentvalues.put(UserContact.UserInformation.User_Firstame,first);
contentvalues.put(UserContact.UserInformation.User_LastName,last);
contentvalues.put(UserContact.UserInformation.User_PhoneNumber,pnum);
contentvalues.put(UserContact.UserInformation.User_Password,pass);
db.insert(UserContact.UserInformation.TABLE_NAME, null, contentvalues);
Log.e ("Database Operation", "one row inserted . . .");
}
public static String getSingleEntry(String pnum, SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, " User_PhoneNumber=?",
new String[] { pnum }, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String phonenum = cursor.getString(cursor.getColumnIndex("password"));
cursor.close();
return phonenum;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
UserContact.java
public class UserContact {
public static abstract class UserInformation{
public static final String TABLE_NAME = "info";
public static final String User_Password= "password";
public static final String User_LastName = "last_name";
public static final String User_Firstame = "first_name";
public static final String User_PhoneNumber = "phone_number";
public static final String PHOTOID = "photo_id";
}
}
What is the Error?
Also, please look into this.
public static String getSingleEntry(String pnum, SQLiteDatabase sqLiteDatabase) {
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, " User_PhoneNumber=?",
new String[] { pnum }, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String phonenum = cursor.getString(cursor.getColumnIndex("password"));
cursor.close();
return phonenum; //RETURN YES / NO if exist not the actual password for security purpose.
}
if(!pnumber.equals(storedPassword)){ //ALSO HERE, return YES/NO if exist or new, not the actual password.
Toast.makeText(PhoneNumber.this, "Invalid Login details", Toast.LENGTH_LONG).show();
return;
}
The below method will return the name for the given number. By this way you can trigger whether the number is available or not. Returns true if the number is there else false.
public Boolean numberExists(Context context, String phoneNumber) {
String contactName = null;
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
try {
if (cursor != null) {
if (cursor.moveToFirst()) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
Errors in query
1. Wrong column name User_PhoneNumber never exists in your table. Write query as below
Cursor cursor = sqLiteDatabase.query(UserContact.UserInformation.TABLE_NAME, null, UserContact.UserInformation.User_PhoneNumber+"=?",
new String[] { pnum }, null, null, null);
and
2. Wrong column name :) you are reading password instead of phone number.. write
String phonenum = cursor.getString(cursor.getColumnIndex(UserContact.UserInformation.User_PhoneNumber));
instead of
String phonenum = cursor.getString(cursor.getColumnIndex("password"));

Categories

Resources