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))";
Related
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
I have a SQLdatabase and I want to delete entries that are displayed in a list view using a button that is next to each entry on the list view. But currently it is not letting me delete.
This problem is located in the selectionargs variable as shown below. If I put a number e.g. 1, into the selectionargs manually it will work, but I have been trying to do it through the a variable that represents each entry. This does not result in an error but just goes straight to the toast message cannot delete. ac.ID refers to the adapter class and the ID of the list item entries.
Bookmark class:
public class Bookmark extends AppCompatActivity {
myAdapter myAdapter;
DBManager db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookmark);
db = new DBManager(this);
onLoadAttraction();
// onLoadTransport();
}
public void onLoadAttraction() {
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkAttraction",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, cursor.getString(cursor.getColumnIndex(DBManager.ColOpening))
, cursor.getString(cursor.getColumnIndex(DBManager.ColClosing))
, cursor.getString(cursor.getColumnIndex(DBManager.ColNearbyStop))
,null,null,null, null, null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
public void onLoadTransport(){
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkTransport",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, null
, null
, null
,cursor.getString(cursor.getColumnIndex(DBManager.ColTime))
,cursor.getString(cursor.getColumnIndex(DBManager.ColNextStop))
, cursor.getString(cursor.getColumnIndex(DBManager.ColPhoneNumber))
,null,null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
Adapter ac;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_bookmark, null);
ac = listItem.get(position);
TextView Type = (TextView) myView.findViewById(R.id.BMType);
Type.setText(ac.Type);
TextView Name = (TextView) myView.findViewById(R.id.BMName);
Name.setText(ac.Name);
TextView Location = (TextView) myView.findViewById(R.id.BMLocation);
Location.setText(ac.Location);
TextView Opening = (TextView) myView.findViewById(R.id.BMOpen);
Opening.setText(ac.Opening);
TextView Closing = (TextView) myView.findViewById(R.id.BMClose);
Closing.setText(ac.Closing);
TextView NearbyStop1 = (TextView) myView.findViewById(R.id.BMNearbyStop);
NearbyStop1.setText(ac.NearbyStop);
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] selectionArgs = {ac.ID};
int count = db.Delete("BookmarkAttraction","ID=? ",selectionArgs);
if (count > 0) {
onLoadAttraction();
Toast.makeText(getApplicationContext(),"Data deleted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Cannnot delete", Toast.LENGTH_LONG).show();
}
}
});
return myView;
}
}
}
DBManager class:
public class DBManager {
private SQLiteDatabase sqlDB;
static final String ColId = "ID";
static final String DBName = "InternalDB";
static final String TableName = "BookmarkAttraction";
static final String TableName2 = "BookmarkTransport";
static final String TableName3 = "Itinerary";
static final String ColItineraryName = "ItineraryName";
static final String ColDate = "Date";
static final String ColType = "Type";
static final String ColName = "Name";
static final String ColLocation = "Location";
static final String ColOpening = "OpeningTime";
static final String ColClosing = "ClosingTime";
static final String ColNearbyStop = "NerbyStop1";
static final String ColTime = "Time";
static final String ColNextStop = "NextStop";
static final String ColPhoneNumber = "PhoneNumber";
static final int DBVersion = 1;
static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";
static final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ColType + " TEXT,"
+ ColName + " TEXT,"
+ ColLocation + " TEXT,"
+ ColTime+ " TEXT,"
+ ColNextStop + " TEXT,"
+ ColPhoneNumber + " TEXT);";
static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
+ ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";
static class DBHelper extends SQLiteOpenHelper{
Context context;
DBHelper(Context context){
super(context, DBName, null, DBVersion);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
db.execSQL(CreateTable);
Toast.makeText(context,"Table is created ", Toast.LENGTH_LONG).show();
db.execSQL(CreateTabe2);
Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
db.execSQL(CreateTable3);
Toast.makeText(context,"Itin table created", Toast.LENGTH_LONG).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TableName);
db.execSQL("DROP TABLE IF EXISTS" + TableName2);
db.execSQL("DROP TABLE IF EXISTS" + TableName3);
onCreate(db);
}
}
public DBManager(Context context){
DBHelper db = new DBHelper(context);
sqlDB = db.getWritableDatabase();
}
public long Insert(String tablename,ContentValues values){
long ID = sqlDB.insert(tablename,"",values);
return ID;
}
public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tablename);
Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
return cursor;
}
public int Delete(String tablename,String selection, String[] selectionArgs){
int count = sqlDB.delete(tablename,selection,selectionArgs);
return count;
}
}
Adapter class:
public class Adapter {
public String ID;
public String Type;
public String Name;
public String Location;
public String Opening;
public String Closing;
public String NearbyStop;
public String Time;
public String NextStop;
public String PhoneNumber;
public String Latitude;
public String Longitude;
public Adapter(String type, String name, String location, String opening, String closing,
String nearbyStop, String time, String nextStop, String phoneNumber, String Latitude,
String Longitude) {
this.Type = type;
this.Name = name;
this.Location = location;
this.Opening = opening;
this.Closing = closing;
this.NearbyStop = nearbyStop;
this.Time = time;
this.NextStop = nextStop;
this.PhoneNumber = phoneNumber;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
}
The code for the delete button is in my bookmark class with the DBManager holding the actual delete code. If anyone can help with this it would be greatly appreciated.
Remove the ac field of your myAdapter class, and use it as a method variable inside the getView method.
Then use the ListView.setOnItemClickListener method to add an on click listener with positional awareness. (do this only once after you set the adapter) This way you can do listItem.get(position) to get the item in that position.
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
I have two tables: user and balance.
User DAO:
public class NewUserDAO {
public static final String TAG = "NewUserDAO";
public static final String TABLE_NEWUSER = "newUser";
//database fields
private SQLiteDatabase mDataBase;
private DatabaseHandler mDbHelper;
private Context mContext;
private String [] mAllColumns = {
DatabaseHandler.COLUMN_NEWUSER_ID,
DatabaseHandler.COLUMN_NEWUSER_NAME, DatabaseHandler.COLUMN_NEW_USER_PASSWORD,
DatabaseHandler.COLUMN_NEW_USER_AGE };
public NewUserDAO(Context context){
this.mContext = context;
mDbHelper = new DatabaseHandler(context);
try{
open();
} catch (SQLException e){
Log.e(TAG,"SQLexception on opening database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException{
mDataBase = mDbHelper.getWritableDatabase();
}
public void close(){
mDbHelper.close();
}
public void createNewUser(NewUserTable newUserTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_NEWUSER_NAME,newUserTable.getName());
values.put(DatabaseHandler.COLUMN_NEW_USER_PASSWORD, newUserTable.getPassword());
values.put(DatabaseHandler.COLUMN_NEW_USER_AGE, newUserTable.getAge());
mDataBase.insert(TABLE_NEWUSER, null, values);
mDataBase.close();
}
}
balance DAO:
public class BalanceDAO {
public static final String TAG = "BalanceDAO";
public static final String TABLE_BALANCE = "balanceOfUser";
private Context mContext;
//Database fields
private SQLiteDatabase mDatabase;
private DatabaseHandler mDhelper;
private String[] mAllColumns = {
DatabaseHandler.COLUMN_BALANCE_ID,
DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,
DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,
DatabaseHandler.COLUMN_BALANCE_NEW_USER_ID
};
public BalanceDAO (Context context){
mDhelper = new DatabaseHandler(context);
this.mContext = context;
try{
open();
}
catch (SQLException e){
Log.e(TAG, "SQLException on openning database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDhelper.getWritableDatabase();
}
public void close(){
mDhelper.close();
}
public void createBalance (BalanceTable balanceTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,balanceTable.getDollarBalance());
values.put(DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,balanceTable.getRubBalance());
mDatabase.insert(TABLE_BALANCE, null, values);
mDatabase.close();
}
}
And SQLiteOpenHelper class:
public class DatabaseHandler extends SQLiteOpenHelper {
//COLUMNS OF THE NEW USER TABLE
public static final String TABLE_NEWUSER = "newUser";
public static final String COLUMN_NEWUSER_ID = "id";
public static final String COLUMN_NEWUSER_NAME = "name";
public static final String COLUMN_NEW_USER_PASSWORD = "password";
public static final String COLUMN_NEW_USER_AGE = "age";
//COLUMNS OF THE BALANCE TABLE
public static final String COLUMN_BALANCE_ID = "id";
public static final String TABLE_BALANCE = "balanceOfUser";
public static final String COLUMN_BALANCE_DOLLARBALANCE = "dollarBalance";
public static final String COLUMN_BALANCE_RUBBALANCE = "rubBalance";
public static final String COLUMN_BALANCE_NEW_USER_ID = "newUserId";
private static final String DATABASE_NAME = "webStore";
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_NEWUSER = "CREATE TABLE " + TABLE_NEWUSER + "("
+ COLUMN_NEWUSER_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_NEWUSER_NAME + " TEXT not null,"
+ COLUMN_NEW_USER_PASSWORD + " TEXT not null,"
+ COLUMN_NEW_USER_AGE + " INTEGER"
+ ")";
db.execSQL(SQL_CREATE_NEWUSER);
String SQL_CREATE_BALANCE = "CREATE TABLE " + TABLE_BALANCE + "("
+ COLUMN_BALANCE_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_BALANCE_DOLLARBALANCE + " INTEGER,"
+ COLUMN_BALANCE_RUBBALANCE + " INTEGER,"
+ COLUMN_BALANCE_NEW_USER_ID + " INTEGER," + "FOREIGN KEY("+COLUMN_BALANCE_NEW_USER_ID+") REFERENCES "
+ TABLE_NEWUSER + "(id) "+ ")" ;
db.execSQL(SQL_CREATE_BALANCE);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWUSER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BALANCE);
}
}
I want to join user and balance tables. How can i do? When i call Create Method, i have exception.
public void CreateUser(View view) {
etName = (EditText)findViewById(R.id.etName);
etPassword = (EditText)findViewById(R.id.etPassword);
etAge = (EditText)findViewById(R.id.etAge);
String name = String.valueOf(etName.getText());
String password = String.valueOf(etPassword.getText());
int age = Integer.parseInt(String.valueOf(etAge.getText()));
BalanceTable balanceTable = new BalanceTable(0,0);
NewUserTable newUserTable = new NewUserTable(name,password,age);
//write to database of user from our edit texts
DatabaseHandler databaseHandler = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
NewUserDAO dbForUser = new NewUserDAO(this);
dbForUser.createNewUser(newUserTable);
BalanceDAO balanceDAO = new BalanceDAO(this);
balanceDAO.createBalance(balanceTable);
}
From edit text i take data. Help please
There are a few types if join, inner (which I think is what you want) which shows the data that matches, left showing all data from the first table and any additional data from the second table that meets the on condition or right which is shows all from the second table and any form the right that matches.
to Join two table you must use a statement such as
"SELECT <all the values you want> "+
" FROM users" +
" left join balance" +
" ON users.id=balance.userid " +
" where <some condition> "+
" order by gmttimestamp ;"; "
this will give you result set of mixed tables
I'm having a problem using my database to check the username and password of the user. I'm using a query to select the specific row and then check the password against what was entered by the user. The error I am getting is a java.lang.NullPointerException in my login page when i call the
Users userlogin = db.userlogin(usernameinput);
After looking at the method I'm thinking its the first cursor that causes it to fail
cursor.getInt(0);
What I'm wondering is am I right in thinking this and what can I do to change it?
I've tried changing the if statement to
If(cursor.getcount() > 0)
and still no luck.
public class LoginPage extends ActionBarActivity {
Button loginbutton;
EditText usernameuser, passworduser;
DatabaseHandler db;
String usernameinput, passwordinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
loginbutton = (Button) findViewById(R.id.loginbtn);
usernameuser = (EditText) findViewById(R.id.usernameInsert);
passworduser = (EditText) findViewById(R.id.passwordInsert);
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usernameinput = usernameuser.getText().toString();
passwordinput = passworduser.getText().toString();
Users userlogin = db.userLogin(usernameinput);
if (usernameinput.equals(userlogin.get_username()) && passwordinput.equals(userlogin.get_password())) {
startActivity(new Intent(getApplicationContext(), Home_Page.class));
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
Database handler Query used to check login:
public Users userLogin(String username) {
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, projection, selection, selectionargs, null, null,null );
if (cursor != null)
cursor.moveToFirst();
Users users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getDouble(6),
cursor.getDouble(7),
cursor.getDouble(8),
cursor.getDouble(9),
cursor.getDouble(10),
cursor.getDouble(11),
cursor.getDouble(12),
cursor.getDouble(13),
cursor.getDouble(14),
cursor.getDouble(15),
cursor.getDouble(16),
cursor.getDouble(17),
cursor.getDouble(18),
cursor.getDouble(19));
cursor.close();
return users;
}
04-08 13:05:33.194 2565-2565/com.example.john.fitnessapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.john.fitnessapp, PID: 2565
java.lang.NullPointerException
at com.example.john.fitnessapp.LoginPage$1.onClick(LoginPage.java:42)
at android.view.View.performClick(View.java:4569)
at android.view.View$PerformClick.run(View.java:18553)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
at dalvik.system.NativeStart.main(Native Method)
user class:
public class Users {
int _id, _age;
String _username, _password, _email, _gender;
double _startWeight, _currentWeight, _weightChange, _height, _BMI, _BMR, _reqCal, _monCal, _tuesCal, _wedCal, _thurCal, _friCal, _satCal, _sunCal;
public Users(){}
public Users(int _id, String _username, String _password, int _age, String _email, String _gender, double _height, double _startWeight,
double _currentWeight, double _weightChange, double _BMI, double _BMR, double _reqCal, double _monCal, double _tuesCal, double _wedCal,
double _thurCal, double _friCal, double _satCal, double _sunCal){
this._id = _id;
this._username = _username;
this._password = _password;
this._age = _age;
this._email = _email;
this._gender = _gender;
this._height = _height;
this._startWeight = _startWeight;
this._currentWeight = _currentWeight;
this._weightChange = _weightChange;
this._BMI = _BMI;
this._BMR = _BMR;
this._reqCal = _reqCal;
this._monCal = _monCal;
this._tuesCal = _tuesCal;
this._wedCal = _wedCal;
this._thurCal = _thurCal;
this._friCal = _friCal;
this._satCal = _satCal;
this._sunCal = _sunCal;
}
public int get_id(){
return this._id;
}
public void set_id(int id){
this._id = id;
}
public String get_username(){
return this._username;
}
public void set_username(String username){
this._username = username;
}
public String get_password(){
return this._password;
}
public void set_password(String password){
this._password = password;
}
public int get_age(){
return this._age;
}
public void set_age(int age){
this._age = age;
}
public String get_email(){
return this._email;
}
public void set_email(String email){
this._email = email;
}
public String get_gender(){
return this._gender;
}
public void set_gender(String gender){
this._gender = gender;
}
public double get_height(){
return this._height;
}
public void set_height(double height){
this._height = height;
}
public double get_startWeight(){
return this._startWeight;
}
public void set_startWeight(double startWeight){
this._startWeight = startWeight;
}
public double get_currentWeight(){
return this._currentWeight;
}
public void set_currentWeight(double currentWeight){
this._currentWeight = currentWeight;
}
public double get_weightChange(){
return this._weightChange;
}
public void set_weightChange(){
this._weightChange = _currentWeight - _startWeight;
}
public double get_BMI(){
return this._BMI;
}
public void set_BMI(double BMI){
this._BMI = BMI;
}
public double get_BMR(){
return this._BMR;
}
public void set_BMR(double BMR){
this._BMR = BMR;
}
public double get_reqCal(){
return this._reqCal;
}
public void set_reqCal(double reqCal){
this._reqCal = reqCal;
}
public double get_monCal(){
return this._monCal;
}
public void set_monCal(double monCal){
this._monCal = monCal;
}
public double get_tuesCal(){
return this._tuesCal;
}
public void set_tuesCal(double tuesCal){
this._tuesCal = tuesCal;
}
public double get_wedCal(){
return this._wedCal;
}
public void set_wedCal(double wedCal){
this._wedCal = wedCal;
}
public double get_thurCal(){
return this._thurCal;
}
public void set_thurCal(double thurCal){
this._thurCal = thurCal;
}
public double get_friCal(){
return this._friCal;
}
public void set_friCal(double friCal){
this._friCal = friCal;
}
public double get_satCal(){
return this._satCal;
}
public void set_satCal(double satCal){
this._satCal = satCal;
}
public double get_sunCal(){
return this._sunCal;
}
public void set_sunCal(double sunCal){
this._sunCal = sunCal;
}
}
Databasehandler:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String TAG = "DBHelper";
//DATABASE VERSION
private static int DATABASE_VERSION = 1;
//DATABASE NAME
private static final String DATABASE_NAME = "AppDatabase";
//TABLE NAMES
private static final String TABLE_USERS = "Users_Table";
private static final String TABLE_PRODUCTS = "Products_Table";
//COMMON COLUMN NAMES
private static final String KEY_USER_ID = "User_ID";
private static final String KEY_PRODUCT_ID = "Product_ID";
//USER TABLE
private static final String KEY_USERNAME = "Username";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_AGE = "Age";
private static final String KEY_EMAIL = "Email";
private static final String KEY_GENDER = "Gender";
private static final String KEY_HEIGHT = "Height";
private static final String KEY_CURRENT_WEIGHT = "Current_Weight";
private static final String KEY_START_WEIGHT = "Start_Weight";
private static final String KEY_WEIGHT_CHANGE = "Weight_Change";
private static final String KEY_BMI = "BMI";
private static final String KEY_BMR = "BMR";
private static final String KEY_REQ_CAL = "Required_Calories";
private static final String KEY_MON_CAL = "Monday_Calories";
private static final String KEY_TUES_CAL = "Tuesday_Calories";
private static final String KEY_WED_CAL = "Wednesday_Calories";
private static final String KEY_THUR_CAL = "Thursday_Calories";
private static final String KEY_FRI_CAL = "Friday_Calories";
private static final String KEY_SAT_CAL = "Saturday_Calories";
private static final String KEY_SUN_CAL = "Sunday_Calories";
//PRODUCT TABLE
private static final String KEY_ITEMNAME = "Item_name";
private static final String KEY_ITEMCALORIES = "Item_Calories";
//
private static final String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "( "
+ KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_AGE + " INTEGER, "
+ KEY_EMAIL + " TEXT, "
+ KEY_GENDER + " TEXT, "
+ KEY_HEIGHT + " DOUBLE, "
+ KEY_START_WEIGHT + " DOUBLE, "
+ KEY_CURRENT_WEIGHT + " DOUBLE, "
+ KEY_WEIGHT_CHANGE + " DOUBLE, "
+ KEY_BMI + " DOUBLE, "
+ KEY_BMR + " DOUBLE, "
+ KEY_REQ_CAL + " DOUBLE, "
+ KEY_MON_CAL + " DOUBLE, "
+ KEY_TUES_CAL + " DOUBLE, "
+ KEY_WED_CAL + " DOUBLE, "
+ KEY_THUR_CAL + " DOUBLE, "
+ KEY_FRI_CAL + " DOUBLE, "
+ KEY_SAT_CAL + " DOUBLE, "
+ KEY_SUN_CAL + " DOUBLE ); ";
private static final String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "( " + KEY_PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_ITEMNAME + " TEXT, "
+ KEY_ITEMCALORIES + " DOUBLE );";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG,
"Upgrading the database from version " + oldVersion + " to " + newVersion);
DATABASE_VERSION = 2;
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
Edit: Make sure you initialize your class that extends SQLiteOpenHelper.
Make sure you call:
db = new DatabaseHandler(this);
If you don't initialize db then it will be null when you call db.userLogin(usernameinput);, and that might be the cause of the NullPointerException that you're getting.
You could just call it in `onCreate()' like this:
public class LoginPage extends ActionBarActivity {
Button loginbutton;
EditText usernameuser, passworduser;
DatabaseHandler db;
String usernameinput, passwordinput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
db = new DatabaseHandler(this); //initialize the DatabaseHandler
//........
In addition, it looks like you're only querying three columns of the database, and trying to access twenty columns in the cursor.
Also, you should check the return value of cursor.moveToFirst().
In general, the cursor will never be null.
This will probably make it work short term, but you might want to consider re-factoring your code such that you don't have to query all rows to make it work:
public Users userLogin(String username) {
Users users = null;
SQLiteDatabase db = this.getReadableDatabase();
//String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, null, selection, selectionargs, null, null,null );
if (cursor.moveToFirst()){
users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getInt(3),
cursor.getString(4),
cursor.getString(5),
cursor.getDouble(6),
cursor.getDouble(7),
cursor.getDouble(8),
cursor.getDouble(9),
cursor.getDouble(10),
cursor.getDouble(11),
cursor.getDouble(12),
cursor.getDouble(13),
cursor.getDouble(14),
cursor.getDouble(15),
cursor.getDouble(16),
cursor.getDouble(17),
cursor.getDouble(18),
cursor.getDouble(19));
}
cursor.close();
return users;
}
Ideally you would create another constructor for your Users class that could just take the three parameters that you need in this case.
Your modified code would be something like this:
public Users userLogin(String username) {
Users users = null;
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD};
String selection = KEY_USERNAME + " =?";
String[] selectionargs = {username};
Cursor cursor = db.query(TABLE_USERS, projection, selection, selectionargs, null, null,null );
if (cursor.moveToFirst()){
users = new Users(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2))
}
cursor.close();
return users;
}
Also, it would be good to check for null return value from your userLogin() function:
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usernameinput = usernameuser.getText().toString();
passwordinput = passworduser.getText().toString();
Users userlogin = db.userLogin(usernameinput);
if (userlogin != null && usernameinput.equals(userlogin.get_username()) && passwordinput.equals(userlogin.get_password())) {
startActivity(new Intent(getApplicationContext(), Home_Page.class));
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
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;
}
}