Related
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;
}
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.
I know this question has been asked several times, but I just can't get the right syntax for my problem.
I want to sum my value of "einnahmen".
This is my SqlDbHelper class:
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "nr";
public static final String COLUMN2 = "name";
public static final String COLUMN3 = "einnahmen";
public static final String COLUMN4 = "ausgaben";
public static final String COLUMN5 = "datum";
private static final String SCRIPT_CREATE_DATABASE =
"create table "+ DATABASE_TABLE
+ " (" + COLUMN1+ " integer primary key autoincrement, "
+ COLUMN2+ " text not null, "
+ COLUMN3 + " text not null, "
+ COLUMN4 + " text not null, "
+ COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
This is my MainActivity:
public class BookActivity extends Activity {
SqlHandler sqlHandler;
ListView lvCustomList;
EditText etName, etEinnahmen, etAusgaben, etDatum;
ImageButton btn_add;
TextView gesamteinnahmen;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
gesamteinnahmen = (TextView) findViewById(R.id.tVgesamtEinnahmen);
lvCustomList = (ListView) findViewById(R.id.lv_custom_list);
etName = (EditText) findViewById(R.id.et_name);
etEinnahmen = (EditText) findViewById(R.id.et_einnahmen);
etAusgaben = (EditText) findViewById(R.id.et_ausgaben);
etDatum = (EditText) findViewById(R.id.et_datum);
btn_add = (ImageButton) findViewById(R.id.btn_add);
sqlHandler = new SqlHandler(this);
showList();
btn_add.setOnClickListener(new OnClickListener() {
#SuppressLint("ShowToast")
#Override
public void onClick(View v) {
String name = etName.getText().toString();
String einnahmen = etEinnahmen.getText().toString();
String ausgaben = etAusgaben.getText().toString();
String datum = etDatum.getText().toString();
if (TextUtils.isEmpty(name)) {etName.setError("Das Feld ist leer");return;}
else if (TextUtils.isEmpty(einnahmen)) {etEinnahmen.setError("Das Feld ist leer");return;
} else if (TextUtils.isEmpty(ausgaben)) {etAusgaben.setError("Das Feld ist leer");return;
} else if (TextUtils.isEmpty(datum)) {etDatum.setError("Das Feld ist leer");return;
} else {
Toast.makeText(BookActivity.this,"Daten wurden erfolgreich gespeichert", Toast.LENGTH_SHORT).show();
String query = "INSERT INTO PHONE_CONTACTS(name,einnahmen,ausgaben,datum) values " +
"('" + name + "','" + einnahmen +"','" + ausgaben + "','" + datum + "')";
sqlHandler.executeQuery(query);
showList();
etName.setText("");
etEinnahmen.setText("");
etAusgaben.setText("");
etDatum.setText("");
}
}
});
}
private void showList() {
ArrayList contactList = new ArrayList();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS";
Cursor c1 = sqlHandler.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
ContactListItems contactListItems = new ContactListItems();
contactListItems.setNr(c1.getString(c1.getColumnIndex("nr")));
contactListItems.setName(c1.getString(c1.getColumnIndex("name")));
contactListItems.setEinnahmen(c1.getString(c1.getColumnIndex("einnahmen")));
contactListItems.setAusgaben(c1.getString(c1.getColumnIndex("ausgaben")));
contactListItems.setDatum(c1.getString(c1.getColumnIndex("datum")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
c1.close();
ContactListAdapter contactListAdapter = new ContactListAdapter(
BookActivity.this, contactList);
lvCustomList.setAdapter(contactListAdapter);}
}
I hope this code helps you.
Your sql query should looks like
query = "SELECT *, SUM(einnahmen) as sum FROM PHONE_CONTACS";
in your SqlDbHelper class:
public long sumEinnahmen() {
SQLiteStatement statement = getReadableDatabase().compileStatement(
"select sum(" + COLUMN3 + " from " + DATABASE_TABLE);
try {
return statement.simpleQueryForLong();
} finally {
statement.close();
}
}
Note that your column is currently declared as a text column instead of as integer or real column. If you are only storing numeric data in that column, you should declare it with either of those numeric types instead.
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))";
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;
}
}