Forgot password in android using SQLite - java

I implemented forgot password but i am getting an error. My db contains data.
Here is the logcat:
"E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.myapplication, PID: 8265
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.example.admin.myapplication.DatabaseHelper.updatepwd(java.lang.String, java.lang.String)' on a null object reference
at com.example.admin.myapplication.Reset$1.onClick(Reset.java:39)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)"
Below is the following code i have used:
Reset.java
public class Reset extends AppCompatActivity {
TextView phone;
EditText pwd,cpwd;
Button resetbtn;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset);
phone = (TextView)findViewById(R.id.Phonenumber);
pwd = (EditText) findViewById(R.id.pssword);
cpwd = (EditText) findViewById(R.id.pwdreenter);
resetbtn = (Button) findViewById(R.id.btnReset);
Intent intent = getIntent();
phone.setText(intent.getStringExtra("phone"));
resetbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = phone.getText().toString();
String pswd = pwd.getText().toString();
String repswd = cpwd.getText().toString();
if (pswd.equals(repswd)) {
Boolean pwd = db.updatepwd(user, pswd);
if (pwd) {
Intent intent1 = new Intent(getApplicationContext(), Login.class);
startActivity(intent1);
Toast.makeText(Reset.this, "Password Updated Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Reset.this, "Password NotUpdated Successfully", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Password Don't Match", Toast.LENGTH_SHORT).show();
}
}
});
//new code
public class MyTestDatabaseInstanceHolder {
public MyTestDBHandler DBHelper;
public static SQLiteDatabase m_ObjDataBase;
public static void createDBInstance(Context pContext){
if(DBHelper == null) {
DBHelper = new WLDBHandler(pContext);
m_cObjDataBase = DBHelper.openAndCreateDataBase();
}
}
}
Db.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "application.db";
public static final String TABLE_SIGNUP = "Signup";
public static final String COL_ID = "USER_ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE_NUMBER";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_CONFIRMPASSWORD = "CONFIRMPASSWORD";
public static final String COL_NAMEone_CON = "NAMEONE";
public static final String COL_NUMBERone_CON = "NUMBERONE";
public static final String COL_NAMEtwo_CON = "NAMETWO";
public static final String COL_NUMBERtwo_CON = "NUMBERTWO";
public static final String COL_NAMEthree_CON = "NAMETHREE";
public static final String COL_NUMBERthree_CON = "NUMBERTHREE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
// SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_SIGNUP + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ COL_NAME + " VARCHAR(255) , " + COL_PHONE + " VARCHAR (255) UNIQUE ," + COL_EMAIL + " VARCHAR (255) UNIQUE," + COL_PASSWORD + " VARCHAR (255), "
+ COL_CONFIRMPASSWORD + " VARCHAR (255)," + COL_NAMEone_CON + " VARCHAR (255), "
+ COL_NUMBERone_CON + " VARCHAR (255) UNIQUE ," + COL_NAMEtwo_CON + " VARCHAR (255)," + COL_NUMBERtwo_CON + " VARCHAR (255) UNIQUE , "
+ COL_NAMEthree_CON + " VARCHAR (255)," + COL_NUMBERthree_CON + " VARCHAR (255) UNIQUE " + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGNUP);
onCreate(db);
}
Boolean updatepwd(String PHONE_NUMBER, String PASSWORD) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("PASSWORD", PASSWORD);
long res= db.update("Signup", contentValues, "PHONE_NUMBER = ?", new String[]{PHONE_NUMBER});
db.close();
if(res == -1)
return false;
else
return true;
}

Related

Unfortunately Myapp has stopped after entering login details

I am developing an application and after I enter the login details the app crashes.I think the error is due to the problem of database linking and fetching and tried few solutions posted online, but nothing worked.
What can i do to solve this?
06-21 13:21:04.590 1913-1913/in.co.arrow E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.co.arrow, PID: 1913
java.lang.IllegalStateException: Couldn't read row 0, col 4 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at in.co.arrow.sql.SqliteHelper.Authenticate(SqliteHelper.java:140)
at in.co.arrow.LoginActivity$1.onClick(LoginActivity.java:55)
at android.view.View.performClick(View.java:6367)
at android.view.View$PerformClick.run(View.java:25032)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6753)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:482)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
here are my SqliteHelper and LoginActivity classes
package in.co.arrow;
public class LoginActivity extends AppCompatActivity {
EditText editTextEmail;
EditText editTextPassword;
TextInputLayout textInputLayoutEmail;
TextInputLayout textInputLayoutPassword;
Button buttonLogin;
SqliteHelper sqliteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sqliteHelper = new SqliteHelper(this);
initCreateAccountTextView();
initViews();
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User currentUser = sqliteHelper.Authenticate(new User(null,null,null,null,null,Email,Password,null,null,null,null,null,null));
if (currentUser != null) {
Snackbar.make(buttonLogin, "Successfully Logged in!", Snackbar.LENGTH_LONG).show();
/* Intent intent=new Intent(LoginActivity.this,HomeScreenActivity.class);
startActivity(intent);
finish(); */
} else {
Snackbar.make(buttonLogin, "Failed to log in , please try again", Snackbar.LENGTH_LONG).show();
}
}
}
});
}
private void initCreateAccountTextView() {
TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount);
textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>"));
textViewCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
private void initViews() {
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
}
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html) {
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
public boolean validate() {
boolean valid = false;
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
textInputLayoutEmail.setError("Please enter valid email!");
} else {
valid = true;
textInputLayoutEmail.setError(null);
}
if (Password.isEmpty()) {
valid = false;
textInputLayoutPassword.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
textInputLayoutPassword.setError(null);
} else {
valid = false;
textInputLayoutPassword.setError("Password is to short!");
}
}
return valid;
}
}
SqliteHelper.java
package in.co.arrow.sql;
public class SqliteHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "arrow";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String KEY_ID = "id";
public static final String KEY_USER_NAME = "username";
public static final String KEY_FIRST_NAME="firstname";
public static final String KEY_LAST_NAME="lastname";
public static final String KEY_MOBILE_NO="mobileno";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
public static final String KEY_FATHERS_NAME="fathersname";
public static final String KEY_GENDER="gender";
public static final String KEY_INST_NAME="instname";
public static final String KEY_DOB="dob";
public static final String KEY_BRANCH="branch";
public static final String KEY_YOP="yop";
public static final String SQL_TABLE_USERS = " CREATE TABLE " + TABLE_USERS
+ " ( "
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_USER_NAME + " TEXT, "
+ KEY_FIRST_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT,"
+ KEY_MOBILE_NO + " TEXT,"
+ KEY_EMAIL + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_FATHERS_NAME + " TEXT,"
+ KEY_GENDER + " TEXT,"
+ KEY_INST_NAME + " TEXT,"
+ KEY_DOB + " TEXT,"
+ KEY_BRANCH + " TEXT,"
+ KEY_YOP + " TEXT "
+ " ) ";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
}
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_NAME, user.userName);
values.put(KEY_FIRST_NAME, user.firstname);
values.put(KEY_LAST_NAME, user.lastname);
values.put(KEY_GENDER, user.gender);
values.put(KEY_FATHERS_NAME, user.fathersname);
values.put(KEY_MOBILE_NO, user.mobileno);
values.put(KEY_EMAIL, user.email);
values.put(KEY_PASSWORD, user.password);
values.put(KEY_DOB, user.dob);
values.put(KEY_INST_NAME,user.instname);
values.put(KEY_BRANCH, user.branch);
values.put(KEY_YOP, user.yop);
long todo_id = db.insert(TABLE_USERS, null, values);
}
public User Authenticate(User user) {
SQLiteDatabase db = this.getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
User user1;
user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3),cursor.getString(4), cursor.getString(5), cursor.getString(6),cursor.getString(7),cursor.getString(8),cursor.getString(9),cursor.getString(10),cursor.getString(11),cursor.getString(12));
if (user.password.equalsIgnoreCase(user1.password)) {
return user1;
}
}
return null;
}
public boolean isEmailExists(String email) {
SQLiteDatabase db = this.getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = db.query(TABLE_USERS,// Selecting Table
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{email},
null, null, null);
if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) {
return true;
}
return false;
}
}
Your cursor has only 4 columns:
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD}
but you are trying to read 13 columns out of it. It fails on the first non-existing one at index 4.
You can add all the columns you're reading to your projection.
Your isssue is that you have only specified 4 columns to be extracted into the cursor, yet you are trying to get data from 13 columns.
You could change :-
Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
to either :-
Cursor cursor = db.query(TABLE_USERS,
null, // <<<< gets all columns from the table
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
or :-
Cursor cursor = db.query(TABLE_USERS,
new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD, KEY_FIRST_NAME, KEY_LAST_NAME, KEY_GENDER, KEY_FATHERS_NAME, KEY_MOBILE_NO, KEY_DOB, KEY_INST_NAME, KEY_BRANCH, KEY_YOP},
KEY_EMAIL + "=?",
new String[]{user.email},
null, null, null);
The above two assuming that you want data from all columns.
or you could reduce the number of columns from which you retrieve data but that would depend upon what constructors are available for a User object.

SQLite Save Error NOT NULL Constraint

I have a local database in my app for storing user profiles from input fields. I have created the database using SQLiteOpenHelper class but after running my app, this error appears. I have been through the DatabaseHelper class but can't find what's wrong with it. I hope someone points out my mistake. Thanks.
my db class file here:
public class DBHelper {
private static final String DATABASE_NAME = "UsersDemo.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
//private static final String COL_PROFILE_PHOTO = "profilePhoto";
private Context mCtx;
private DatabaseManager databaseManager;
private SQLiteDatabase db;
public DBHelper(Context context){
this.mCtx = context;
databaseManager = new DatabaseManager(mCtx);
}
public DBHelper open() throws SQLException{
db = databaseManager.getWritableDatabase();
return this;
}
public void close(){
databaseManager.close();
}
public boolean saveInputField(TingTingUser user){
SQLiteDatabase userDb = databaseManager.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FULL_NAME, user.getDisplayName());
values.put(COL_USER_ID, user.getUserId());
values.put(COL_GENDER, user.getGender());
values.put(COL_DOB, user.getDob());
values.put(COL_MOBILE_NUM, user.getMobileNumber());
values.put(COL_ORGANIZATION, user.getOrganization());
values.put(COL_OCCUPATION, user.getOccupation());
long result = userDb.insert(TABLE_NAME, null, values);
userDb.close();
if (result == -1){
return false;
} else {
return true;
}
}
public TingTingUser getCurrentUser(int id){
SQLiteDatabase currDB = databaseManager.getWritableDatabase();
Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
return user;
}
return null;
}
public void saveCameraImage(byte[] imageBytes){
SQLiteDatabase camDb = databaseManager.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
camDb.insert(TABLE_NAME, null, contentValues);
}
public void saveGalleryImage(byte[] imageBytes){
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
db.insert(TABLE_NAME, null, contentValues);
}
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
}
The error occurs in my MainActivity when I call saveInputField() method of DBHelper, shown below:
JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
Log.d("OTPDialogFragment", "OTP Verified Successfully");
try {
JSONObject verifyObject = new JSONObject(response.toString());
JSONObject userObject = verifyObject.getJSONObject("user");
userId = userObject.getString("_id");
Log.d(TAG, "Retrieved user id is:\t" + userId);
TingTingUser user = new TingTingUser();
user.setDisplayName(fullName);
user.setMobileNumber(num);
user.setGender(genderVal);
user.setDob(dob);
user.setOccupation("default");
user.setOrganization("default");
user.setUserId(userId);
if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId)){
if (dbHelper.saveInputField(user) == true){ // error occurs here
Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show(); // Toast shows cos save failed, dont know why
}
}
Sorry guys, my mainactivity is too long, only showed what is necessary.
Error message in logcat:
android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.billionusers.tingting.db.DBHelper$DatabaseManager.onCreate(DBHelper.java:131)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:53)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:466)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:443)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
From the logcat
near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
and DBHelper.onCreate
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
Your create statement is invalid because you have put into comments the last line so it terminates in + COL_ORGANIZATION + " TEXT, "; which is not correct. The ending should be:
+ COL_ORGANIZATION + " TEXT ); ";

Android: Unable to insert data into SQLite using DbHelper and Contract class

public class Main2Activity extends AppCompatActivity {
private EditText editText1, editText2, editText3, editText4;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
editText4 = (EditText) findViewById(R.id.editText4);
button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String un, pw, cpw, ph;
un = editText1.getText().toString();
pw = editText2.getText().toString();
cpw = editText3.getText().toString();
ph = editText4.getText().toString();
DbHelper dbHelpero = new DbHelper(Main2Activity.this);
SQLiteDatabase db = dbHelpero.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Entry.C_UNAME, un);
values.put(Entry.C_PASS, pw);
values.put(Entry.C_CPASS, cpw);
values.put(Entry.C_PNO, ph);
long newRowId = db.insert(Entry.TABLE_NAME, null, values);
if (newRowId == -1) {
Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is the Contract.java
public class Contract {
private Contract() {
}
public static final class Entry implements BaseColumns {
public final static String TABLE_NAME = "details";
public final static String _ID = BaseColumns._ID;
public final static String C_UNAME = "uname";
public final static String C_PASS = "pw";
public final static String C_CPASS = "cpw";
public final static String C_PNO = "pno";
}
}
And the DbHelper.java
public class DbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = DbHelper.class.getSimpleName();
public final static String DATABASE_NAME = "contacts.db";
private static final int DATABASE_VERSION = 1;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
There are no syntax errors but still, the app is crashing.
Replace your CREATE_TABLE query with:
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
You can't have a TEXT type have an AUTOINCREMENT property as you currently have it on your _ID field. You need to change it to be an INTEGER so it can be used as PRIMARY KEY and then have it AUTOINCREMENT

Database using Eclipse

I am making a login screen which is connected to the database shown below, I have the class called DatabaseHelper which contains all my tables and functions, and the main.java contains the codes below, and the register.java contains the following codes :
package DatabaseHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ExpenseManager";
// Table Names
private static final String TABLE_user = "user";
private static final String TABLE_income = "income";
private static final String TABLE_store = "store";
// Common column names
private static final String KEY_ID = "uid";
// user Table - column names
public static final String KEY_username = "username";
public static final String KEY_password = "password";
private static final String KEY_email = "email";
private static final String KEY_url = "url";
private static final String KEY_amountalert = "amountalert";
private static final String KEY_currency = "currency";
// income Table - column names
private static final String KEY_IID = "iid";
private static final String KEY_INCOMEDATE = "Incomedate";
private static final String KEY_AMOUNT = "amount";
private static final String KEY_INCOMETYPE = "Incometype";
// store Table - column names
private static final String KEY_EID = "eid";
private static final String KEY_ITEM = "item";
private static final String KEY_PRICE = "price";
private static final String KEY_TYPE = "type";
private static final String KEY_DATE = "date";
private static final String KEY_PLACE = "place";
// Table Create Statements
// user table create statement
private static final String CREATE_TABLE_user = "CREATE TABLE "
+ TABLE_user + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_username + " TEXT," + KEY_password + " TEXT," + KEY_email
+ " TEXT, " + KEY_url + " TEXT," + KEY_amountalert + " FLOAT,"
+ KEY_INCOMETYPE + " TEXT," + KEY_currency + " TEXT," + ")";
// income table create statement
private static final String CREATE_TABLE_income = "CREATE TABLE "
+ TABLE_income + "(" + KEY_IID + " INTEGER PRIMARY KEY,"
+ KEY_AMOUNT + " TEXT," + KEY_ID + " INTEGER," + KEY_INCOMEDATE
+ " DATETIME," + KEY_INCOMETYPE + " TEXT, " + "FOREIGN KEY ("
+ KEY_ID + ") REFERENCES TABLE_user(uid))";
// store table create statement
private static final String CREATE_TABLE_store = "CREATE TABLE "
+ TABLE_store + "(" + KEY_EID + " INTEGER PRIMARY KEY," + KEY_ITEM
+ " TEXT," + KEY_PRICE + " FLOAT," + KEY_TYPE + " TEXT, "
+ KEY_PLACE + " TEXT, " + KEY_DATE + " DATETIME, " + KEY_ID
+ " INTEGER," + "FOREIGN KEY (" + KEY_ID
+ ") REFERENCES TABLE_user(uid))";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_user);
db.execSQL(CREATE_TABLE_income);
db.execSQL(CREATE_TABLE_store);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_user);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_income);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_store);
// create new tables
onCreate(db);
}
public DatabaseHelper open() {
return this;
}
public void close() {
db.close();
}
public void Login(String username,String password){
ContentValues values = new ContentValues();
String un = (String) values.get(username);
String ps = (String) values.get(password);
db.close();
}
public void insertEntry(String username,String password, String email, String url, String amountAlert){
ContentValues values = new ContentValues();
// Assign values for each row.
values.put("KEY_username", username);
values.put("KEY_password",password);
values.put("KEY_email",email);
values.put(KEY_url, url);
values.put(KEY_amountalert, amountAlert);
// Insert the row into your table
db.insert(TABLE_user, null, values);
db.close();
}
}
package com.example.dailyexpensemanager;
import info.androidhive.sqlite.model.user;
public class Main extends Activity {
private EditText username;
private EditText password;
private TextView attempts;
private Button login;
int counter = 3;
private DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView5);
attempts.setText(Integer.toString(counter));
login = (Button) findViewById(R.id.button1);
TextView registerScreen = (TextView) findViewById(R.id.sign);
final String getUsername=username.getText().toString();
final String getPassword=password.getText().toString();
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(i);
}
});
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dbHelper = new DatabaseHelper(getBaseContext());
dbHelper.open();
dbHelper.Login(getUsername, getPassword);
if ((getUsername.equals(DatabaseHelper.KEY_username)) && (getPassword.equals(DatabaseHelper.KEY_password))) {
Toast.makeText(getApplicationContext(),"Redirecting...",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Main.this,home.class);
startActivity(in);
} else {
Toast.makeText(Main.this, "Login failed", Toast.LENGTH_SHORT).show();
attempts.setBackgroundColor(Color.RED); counter--;
attempts.setText(Integer.toString(counter));
if(counter==0){
login.setEnabled(false); }
}
dbHelper.close();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.example.dailyexpensemanager;
public class RegisterActivity extends Activity {
private EditText username;
private EditText password;
private EditText passwordc;
private EditText email;
private EditText bank;
private EditText amount;
Button btnRegister;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
//Fill the spin
String array_spinner[];
array_spinner = new String[3];
array_spinner[0] = "Lebanese Lira (L.L)";
array_spinner[1] = "Dollar ($)";
array_spinner[2] = "Euro (€)";
Spinner s = (Spinner) findViewById(R.id.spin);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
//end spin filling
// Get References of Views
username=(EditText)findViewById(R.id.reg_fullname);
password=(EditText)findViewById(R.id.reg_password);
passwordc=(EditText)findViewById(R.id.reg_passwordc);
email=(EditText)findViewById(R.id.reg_email);
bank=(EditText)findViewById(R.id.bank);
amount=(EditText)findViewById(R.id.amount);
btnRegister=(Button)findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String getUsername=username.getText().toString();
String getPassword=password.getText().toString();
String getconfirmPassword=passwordc.getText().toString();
String getEmail=email.getText().toString();
String getBank =bank.getText().toString();
String getAmount=amount.getText().toString();
dbHelper = new DatabaseHelper(getBaseContext());
dbHelper.open();
dbHelper.insertEntry(getUsername, getPassword, getEmail, getBank, getAmount);
// check if any of the fields are vacant
if(getUsername.equals("")||getPassword.equals("")||getconfirmPassword.equals("")||getEmail.equals("")
||getBank.equals("")||getAmount.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!getPassword.equals(getconfirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
dbHelper.insertEntry(getUsername, getPassword, getEmail , getBank , getAmount );
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
dbHelper.close();
}
});
}
}
When running the application, it runs normally, my problem is, when pressing on login or on register button, the application will stop unexpectally. Please I want a solution for this problem .
There's an error here:
KEY_currency + " TEXT," + ")";
Please remove the extra comma:
KEY_currency + " TEXT" + ")";
[EDIT]
Here's another error (it occurs twice in your code)
REFERENCES TABLE_user(uid))";
It should be
REFERENCES user(uid))";

Inserting and updating data on multiple table on SQLite database

In my project, I created a SQLite database with using a class that extends SQLiteOpenHelper library in android to creating three tables in one database.
the problem is when in MainActivity class (comes below) I want to create and update a data row, instead of putting data in desired table, they saved only in "table3db" table and the other tables are still empty (I saw this condition with an application can browse SQLite databases), but I want to save each data in desired table. for example first and second data must be saved in first table and third must be in second table and fourth data integer must be save in third table.
what should I do to correct this problem??
for first step I created three Tables with below codes in DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db";
private static final int DATABASE_VERSION = 1;
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_VALUE2 = "value2";
private static final String TABLE_NAME = "table1db";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String COLUMN_ID_2 = "_id";
private static final String COLUMN_NAME_2 = "name";
private static final String COLUMN_VALUE_2 = "value";
private static final String COLUMN_VALUE2_2 = "value2";
private static final String TABLE_NAME_2 = "table2db";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_2 + " INTEGER," +
COLUMN_VALUE_2 + " INTEGER," +
COLUMN_VALUE2_2 + " TEXT" +
");";
private static final String COLUMN_ID_3 = "_id";
private static final String COLUMN_NAME_3 = "name";
private static final String COLUMN_VALUE_3 = "value";
private static final String COLUMN_VALUE2_3 = "value2";
private static final String TABLE_NAME_3 = "table3db";
private static final String CREATE_TABLE_3 = "CREATE TABLE " + TABLE_NAME_3 + " (" +
COLUMN_ID_3 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME_3 + " INTEGER," +
COLUMN_VALUE_3 + " INTEGER," +
COLUMN_VALUE2_3 + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_2);
Log.i(TAG, "editTexts Table created.");
db.execSQL(CREATE_TABLE);
Log.i(TAG, "Table created.");
db.execSQL(CREATE_TABLE_3);
Log.i(TAG, "Table created.");
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(TAG, "Object created.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
newVersion=oldVersion+1;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
onCreate(db);
}
public String getTableName(int tableNumber) {
String out="";
switch (tableNumber){
case 1:
out=TABLE_NAME;
case 2:
out=TABLE_NAME_2;
case 3:
out=TABLE_NAME_3;
}
return out;
}
public String getRowIdName(int tableNumber) {
String out="";
switch (tableNumber){
case 1:
out=COLUMN_ID;
case 2:
out=COLUMN_ID_2;
case 3:
out=COLUMN_ID_3;
}
return out;
}
}
Then I created this class to use DatabaseHelper class with following code by the name of DatabaseHandler
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String VALUE2 = "value2";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "DatabaseHelper Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertCBox(int tableNumber, CBox checkBox) {
ContentValues cv = new ContentValues();
cv.put(NAME, checkBox.getName());
cv.put(VALUE, checkBox.getStatus());
cv.put(VALUE2, checkBox.getText());
database.insert(dbHelper.getTableName(tableNumber), NAME, cv);
Log.i(TAG, "Contact added successfully.");
}
public void deleteCheckBox(int tableNumber, int id) {
database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public void updateCheckBox(int tableNumber, int id,int name,int state, String text) {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(VALUE, state);
cv.put(VALUE2, text);
database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public CBox getCBox(int tableNumber, int id){
Log.i(TAG, "getCBOX started");
Cursor cursor = database.query(dbHelper.getTableName(tableNumber), null, null, null, null, null, null);
Log.i(TAG, "cursor query done");
cursor.moveToFirst();
cursor.moveToPosition(id-1);
Log.i(TAG, "cursor is here: "+ cursor.getPosition());
// cursor.moveToPosition(id--);
Log.i(TAG, "cursor moved to position successfully "+ id--);
CBox CBox = cursorToContact(cursor);
Log.i(TAG, "cursor to contact done");
cursor.close();
Log.i(TAG, "cursor closed");
return CBox;
}
public void clearTable(int tableNumber) {
database.delete(dbHelper.getTableName(tableNumber), null, null);
}
private CBox cursorToContact(Cursor cursor) {
CBox checkBox = new CBox();
Log.i(TAG, "cursor to contact > started");
checkBox.setId(cursor.getInt(0));
Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
checkBox.setName(cursor.getInt(1));
Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
checkBox.setStatus(cursor.getInt(2));
Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
checkBox.setText(cursor.getString(3));
Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());
return checkBox;
}
}
for 3rd step in my Mainactivity class I used following codes to use database and inserting and updating and saving data:
public class MainActivity extends Activity {
private DatabaseHandler dbHandler;
private static final int databaseTableNumber1=1;
private static final int databaseTableNumber2=2;
private static final int databaseTableNumber3=3;
private CBox cBox01;
private CBox cBox02;
private CBox cBox03;
private CBox cBox04;
private boolean firstRunPassed=false;
private SharedPreferences sharedperefs;
private String preferenceName = "Preferences";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i(TAG, "On Create");
setContentView(R.layout.activity_main);
dbHandler = new DatabaseHandler(this);
final Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dbHandler.open();
int state;
String text;
CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
if(checkBox01.isChecked()) state=1; else state=0;
dbHandler.updateCheckBox(databaseTableNumber1,1,R.id.checkBox1,state,"");
RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
state= radioGroup01.getCheckedRadioButtonId();
dbHandler.updateCheckBox(databaseTableNumber1,2, R.id.radioGroup1, state,"");
EditText editText01=(EditText) findViewById(R.id.editText1);
text=editText01.getText().toString();
dbHandler.updateCheckBox(databaseTableNumber2,1, R.id.editText1,state,text);
ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
if(toggleButton01.isChecked()) state=1; else state=0;
dbHandler.updateCheckBox(databaseTableNumber3,1,R.id.toggleButton1,state,"");
dbHandler.close();
}
});
}
#Override
protected void onPause(){
super.onPause();
Log.i(TAG, "On Pause");
sharedperefs = getSharedPreferences(preferenceName, MODE_PRIVATE);
SharedPreferences.Editor editor =sharedperefs.edit();
firstRunPassed=true;
editor.putBoolean("firstRunPassed", firstRunPassed);
editor.commit();
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume");
sharedperefs=getSharedPreferences(preferenceName, MODE_PRIVATE);
firstRunPassed=sharedperefs.getBoolean("firstRunPassed", false);
dbHandler.open();
Log.i(TAG, "dbhandler opened");
if(firstRunPassed){
cBox01=new CBox();
cBox01=dbHandler.getCBox(databaseTableNumber1,1);
CheckBox checkBox01= (CheckBox) findViewById(R.id.checkBox1);
if(cBox01.getStatus()==1)
checkBox01.setChecked(true);
else
checkBox01.setChecked(false);
cBox02=new CBox();
cBox02=dbHandler.getCBox(databaseTableNumber1,2);
RadioGroup radioGroup01=(RadioGroup) findViewById(R.id.radioGroup1);
radioGroup01.check(cBox02.getStatus());
cBox03=new CBox();
cBox03=dbHandler.getCBox(databaseTableNumber2,4);
EditText editText01=(EditText) findViewById(R.id.editText1);
editText01.setText(cBox03.getText());
cBox04=new CBox();
cBox04=dbHandler.getCBox(databaseTableNumber3,1);
ToggleButton toggleButton01 =(ToggleButton) findViewById(R.id.toggleButton1);
if(cBox04.getStatus()==1)
toggleButton01.setChecked(true);
else
toggleButton01.setChecked(false);
} else {
cBox01 = new CBox(); cBox01.setId(1); cBox01.setName(R.id.checkBox1); cBox01.setStatus(0); cBox01.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox01);
cBox02 = new CBox(); cBox02.setId(2); cBox02.setName(R.id.radioGroup1); cBox02.setStatus(0); cBox02.setText(""); dbHandler.insertCBox(databaseTableNumber1,cBox02);
cBox03 = new CBox(); cBox03.setId(1); cBox03.setName(R.id.editText1); cBox03.setStatus(0); cBox03.setText("Start please"); dbHandler.insertCBox(databaseTableNumber2,cBox03);
cBox04 = new CBox(); cBox04.setId(1); cBox04.setName(R.id.toggleButton1); cBox04.setStatus(0); cBox04.setText(""); dbHandler.insertCBox(databaseTableNumber3,cBox04);
}
dbHandler.close();
Log.i(TAG, "dbhandler closed");
}
}
and the CBox is my last class, used for setting and getting data cells:
public class CBox {
private int id;
private int name;
private int Status;
private String text;
private String unit;
public long getId() {
return id;
}
public String getIdInString() {
return Long.toString(id);
}
public int getName() {
return name;
}
public int getStatus() {
return Status;
}
public String getText() {
return text;
}
public String getUnit() {
return unit;
}
public void setId(int id) {
this.id = id;
}
public void setName(int name) {
this.name = name;
}
public void setStatus(int status) {
this.Status = status;
}
public void setText(String text) {
this.text = text;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
I did it at last. :D
I don't what was the problem but with changing the DatabaseHelper and Database Helperclass as below and changing input variable of functions used in this class to string, the problems had been eliminated.
here is the DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "database";
private static final int DATABASE_VERSION = 1;
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_VALUE2 = "value2";
private static final String TABLE_NAME_1 = "table1db";
private static final String CREATE_TABLE_1 = "CREATE TABLE " + TABLE_NAME_1 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String TABLE_NAME_2 = "table2db";
private static final String CREATE_TABLE_2 = "CREATE TABLE " + TABLE_NAME_2 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
private static final String TABLE_NAME_3 = "table3db";
private static final String CREATE_TABLE_3 = "CREATE TABLE " + TABLE_NAME_3 + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " INTEGER," +
COLUMN_VALUE + " INTEGER," +
COLUMN_VALUE2 + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1); Log.i(TAG, "Table 1 created.");
db.execSQL(CREATE_TABLE_2); Log.i(TAG, "Table 2 created.");
db.execSQL(CREATE_TABLE_3); Log.i(TAG, "Table 3 created.");
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.i(TAG, "Object created.");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
newVersion=oldVersion+1;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_1 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_2 + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_3 + ";");
onCreate(db);
}
public String getTableName(String tableNumber) {
return tableNumber;
}
public String getRowIdName(String tableNumber) {
return COLUMN_ID;
}
}
and the Database Handler class:
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String VALUE2 = "value2";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "DatabaseHelper Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertCBox(String tableNumber, CBox checkBox) {
ContentValues cv = new ContentValues();
cv.put(NAME, checkBox.getName());
cv.put(VALUE, checkBox.getStatus());
cv.put(VALUE2, checkBox.getText());
database.insert(dbHelper.getTableName(tableNumber), null, cv);
Log.i(TAG, "Contact added successfully.");
}
public void deleteCheckBox(String tableNumber, int id) {
database.delete(dbHelper.getTableName(tableNumber), dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public void updateCheckBox(String tableNumber, int id,int name,int state, String text) {
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(VALUE, state);
cv.put(VALUE2, text);
database.update(dbHelper.getTableName(tableNumber), cv, dbHelper.getRowIdName(tableNumber) + "=" + id, null);
}
public CBox getCBox(String tableNumber, int id){
Log.i(TAG, "getCBOX started");
Cursor cursor = database.query(true,dbHelper.getTableName(tableNumber), null, null, null, null, null, null, null);
Log.i(TAG, "cursor query done");
cursor.moveToPosition(id-1);
Log.i(TAG, "cursor is here: "+ cursor.getPosition());
// cursor.moveToPosition(id--);
Log.i(TAG, "cursor moved to position successfully "+ (id-1));
CBox CBox = cursorToContact(cursor);
Log.i(TAG, "cursor to contact done");
cursor.close();
Log.i(TAG, "cursor closed");
return CBox;
}
public void clearTable(String tableNumber) {
database.delete(dbHelper.getTableName(tableNumber), null, null);
}
private CBox cursorToContact(Cursor cursor) {
CBox checkBox = new CBox();
Log.i(TAG, "cursor to contact > started");
checkBox.setId(cursor.getInt(0));
Log.i(TAG, "cursor to contact > getInt(0) done " + checkBox.getId());
checkBox.setName(cursor.getInt(1));
Log.i(TAG, "cursor to contact > getInt(1) done " + checkBox.getName());
checkBox.setStatus(cursor.getInt(2));
Log.i(TAG, "cursor to contact > getInt(2) done " + checkBox.getStatus());
checkBox.setText(cursor.getString(3));
Log.i(TAG, "cursor to contact > getString(3) done " + checkBox.getText());
return checkBox;
}
}

Categories