How to delete all RecyclerView items from SQLite Database? - java

I am a beginner at coding in Java. I am creating a notes app with lots of other features. And one of the features are, storing the user's bank card details in a RecyclerView. I did this by making an SQLite CRUD. All of the Create, Read, Update and Delete works. And I protected this page with a Pattern lock.
And when we are in the Input Pattern page, we can see a clickable text called Click HERE if you forgot your pattern, That works. And when you click on that clickable text, the app shows an Alert Dialog, titled are you sure? and the message is If you change your pattern, all your data will be deleted then there are two buttons Yes and No. No does nothing, it just cancel the forgot pattern thing. But the problem is with the Yes button.
When we click it, It should delete all bank cards or delete all data. Please suggest a way to delete all data from the SQLite Database. I tried lots of ways to do this.
HERE IS MY INPUT PATTERN ACTIVITY
package com.ixidev.simplenotepad;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ixidev.simplenotepad.model.Note;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProgramActivity extends AppCompatActivity {
FloatingActionButton fab, fabChangePattern, fabexit;
RecyclerView mRecyclerViewBC;
CardsDatabaseHelper cardsDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
mRecyclerViewBC = findViewById(R.id.recyclerViewBC);
cardsDatabaseHelper = new CardsDatabaseHelper(this);
showRecord();
fabexit = findViewById(R.id.exitProgram);
fab = findViewById(R.id.addFabButtonBC);
fabChangePattern = findViewById(R.id.ChangePattern);
fabexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, MainActivity.class);
startActivity(intent);
}
});
fabChangePattern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, CreatePasswordActivity.class);
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, AddBankCardActivity.class);
intent.putExtra("BCeditMode", false);
startActivity(intent);
}
});
}
private void showRecord() {
CardAdapter cardAdapter = new CardAdapter(ProgramActivity.this, cardsDatabaseHelper.getAllBCdata(ConstantsCard.BC_C_ADD_TIMESTAMP + " DESC"));
mRecyclerViewBC.setAdapter(cardAdapter);
}
#Override
protected void onResume() {
super.onResume();
showRecord();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
}
HERE IS MY DATABASE HELPER CLASS
package com.ixidev.simplenotepad;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class CardsDatabaseHelper extends SQLiteOpenHelper {
public CardsDatabaseHelper(#Nullable Context context) {
super(context, ConstantsCard.BC_DB_NAME, null, ConstantsCard.BC_DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ConstantsCard.BC_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ConstantsCard.BC_TABLE_NAME);
onCreate(db);
}
public long insertInfo(String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
long id = db.insert(ConstantsCard.BC_TABLE_NAME, null, values);
db.close();
return id;
}
public void updateInfo(String BCid, String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
db.update(ConstantsCard.BC_TABLE_NAME, values, ConstantsCard.BC_C_ID + " = ?", new String[]{BCid});
db.close();
}
public void deleteInfo(String BCid) {
SQLiteDatabase db = getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME, ConstantsCard.BC_C_ID + " = ? ", new String[]{BCid});
db.close();
}
public void testDelete() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME,null,null);
db.execSQL("delete from "+ ConstantsCard.BC_TABLE_NAME);
db.execSQL("TRUNCATE table " + ConstantsCard.BC_TABLE_NAME);
db.close();
}
public void delete(String BCid)
{
String[] args={BCid};
getWritableDatabase().delete("texts", "_ID=?", args);
}
public ArrayList<CardModel> getAllBCdata(String orderByBC) {
ArrayList<CardModel> ArrayListCard = new ArrayList<>();
String selectQuery = "SELECT * FROM " + ConstantsCard.BC_TABLE_NAME + " ORDER BY " + orderByBC;
SQLiteDatabase BCdb = this.getWritableDatabase();
Cursor CardCursor = BCdb.rawQuery(selectQuery, null);
if (CardCursor.moveToNext()) {
do {
CardModel cardModel = new CardModel(
""+CardCursor.getInt(CardCursor.getColumnIndex(ConstantsCard.BC_C_ID)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_IMAGE)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_NUMBER)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_CVV)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_EXPIRY)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_ADD_TIMESTAMP)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_UPDATE_TIMESTAMP))
);
ArrayListCard.add(cardModel);
} while (CardCursor.moveToNext());
}
BCdb.close();
return ArrayListCard;
}
}
HERE IS MY ADAPTER CLASS
package com.ixidev.simplenotepad;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.arch.core.executor.TaskExecutor;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.Holder> {
private Context CardContext;
private ArrayList<CardModel> CardArrayList;
CardsDatabaseHelper cardsDatabaseHelper;
public CardAdapter(Context cardContext, ArrayList<CardModel> cardArrayList) {
CardContext = cardContext;
CardArrayList = cardArrayList;
cardsDatabaseHelper = new CardsDatabaseHelper(CardContext);
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View viewBC = LayoutInflater.from(CardContext).inflate(R.layout.bc_row, parent, false);
return new Holder(viewBC);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
CardModel cardModel = CardArrayList.get(position);
final String BCid = cardModel.getBCid();
final String BCimage = cardModel.getImageBC();
final String BCnumber = cardModel.getNumber();
final String BCcvv = cardModel.getCvv();
final String BCexpiry = cardModel.getExpiryBC();
final String addTimeStampBC = cardModel.getAddTimeStampBC();
final String updateTimeStampBC = cardModel.getUpdateTimeStampBC();
holder.profileIvBC.setImageURI(Uri.parse(BCimage));
holder.number.setText(BCnumber);
holder.cvv.setText(BCcvv);
holder.expiryBC.setText(BCexpiry);
holder.editButtonBC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDialog(
""+position,
""+BCid,
""+BCnumber,
""+BCcvv,
""+BCexpiry,
""+BCimage,
""+addTimeStampBC,
""+updateTimeStampBC
);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
deleteDialog(
""+BCid
);
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CardContext, "Clicked", Toast.LENGTH_SHORT).show();
cardsDatabaseHelper.testDelete();
cardsDatabaseHelper.delete(BCid);
}
});
}
private void deleteDialog(final String BCid) {
AlertDialog.Builder builderBC = new AlertDialog.Builder(CardContext);
builderBC.setTitle("Delete?");
builderBC.setMessage("Are you sure you want to delete this document?");
builderBC.setCancelable(false);
builderBC.setIcon(R.drawable.ic_action_delete);
builderBC.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
cardsDatabaseHelper.deleteInfo(BCid);
((ProgramActivity)CardContext).onResume();
Toast.makeText(CardContext, "Successfully deleted!", Toast.LENGTH_SHORT).show();
}
});
builderBC.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderBC.create().show();
}
private void editDialog(String position, String BCid, String BCnumber, String BCcvv, String BCexpiry, String BCimage, String addTimeStampBC, String updateTimeStampBC) {
AlertDialog.Builder BCbuilder = new AlertDialog.Builder(CardContext);
BCbuilder.setTitle("Edit?");
BCbuilder.setMessage("Are you sure you want to edit this Bank Card?");
BCbuilder.setCancelable(false);
BCbuilder.setIcon(R.drawable.ic_action_edit);
BCbuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CardContext, EditBankCardActivity.class);
intent.putExtra("BCID", BCid);
intent.putExtra("NUMBER", BCnumber);
intent.putExtra("CVV", BCcvv);
intent.putExtra("EXPIRYBC", BCexpiry);
intent.putExtra("IMAGE", BCimage);
intent.putExtra("BC_ADD_TIMESTAMP", addTimeStampBC);
intent.putExtra("BC_UPDATE_TIMESTAMP", updateTimeStampBC);
intent.putExtra("BCeditMode", true);
CardContext.startActivity(intent);
}
});
BCbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
BCbuilder.create().show();
}
#Override
public int getItemCount() {
return CardArrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIvBC;
TextView number, cvv, expiryBC;
ImageButton editButtonBC;
public Holder(#NonNull View itemView) {
super(itemView);
profileIvBC = itemView.findViewById(R.id.profileIvBC);
number = itemView.findViewById(R.id.number);
cvv = itemView.findViewById(R.id.cvv);
expiryBC = itemView.findViewById(R.id.expiry);
editButtonBC = itemView.findViewById(R.id.editBtnBC);
}
}
}
HERE IS MY MODEL CLASS
package com.ixidev.simplenotepad;
public class CardModel {
String BCid, imageBC, number, cvv, expiryBC, addTimeStampBC, updateTimeStampBC;
public CardModel(String BCid, String imageBC, String number, String cvv, String expiryBC, String addTimeStampBC, String updateTimeStampBC) {
this.BCid = BCid;
this.imageBC = imageBC;
this.number = number;
this.cvv = cvv;
this.expiryBC = expiryBC;
this.addTimeStampBC = addTimeStampBC;
this.updateTimeStampBC = updateTimeStampBC;
}
public String getBCid() {
return BCid;
}
public void setBCid(String BCid) {
this.BCid = BCid;
}
public String getImageBC() {
return imageBC;
}
public void setImageBC(String imageBC) {
this.imageBC = imageBC;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getExpiryBC() {
return expiryBC;
}
public void setExpiryBC(String expiryBC) {
this.expiryBC = expiryBC;
}
public String getAddTimeStampBC() {
return addTimeStampBC;
}
public void setAddTimeStampBC(String addTimeStampBC) {
this.addTimeStampBC = addTimeStampBC;
}
public String getUpdateTimeStampBC() {
return updateTimeStampBC;
}
public void setUpdateTimeStampBC(String updateTimeStampBC) {
this.updateTimeStampBC = updateTimeStampBC;
}
}
And here is my CONSTANTS class
package com.ixidev.simplenotepad;
public class ConstantsCard {
public static final String BC_DB_NAME = "MY_BANK_CARDS";
public static final int BC_DB_VERSION = 1;
public static final String BC_TABLE_NAME = "MY_BANK_CARDS_TABLE";
public static final String BC_C_ID = "BC_ID";
public static final String BC_C_NUMBER = "BC_NUMBER";
public static final String BC_C_CVV = "BC_CVV";
public static final String BC_C_EXPIRY = "BC_EXPIRY";
public static final String BC_C_IMAGE = "BC_IMAGE";
public static final String BC_C_ADD_TIMESTAMP = "BC_ADD_TIMESTAMP";
public static final String BC_C_UPDATE_TIMESTAMP = "BC_UPDATE_TIMESTAMP";
public static final String BC_CREATE_TABLE = "CREATE TABLE " + BC_TABLE_NAME + "("
+ BC_C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BC_C_NUMBER + " TEXT,"
+ BC_C_CVV + " TEXT,"
+ BC_C_EXPIRY + " TEXT,"
+ BC_C_IMAGE + " TEXT,"
+ BC_C_ADD_TIMESTAMP + " TEXT,"
+ BC_C_UPDATE_TIMESTAMP + " TEXT"
+ ");";
}

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.

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

Comparing the User Input Edit Text with SQLite Database Android Java

Hello I am making a teacher assistant app, the app uses SQLite database and allows teacher to take attendance by adding updating and removing students, the student ID is generated everytime a new student is added, now here is the thing how to display error message if the input from the teacher doesn't match a student ID in database instead of making my app crash.
StudentOperations
package com.appcreator.isa.theteacherassistantapp.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
import java.util.ArrayList;
import java.util.List;
public class StudentOperations
{
public static final String LOGTAG = "STD_MNGMNT_SYS";
SQLiteOpenHelper dbhandler;
SQLiteDatabase database;
private static final String[] allColumns = {
StudentDatabaseHandler.COLUMN_SID,
StudentDatabaseHandler.COLUMN_EID,
StudentDatabaseHandler.COLUMN_FIRST_NAME,
StudentDatabaseHandler.COLUMN_LAST_NAME,
StudentDatabaseHandler.COLUMN_STUDY,
StudentDatabaseHandler.COLUMN_ATTENDANCE
};
public StudentOperations(Context context)
{
dbhandler = new StudentDatabaseHandler(context);
}
public void open()
{
Log.i(LOGTAG,"Database Opened");
database = dbhandler.getWritableDatabase();
}
public void close()
{
Log.i(LOGTAG, "Database Closed");
dbhandler.close();
}
public Student addStudent(Student Student)
{
ContentValues values = new ContentValues();
values.put(StudentDatabaseHandler.COLUMN_EID, Student.getEnrlomentID());
values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME,Student.getFirstname());
values.put(StudentDatabaseHandler.COLUMN_LAST_NAME,Student.getLastname());
values.put(StudentDatabaseHandler.COLUMN_STUDY, Student.getStudy());
values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, Student.getAttendance());
long insertSID = database.insert(StudentDatabaseHandler.TABLE_STUDENTS,null,values);
Student.setStudentID(insertSID);
return Student;
}
// Getting single Student
public Student getStudent(long id)
{
Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,StudentDatabaseHandler.COLUMN_SID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
if (cursor != null)
cursor.moveToFirst();
Student e = new Student(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
// return Student
return e;
}
public List<Student> getAllStudents()
{
Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,null,null,null, null, null);
List<Student> students = new ArrayList<>();
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
Student student = new Student();
student.setStudentID(cursor.getLong(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_SID)));
student.setEnrlomentID(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_EID)));
student.setFirstname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_FIRST_NAME)));
student.setLastname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_LAST_NAME)));
student.setStudy(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_STUDY)));
student.setAttendance(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_ATTENDANCE)));
students.add(student);
}
}
// return All Students
return students;
}
// Updating Student
public int updateStudent(Student student)
{
ContentValues values = new ContentValues();
values.put(StudentDatabaseHandler.COLUMN_EID, student.getEnrlomentID());
values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME, student.getFirstname());
values.put(StudentDatabaseHandler.COLUMN_LAST_NAME, student.getLastname());
values.put(StudentDatabaseHandler.COLUMN_STUDY, student.getStudy());
values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, student.getAttendance());
// updating row
return database.update(StudentDatabaseHandler.TABLE_STUDENTS, values,
StudentDatabaseHandler.COLUMN_SID + "=?",new String[] { String.valueOf(student.getStudentID())});
}
// Deleting Student
public void removeStudent(Student student)
{
database.delete(StudentDatabaseHandler.TABLE_STUDENTS, StudentDatabaseHandler.COLUMN_SID + "=" + student.getStudentID(), null);
}
}
The Main Activity
package com.appcreator.isa.theteacherassistantapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
public class MainActivity extends AppCompatActivity
{
private Button addStudentButton;
private Button editStudentButton;
private Button deleteStudentButton;
private StudentOperations studentOps;
private static final String EXTRA_STUDENT_ID = "TEMP";
private static final String EXTRA_ADD_UPDATE = "TEMP";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addStudentButton = (Button) findViewById(R.id.button_add_student);
editStudentButton = (Button) findViewById(R.id.button_edit_student);
deleteStudentButton = (Button) findViewById(R.id.button_delete_student);
addStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndUpdateStudent();
}
});
deleteStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndRemoveStudent();
}
});
}
public void getStudentIDAndUpdateStudent()
{
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().trim().length() > 0)
{
// get user input and set it to result
// edit text
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}).create()
.show();
}
public void getStudentIDAndRemoveStudent(){
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().trim().length() > 0)
{
// get user input and set it to result
// edit text
//studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}).create()
.show();
}
#Override
protected void onResume()
{
super.onResume();
studentOps = new StudentOperations(MainActivity.this);
studentOps.open();
}
#Override
protected void onPause()
{
super.onPause();
studentOps.close();
}
}
Logcat
10-17 03:42:09.750 11105-11105/com.appcreator.isa.theteacherassistantapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appcreator.isa.theteacherassistantapp, PID: 11105
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.appcreator.isa.theteacherassistantapp.Database.StudentOperations.getStudent(StudentOperations.java:71)
at com.appcreator.isa.theteacherassistantapp.MainActivity$5.onClick(MainActivity.java:144)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Updated Main Activity
package com.appcreator.isa.theteacherassistantapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;
public class MainActivity extends AppCompatActivity
{
private Button addStudentButton;
private Button editStudentButton;
private Button deleteStudentButton;
private StudentOperations studentOps;
private static final String EXTRA_STUDENT_ID = "TEMP";
private static final String EXTRA_ADD_UPDATE = "TEMP";
private static final String TAG = "Student Exits";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addStudentButton = (Button) findViewById(R.id.button_add_student);
editStudentButton = (Button) findViewById(R.id.button_edit_student);
deleteStudentButton = (Button) findViewById(R.id.button_delete_student);
addStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndUpdateStudent();
}
});
deleteStudentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
getStudentIDAndRemoveStudent();
}
});
}
public boolean check_existence(String stud_id)
{
SQLiteOpenHelper db = new StudentDatabaseHandler(this);
SQLiteDatabase database = db.getWritableDatabase();
String select = "SELECT * FROM students WHERE studentID =" + stud_id;
Cursor c = database.rawQuery(select, null);
if (c.moveToFirst())
{
Log.d(TAG,"Student Exists");
return true;
}
if(c!=null)
{
c.close();
}
database.close();
return false;
}
public void getStudentIDAndUpdateStudent()
{
LayoutInflater li = LayoutInflater.from(this);
final View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().isEmpty())
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
else
{
// get user input and set it to result
// edit text
if (check_existence(userInput.getText().toString()) == true)
{
Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
else
{
Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
}
}
}
}).create()
.show();
}
public void getStudentIDAndRemoveStudent()
{
LayoutInflater li = LayoutInflater.from(this);
View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_student_id.xml to alertdialog builder
alertDialogBuilder.setView(getStudentIdView);
final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id)
{
if (userInput.getText().toString().isEmpty())
{
Toast.makeText(MainActivity.this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
else
{
if(check_existence(userInput.getText().toString()) == true)
{
// get user input and set it to result
// edit text
//studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Invalid Input" , Toast.LENGTH_SHORT).show();
}
}
}
}).create()
.show();
}
#Override
protected void onResume()
{
super.onResume();
studentOps = new StudentOperations(MainActivity.this);
studentOps.open();
}
#Override
protected void onPause()
{
super.onPause();
studentOps.close();
}
}
You can make a new method to do the work with boolean data type and if it returns false, you might want to display it to the user via Toast or anything like that.
It may look like this in code:
public boolean check_existence(String stud_id) {
SQLiteDatabase db = this.getWritableDatabase();
String select = "SELECT * FROM table_name WHERE column_name ='" + stud_id;
Cursor c = db.rawQuery(select, null);
if (c.moveToFirst()) {
Log.d(TAG,"User exits");
return true;
}
if(c!=null) {
c.close();
}
db.close();
return false;
}
You can now just call the method and if it returns false you may just display what you want using Toast.

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"};

Check if value entered exists in database android

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

Categories

Resources