Values are not inserted properly in the SQLite database - java

I'm setting SQLite to my app signup page and I want to use my mobile number instead of email for signing up. My app shows no error but the toast ("Registered Successfully") never appears and activity mainWindow never starts.
My Database file is below
public class DatabaseHelp extends SQLiteOpenHelper {
public DatabaseHelp( Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table user(First_NAME text ,Last_NAME text,mobile number primary key ,password text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists user");
}
//inserting in database
public boolean insert(String First_NAME,String Last_NAME,String mobile,String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("Fisrt Name",First_NAME);
contentValues.put("Last Name",Last_NAME);
contentValues.put("Mobile Number",mobile);
contentValues.put("Password",password);
long ins=db.insert("user",null,contentValues);
if(ins==-1) {return false;}
else{ return true;}
}
// if number exists
public Boolean chkemail(String mobile){
SQLiteDatabase db= this.getWritableDatabase();
Cursor cursor=db.rawQuery("Select * from user where mobile=?",new String[]{mobile});
if(cursor.getCount()>0) return false;
else return true;
}
}
My Signup page java file is below
public class signup extends AppCompatActivity {
DatabaseHelp db;
EditText e1,e2,e3,e4,e5;
Button b1;
public void onClick(View view){
Intent i1 = new Intent(this, forgotpass2.class);
startActivity(i1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
db=new DatabaseHelp(this);
e1=(EditText)findViewById(R.id.editText5);
e2=(EditText)findViewById(R.id.editText6);
e3=(EditText)findViewById(R.id.editText);
e4=(EditText)findViewById(R.id.editText7);
e5=(EditText)findViewById(R.id.editText8);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
String s3=e3.getText().toString();
String s4=e4.getText().toString();
String s5=e5.getText().toString();
if(s1.equals("")||s2.equals("")||s3.equals("")||s4.equals("")||s5.equals("")) {
Toast.makeText(getApplicationContext(), "Fields are empty", Toast.LENGTH_SHORT).show();
} else {
if(s4.equals(s5)){
Boolean chkemail=db.chkemail(s3);
if(chkemail == true) {
Boolean insert = db.insert(s1,s2,s3,s4);
if(insert == true) {
Toast.makeText(getApplicationContext(),"Registered Successfully",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(),"Mobile Number already exits",Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(getApplicationContext(),"Passwords do not match",Toast.LENGTH_SHORT).show();
}
}
});
}
}
What should I do to make the code work properly?

There are several things in your code which need to be pointed out. First, about the insert function, the column names have spaces and I think you should get rid of those spaces for SQLite column names. Modify your insert function like the following.
public boolean insert(String First_NAME,String Last_NAME,String mobile,String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("first_name",First_NAME);
contentValues.put("last_name",Last_NAME);
contentValues.put("mobile",mobile);
contentValues.put("password",password);
long ins=db.insert("user",null,contentValues);
if(ins==-1) return false;
else return true;
}
Now, once you are done with this, I think your chkemail function now works correctly. Because, previously the field mobile was not found in the database table as the column name was different (i.e. the column name in your code was Mobile Number, which I have changed in the insert function to match with the query).
public boolean chkemail(String mobile){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from user where mobile=?",new String[]{mobile});
if(cursor.getCount()>0) return false;
else return true;
}
Please note that I have changed the return type of the chkemail function from Boolean to boolean.
And finally, in the signup activity, you need to modify the part mentioned below as well.
// Changed from Boolean to boolean
boolean insert = db.insert(s1,s2,s3,s4);
if(insert == true) {
Toast.makeText(getApplicationContext(),"Registered Successfully",Toast.LENGTH_SHORT).show();
// Start the new activity here
Intent newIntent = new Intent(this, mainWindow.class);
startActivity(newIntent);
}
Hope that helps!

Related

SQLite Database not getting updated

So Ive created an app where the user can input details about the movies he has watched such as name,cast,rating...ect and the details are stored in a database inside a table names which is initialized in the DataBaseHelper class as
public static final String TABLE_NAME = "table1";
in the below segment of code Ive created a list view and displayed the names of the movies with a checkbox in front of each name. where the check box if ticked mean that its a favorite else not a favorite...initially the column in the table which holds if the movie is a favorite is set to "no"
when ticked and button pressed I want all the movie names with the tick on to update to "yes" in the database.
DisplayActivity class with the list view
public class DisplayActivity extends AppCompatActivity {
DataBaseHelper myDb;
ListView movieNList;
Button addFavoritesB,button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
movieNList =(ListView) findViewById(R.id.moviesLV);
myDb=new DataBaseHelper(this);
addFavoritesB=(Button) findViewById(R.id.addButton);
button=(Button) findViewById(R.id.button);
ArrayList<String> theList=new ArrayList<>();
Cursor data=myDb.getData();
if (data.getCount()==0){
Toast.makeText(DisplayActivity.this,"The Database is empty",Toast.LENGTH_SHORT).show();
}else{
//Adds data to the list view
while(data.moveToNext()){
theList.add(data.getString(1));
Collections.sort(theList);
ListAdapter listAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice,theList);
movieNList.setAdapter(listAdapter);
}
}
buttonAction();
}
public void buttonAction(){
myDb.getWritableDatabase();
addFavoritesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemSelected="Selected items : \n";
for (int i=0;i<movieNList.getCount();i++){
if (movieNList.isItemChecked(i)){
itemSelected += movieNList.getItemAtPosition(i)+"\n";
System.out.println(itemSelected);
myDb.updateFavorites(itemSelected,"yes");
}
}
}
});
}
Method in DataBaseHelper class to update the favorites column
public boolean updateFavorites(String name,String favorites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FAVORITES", favorites);
Cursor res = db.rawQuery("select * from table1 where name=? ", new String[]{name});
if (res.getCount() > 0) {
long result = db.update(TABLE_NAME, contentValues, "name=?", new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
when I try it like this, the columns wont update....Please help
Assuming that itemSelected is created correctly inside the onClick() listener, I suggest that you use a char like "|" as a delimiter instead of "\n" for the movie titles and remove "Selected items : \n" from the start of itemSelected.
Also move myDb.updateFavorites(itemSelected,"yes"); out of the for loop, so that the updateFavorites() is called only once for all selected movies:
public void buttonAction(){
myDb.getWritableDatabase();
addFavoritesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemSelected="|";
for (int i=0;i<movieNList.getCount();i++){
if (movieNList.isItemChecked(i)){
itemSelected += movieNList.getItemAtPosition(i)+"|";
}
}
itemSelected += "|";
myDb.updateFavorites(itemSelected,"yes");
}
});
}
Then use the update() method to update the table with the operator LIKE in the WHERE clause:
public int updateFavorites(String name, String favorites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FAVORITES", favorites);
return db.update(TABLE_NAME, contentValues, "? LIKE '%|' || name || '|%'", new String[] {name});
}
Note that I changed the return type of updateFavorites() from boolean to int() because db.update() returns the number of updated rows.

Receive data from database based on user input in EditText

I have a quick question, I'm sure I'm just making a small mistake but I can't figure it out.I'm trying to get information from the database based on what the user inputs in an EditText. I'm getting error
"java.lang.IllegalStateException: Couldn't read row 0, col 1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.".
Here's My Main Activity Class
public class MainActivity extends AppCompatActivity {
Button create;
Button retrieve;
Button save;
Button clear;
EditText listName;
EditText listDetails;
ToDoListDatabase myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new ToDoListDatabase(this);
create = (Button)findViewById(R.id.createButton);
retrieve = (Button)findViewById(R.id.retrieveButton);
save = (Button)findViewById(R.id.saveButton);
clear = (Button)findViewById(R.id.clearButton);
listName = (EditText)findViewById(R.id.listName);
listDetails = (EditText)findViewById(R.id.listDetails);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddList();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
}
//Method Resets EditText back to default
public void resetEditText(){
listName.setText("");
listDetails.setText("");
}
//Method Adds List Entered By User To DataBase
public void AddList(){
boolean isInserted = myDb.insertData(listName.getText().toString(), listDetails.getText().toString());
if(isInserted == true){
Toast.makeText(MainActivity.this,"List " + listName.getText().toString() + " successfully created", Toast.LENGTH_LONG).show();
resetEditText();
}
else
Toast.makeText(MainActivity.this,"Error creating list", Toast.LENGTH_LONG).show();
}
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
}
Here's My DataBase Class
public class ToDoListDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "List_db";
public static final String TABLE_NAME = "List_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LIST";
public ToDoListDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,LIST TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXITS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String list) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, list);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) { //returns -1 if not inserted
return false;
} else
return true;
}
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME = '" +listName+"'" , null);
return res;
}
}
Here's my Android Monitor
10-10 13:11:41.618 2643-2643/com.example.stephen.todolist E/AndroidRuntime: FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.stephen.todolist.MainActivity.showList(MainActivity.java:79)
at com.example.stephen.todolist.MainActivity$2.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4439)
at android.widget.Button.performClick(Button.java:139)
at android.view.View$PerformClick.run(View.java:18395)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Your ToDoListDatabase class does not contain any field with name listName on which you are calling getText(). Also you are not passing any parameter in your getList(). You should pass your EditText query in this getList() and then create query on this param.
Changes:
MainActivy.java
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
//return;
}
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
ToDoListDatabase.java
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME ='" + listName+"'" , null);
return res;
}
Update
Change your showList as
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
res.moveToFirst();
StringBuffer buffer = new StringBuffer();
while (!res.isAfterLast()) {
buffer.append(res.getString(0));
res.moveToNext();
}
res.close();
listDetails.setText(buffer); //Not working yet!!!!
}
You are using listName (Edidtext) in your SQLiteOpenHelper class so u r getting error kindly pass the value of listName from your activity to method like.
//call and pass value like this.
showList(listName.getText().toString());
//or like this
String mListname = listName.getText().toString();
if(!TextUtils().isEmpty(mListname))//check if not empty
{
showList(mListname);
}else{
//handle error
}
// your method
public void showList(String listName)
{
//your implementation
}
SQLiteOpenHelper doesnt extends View so u cannot use view there.
but u can pass it to method parameter to access it.
showList(EditText listName)
{
String val = listName.getText().toString();
}
//and pass your editText
showList(listName);
Good programming practice for database and databesehelper to wrap them around another class, open database when needed not on every query and making queries with strings not with views themselves. Check this thread for creating a singleton DatabaseManager and execute queries with it.

Android Studio can't insert data into sqlitedatabase

I'm doing a small project for my mobile app subject. I need to link it with sqlitedatabase.
I've been the tutorial at the Youtube, I followed the tutorial step by step. I didn't got any error from the code.
I need to insert the value into the db and display it back but the user input didn't inserted into db so I couldn't display the data from the DB.
I hope someone could help me. I've been stuck for 2 days because of this problem with no error display.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "STUDENT.DB";
//create table
public static final String TABLE_STUDENT = "STUDENT_TABLE";
public static final String COL_STD_ID = "STD_ID";
public static final String COL_STD_NAME = "STD_NAME";
public static final String COL_STD_EMAIL = "STD_EMAIL";
public static final String COL_STD_ADDRESS = "STD_ADDRESS";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME, null, 1);
Log.e("DATABASE OPERATION","Database created/opend...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_STUDENT +" (STD_ID INTEGER PRIMARY KEY AUTOINCREMENT,STD_NAME TEXT,STD_EMAIL TEXT, STD_ADDRESS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_STUDENT );
onCreate(db);
}
public boolean insertData(String STD_NAME, String STD_EMAIL, String STD_ADDRESS)
{
SQLiteDatabase db = this.getWritableDatabase();
//get the data from user into db
ContentValues contentValues = new ContentValues();
contentValues.put(COL_STD_NAME,STD_NAME);
contentValues.put(COL_STD_EMAIL,STD_EMAIL);
contentValues.put(COL_STD_ADDRESS,STD_ADDRESS);
//SEE WHETHER THE DATA INSERT INTO DB OR NOT
//IF RETURN -1, DATA NOT SUCCESSFUL INSERTED
long result = db.insert(TABLE_STUDENT,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + TABLE_STUDENT,null);
return result;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etstdName, etstdEmail, etstdAddress;
Button btnInsertData, btnViewData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etstdName = (EditText)findViewById(R.id.etstdName);
etstdEmail = (EditText)findViewById(R.id.etstdEmail);
etstdAddress = (EditText)findViewById(R.id.etstdEmail);
btnViewData = (Button)findViewById(R.id.btnViewData);
btnInsertData = (Button)findViewById(R.id.btnInsertData);
InsertStdData();
}
// I think i get stuck at here but theres not error display at InsertStdData() methid
public void InsertStdData() {
btnInsertData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDB.insertData(etstdName.getText().toString(),
etstdEmail.getText().toString(),
etstdAddress.getText().toString());
if(isInserted = true)
Toast.makeText(MainActivity.this,"Data successfully inserted.",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not successfully inserted.",Toast.LENGTH_LONG).show();
}
});
}
public void viewStdData(View view) {
Cursor result = myDB.getAllData();
if(result.getCount() == 0) {
//showmessage method
showMessage("ERROR", "NO DATA FOUND");
return;
}
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()){
buffer.append("STD_ID : "+result.getString(0)+"\n");
buffer.append("STD_NAME : "+result.getString(1)+"\n");
buffer.append("STD_EMAIL : "+result.getString(2)+"\n");
buffer.append("STD_ADDRESS :"+result.getString(3)+"\n\n");
}
//show all data
showMessage("DATA",buffer.toString());
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
You called InsertStdData() but you didnt call viewStdData(View view) in your MainActivity.

How do I check that login and password entered is valid [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to create a login funcitonality in android studio in which I verify entered password and login exist in database and go together(based on information in the login database) This should happen when the user clicks "button check login"
If the info is accurate it should take the user to a welcome screen.
I am struggling with how to check the information according to the database. Please help!
Please look at following :
DataBaseHelper.java
package com.example.login;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
LoginDataBaseAdapter.java
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method to openthe Database
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
// Method to close the Database
public void close()
{
db.close();
}
// method returns an Instance of the Database
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
// method to insert a record in Table
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each column.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show();
}
// method to delete a Record of UserName
public int deleteEntry(String UserName)
{
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
// method to get the password of userName
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
return "NOT EXIST";
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
return password;
}
// Method to Update an Existing Record
public void updateEntry(String userName,String password)
{
// create object of ContentValues
ContentValues updatedValues = new ContentValues();
// Assign values for each Column.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}
SignUpActivity.java
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword;
Button btnCreateAccount;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password Does Not Matches", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
Please follow pseduo code:
final String email = emailEditText.getText().toString();
if (!isValidEmail(email)) {
emailEditText.setError("Invalid Email");
}
final String pass = passEditText.getText().toString();
if (!isValidPassword(pass)) {
passEditText.setError("Invalid Password");
}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
private boolean isValidPassword(String pass) {
if (pass != null && pass.length() > 6) {
return true;
}
return false;
}

Change Password In SQLite Database in Android

I'm using SQLite Database for insert , create or update data in my application.I want to change the password in my SQLite database.I'm having problem for change the password in my app. When I run the demo and enter the whatever field is there and hit the Button for change the data in database it goes to else condition. Nothing to show any error or exceptions in log cat. Is there any way to do that? Here is my code.
This is my DBHelper class
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(DataBase_Adapter.DATABASE_CREATE_LOGIN);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to "+_newVersion + ", which will destroy all old data");
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
onCreate(_db);
}
}
This DataBaseAdapter Class Code
public static final String TABLE_NAME_LOGIN="LOGIN";
//Colum,n Names
public static final String KEY_LOGIN_ID="ID";
public static final String KEY_USERNAME="USERNAME";
public static final String KEY_EMAIL_ID="EMAILID";
public static final String KEY_PASSWORD="PASSWORD";
//Table Create Statement
public static final String DATABASE_CREATE_LOGIN = "CREATE TABLE "+TABLE_NAME_LOGIN+" ("+KEY_LOGIN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_USERNAME+" TEXT, "+KEY_EMAIL_ID+" TEXT, "+KEY_PASSWORD+" TEXT)";
//Insert Data in Database Login
public void insertEntry(String userName,String userEmail,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_USERNAME , userName);
newValues.put(KEY_EMAIL_ID , userEmail);
newValues.put(KEY_PASSWORD , password);
// Insert the row into your table
db.insert(TABLE_NAME_LOGIN, null, newValues);
}
//Update Query
public boolean change(String strEmailId , String strNewPin1 )
{
Cursor cur=db.rawQuery("UPDATE "+TABLE_NAME_LOGIN +" SET " + KEY_PASSWORD+ " = '"+strNewPin1+"' WHERE "+ KEY_EMAIL_ID +"=?", new String[]{strEmailId});
if (cur != null)
{
if(cur.getCount() > 0)
{
return true;
}
}
return false;
}
This is my Change Pin Activity
public class Change_Pin_Activity7 extends Activity
{
EditText editText_EmailId , editText_changePin1 , editText_changePin2;
Button buttonChangePin;
TextView textView_PasswordMatch;
String strEmailId , strNewPin1 , strNewPin2;
boolean storedNewData;
DataBase_Adapter dbAdapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.change_pin_activity7);
dbAdapter=new DataBase_Adapter(this);
dbAdapter=dbAdapter.open();
editText_EmailId=(EditText)findViewById(R.id.EditText_EmailId);
editText_changePin1=(EditText)findViewById(R.id.EditText_Pin1);
editText_changePin2=(EditText)findViewById(R.id.EditText_Pin2);
textView_PasswordMatch=(TextView)findViewById(R.id.TextView_PinProblem);
buttonChangePin=(Button)findViewById(R.id.button_ChangePin);
buttonChangePin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
strEmailId = editText_EmailId.getText().toString().trim();
strNewPin1 = editText_changePin1.getText().toString().trim();
strNewPin2 = editText_changePin2.getText().toString().trim();
storedNewData=dbAdapter.change(strEmailId , strNewPin1);
if (strNewPin1.equals(storedNewData))
{
textView_PasswordMatch.setText("Password Match !!!");
Toast.makeText(Change_Pin_Activity7.this,
"Pin Change Successfully", Toast.LENGTH_LONG).show();
}
// check if any of the fields are vaccant
if(strEmailId.equals("")||strNewPin1.equals("")||strNewPin2.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!strNewPin1.equals(strNewPin2))
{
Toast.makeText(getApplicationContext(), "Pin does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
Toast.makeText(getApplicationContext(),"Not Working ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
dbAdapter.close();
}
}
When is if (strNewPin1.equals(storedNewData)) ever going to succeed, if strNewPin1 is a String, and storedNewData is a boolean.

Categories

Resources