Failed to retrieve spesific data from SQLite Database (Android) - java

Hi guys i'm kinda new in Java and SQLite programming, and I have a problem to fetch and retrieve specific data from SQLite database,,
I want to create a login program, and user will input username and password (LoginScreen.java), it will check the existing data in database (database.java), and if exists, it will return true to LoginScreen.java.
After that, LoginScreen.java will check, if true, it will run the SQLViews Intent, if false, it will run the Registration Intent.
And the problem is, my code always return false, even though the data is exists on the database.
Can you please help me to check and give a correction for my code?
Thank you,
Here are the code :
Database.java
package com.thesis.teamizer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database {
public static final String DATABASE_NAME = "TeamizerDB.db";
public static final String TABLE_MEMBER = "Member";
public static final int DATABASE_VERSION = 1;
public static final String MEMBER_USERNAME = "Username";
public static final String MEMBER_PASSWORD = "Password";
public static final String MEMBER_EMAIL = "Email";
public DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_MEMBER + " (" + MEMBER_USERNAME
+ " TEXT PRIMARY KEY NOT NULL, " + MEMBER_PASSWORD
+ " TEXT NOT NULL, " + MEMBER_EMAIL + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
onCreate(db);
}
}
public Database(Context c) {
ourContext = c;
}
public Database open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public boolean createEntry(String username, String password, String email) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(MEMBER_USERNAME, username);
cv.put(MEMBER_PASSWORD, password);
cv.put(MEMBER_EMAIL, email);
ourDatabase.insert(TABLE_MEMBER, null, cv);
return true;
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { MEMBER_USERNAME, MEMBER_PASSWORD,
MEMBER_EMAIL };
Cursor c = ourDatabase.query(TABLE_MEMBER, columns, null, null, null,
null, null);
String result = "";
int iUsername = c.getColumnIndex(MEMBER_USERNAME);
int iPassword = c.getColumnIndex(MEMBER_PASSWORD);
int iEmail = c.getColumnIndex(MEMBER_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iUsername) + " "
+ c.getString(iPassword) + " " + c.getString(iEmail) + "\n";
}
return result;
}
public Boolean getName(String l) throws SQLException {
// TODO Auto-generated method stub
String Query = "SELECT USERNAME FROM " + TABLE_MEMBER + " WHERE "
+ MEMBER_USERNAME + " =?";
Cursor mCursor = ourDatabase.rawQuery(Query, new String[] { l });
boolean hasObject = false;
if (mCursor.moveToFirst()) {
hasObject = false;
mCursor.close();
}
else
hasObject = true;
return hasObject;
}
public Boolean getMatched(String username, String password) {
// TODO Auto-generated method stub
String Query = "SELECT USERNAME FROM " + TABLE_MEMBER + " WHERE "
+ MEMBER_USERNAME + " =? AND " + MEMBER_PASSWORD + " =?";
Cursor c = ourDatabase.rawQuery(Query, new String[] { username,
password });
if (c.moveToFirst()) {
return true;
} else {
return false;
}
}
}
LoginScreen.java
package com.thesis.teamizer;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginScreen extends Activity {
private EditText etUsername;
private EditText etPassword;
private Button bLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
validationUsernameAndPassword();
ifRegisterButtonClicked();
}
private void validationUsernameAndPassword() {
// TODO Auto-generated method stub
etUsername = (EditText) findViewById(R.id.etLoginUsername);
etPassword = (EditText) findViewById(R.id.etLoginPassword);
bLogin = (Button) findViewById(R.id.bLogin);
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int flag = 0;
/*
* if (!isValid(username)) {
* etUsername.setError("Username must be filled"); flag++; }
*
* if (!isValid(password)) {
* etPassword.setError("Password must be filled"); flag++; }
*/
if (flag == 0) {
Database checkLogin = new Database(LoginScreen.this);
checkLogin.open();
Boolean temp = checkLogin.getMatched(username, password);
// Kalo username n passwordnya benar2 ada di database
if (temp == true) {
Intent intent = new Intent(
"com.thesis.teamizer.SQLVIEWS");
startActivity(intent);
} // Kalo username n passwordnya salah atau gak ada di
// database
if (temp == false) {
Intent i = new Intent("com.thesis.teamizer.REGISSCREEN");
startActivity(i);
}
checkLogin.close();
}
}
private boolean isValid(String temp) {
if (temp != null && temp.length() > 6 && !temp.contains(" ")) {
return true;
}
return false;
}
});
}
private void ifRegisterButtonClicked() {
// TODO Auto-generated method stub
Button bRegis = (Button) findViewById(R.id.bRegister);
bRegis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.thesis.teamizer.REGISSCREEN");
startActivity(intent);
}
});
}
}

private void validationUsernameAndPassword() {
...
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
bLogin.setOnClickListener(new OnClickListener() {
...
You are reading the values when the activity is created.
You should do this after the button has been clicked.

Related

signup button linked to sqlite database

public void onSignUpClick(View v){
if(v.getId() == R.id.btnRegister)
{
EditText name = (EditText)findViewById(R.id.TFname);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = name.getText().toString();
String pass1str = name.getText().toString();
String pass2str = name.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg:
Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
tpass.show();
}
else
{
//insert the details in DB:
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setPass(pass1str);
helper.insertContact(c);
}
}
}
I'm trying to make a signup form linked to sqlite database. the registraion button that's linked to onSignUpClick method doesn't work. any help to fix this error?
I have implemented a similar functionality to my app.. You can use this as a reference.You need to add whatever elements needed for your signup activity.
1. Create a database handler for your sqlite application.(DatabaseHandler.java)
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context, Object name,
Object factory, int version) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
String password;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Mydatabase.db";
// Contacts table name
private static final String TABLE_REGISTER= "register";
public static final String KEY_EMAIL_ID="email_id";
public static final String KEY_MOB_NO = "mobile_number";
public static final String KEY_PASSWORD = "password";
public static final String CREATE_TABLE="CREATE TABLE " + TABLE_REGISTER + "("
+ KEY_EMAIL_ID+ " TEXT,"
+ KEY_MOB_NO + " TEXT," + KEY_PASSWORD + " TEXT " + ")";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
onCreate(db);
}
void addregister(UserRegister registerdata)
// code to add the new register
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_EMAIL_ID, registerdata.getEmailId());//register email id
values.put(KEY_MOB_NO, registerdata.getMobNo());//register mobile no
values.put(KEY_PASSWORD, registerdata.getPassword());
// Inserting Row
db.insert(TABLE_REGISTER, null, values);
db.close(); // Closing database connection
}
//code to get the register
String getregister(String username){
SQLiteDatabase db = this.getReadableDatabase();
//String selectquery="SELECT * FROM TABLE_REGISTER";
Cursor cursor=db.query(TABLE_REGISTER,null, "email_id=?",new String[]{username},null, null, null, null);
if(cursor.getCount()<1){
cursor.close();
return "Not Exist";
}
else if(cursor.getCount()>=1 && cursor.moveToFirst()){
password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));
cursor.close();
}
return password;
}
public String getDatabaseName() {
return DATABASE_NAME;
}
public static String getTableContacts() {
return TABLE_REGISTER;
}
public static int getDatabaseVersion() {
return DATABASE_VERSION;
}
}
2. Create a modal class UserRegister
public class UserRegister {
//private variables
String email_id;
String mobile_number;
String password;
// Empty constructor
public UserRegister(){}
// constructor
public UserRegister( String email_id,String mobile_number, String password){
this.email_id=email_id;
this.mobile_number=mobile_number;
this.password = password;
}
public String getEmailId() {
return email_id;
}
public void setEmailId(String email_id){
this.email_id = email_id;
}
public String getMobNo() {
// TODO Auto-generated method stub
return mobile_number;
}
public void setMobNo(String mobile_number){
this.mobile_number=mobile_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.Create the RegistrationActivity
public class Registration_Activity extends AppCompatActivity {
EditText reg_email,reg_phone,reg_password;
Button reg_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final DatabaseHandler db = new DatabaseHandler(this, null, null, 2);
reg_email = (EditText)findViewById(R.id.reg_email);
reg_phone = (EditText)findViewById(R.id.reg_phone);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_button = (Button)findViewById(R.id.reg_button);
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = reg_email.getText().toString();
String phone = reg_phone.getText().toString();
String password = reg_password.getText().toString();
if (email.matches(emailPattern)) {
DatabaseHandler db = new DatabaseHandler(Registration_Activity.this, null, null, 2);
UserRegister userRegister = new UserRegister();
userRegister.setEmailId(email);
userRegister.setMobNo(phone);
userRegister.setPassword(password);
db.addregister(userRegister);
Toast.makeText(getApplicationContext(), "Account Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration_Activity.this, Login_Activity.class);
startActivity(intent);
Registration_Activity.this.finish();
}
else
{
Toast.makeText(getApplicationContext(),"Enter a valid Email Address",Toast.LENGTH_SHORT).show();
}
}
});
}
}
4. Login_Activity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login_Activity extends AppCompatActivity {
TextView signup;
String email,password;
EditText log_username,log_password;
Button login_button;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signup = (TextView)findViewById(R.id.signup);
String htmlString="<u>Signup</u>";
signup.setText(Html.fromHtml(htmlString));
log_username = (EditText)findViewById(R.id.log_username);
log_password = (EditText)findViewById(R.id.log_password);
login_button = (Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db=new DatabaseHandler(Login_Activity.this, null, null, 2);
email = log_username.getText().toString();
password = log_password.getText().toString();
String StoredPassword =db.getregister(email);
if(password.equals(StoredPassword)){
Toast.makeText(getApplicationContext(),"Login Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login_Activity.this,VideoActivity.class);
startActivity(intent);
Login_Activity.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Username/Password incorrect", Toast.LENGTH_LONG).show();
log_username.setText("");
log_password.setText("");
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login_Activity.this,Registration_Activity.class);
startActivity(intent);
Login_Activity.this.finish();
}
});
}
}

when i tried to insert a row to database ,"table timeline has no column named source" occured"

I did have a column named source.I had no ideas where i was wrong.
I constructed table time at onCreate method.
public class DbHelper1 extends SQLiteOpenHelper {
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";//C_SOURCE represents source
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
StringBuffer buffer = new StringBuffer();
buffer.append("create table " + TABLE + " (");
buffer.append(C_ID + " int primary key ,");
buffer.append(C_CREATED_AT + " int ,");
buffer.append(C_USER + " text ,");
buffer.append(C_TEXT + " text ,");
buffer.append(C_SOURCE+" text ");//here is my column source
buffer.append(")");
String sql=buffer.toString();
db.execSQL(sql);
Log.d(TAG, "onCreate sql :"+sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists "+TABLE);
Log.d(TAG, "onUpgrade");
onCreate(db);
}
}
here is my test service:
public class UpdaterService3 extends Service {
private static final String TAG = "UpdaterService3";
static final int DELAY = 3000;
private boolean runFlag = false;
private Updater updater;
private YambaApplication1 yamba;
DbHelper1 dbHelper;
SQLiteDatabase db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
yamba = (YambaApplication1) getApplication();
this.updater = new Updater();
dbHelper = new DbHelper1(this);
Log.d(TAG, "onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
this.runFlag = true;
this.updater.start();
this.yamba.setServiceRunning(true);
Log.d(TAG, "onStarted");
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.runFlag = false;
this.updater.interrupt();
this.updater = null;
this.yamba.setServiceRunning(false);
Log.d(TAG, "onDestroy");
}
private class Updater extends Thread {
public Updater() {
super("UpdaterService-Updater");
}
#Override
public void run() {
// TODO Auto-generated method stub
UpdaterService3 updaterService = UpdaterService3.this;
while (updaterService.runFlag) {
Status status;
Log.d(TAG, "Updater running");
try {
db=dbHelper.getWritableDatabase();
Log.d(TAG, "Updater ran");
status = new Status();
status.createdAt = String.valueOf(System
.currentTimeMillis());
status.id = UUID.randomUUID().toString();
status.source = "hello i'm " + status.id
+ ",nice to see you";
status.text = "wow baby :" + status.id;
status.user = "user:" + status.id;
ContentValues values = new ContentValues();
values.clear();
values.put(DbHelper1.C_ID, status.id);
values.put(DbHelper1.C_CREATED_AT, status.createdAt);
values.put(DbHelper1.C_SOURCE, status.source);
values.put(DbHelper1.C_TEXT, status.text);
values.put(DbHelper1.C_USER, status.user);
db.insertOrThrow(DbHelper1.TABLE, null, values);
Log.d(TAG, String.format("%s:%s", status.user,status.text));
db.close();
Log.d(TAG, "Updater run");
Thread.sleep(DELAY);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
updaterService.runFlag = false;
}
}
}
}
}
here is class status
public class Status {//entity bean
String id;
String createdAt;
String source;
String text;
String user;
}
I was really confused.I was a new coder for android.please help!~
1 DB_VERSION must be named DATABASE_VERSION. It's not an optional constant. If you modify the database structure in time, Android relies on this constant to perform the upgrades.
2 If you changed the database structure (i.e.: added or renamed a column), you must increase the DATABASE_VERSION constant value, in order for the onUpgrade() method to fire.

Not able to retrieve data from SQLite database

I created an sqlite database and was trying to view data entered into my database on a button click. the button click would open a new activity and display the data in a textview but nothing seems to happen. Please tell me what is wrong with my code. Thanks.
View.java
package com.firstproject.aditya;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class View extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
TextView tv= (TextView)findViewById(R.id.tvSQLinfo);
Database info= new Database(this);
info.open();
String data=info.getData();
info.close();
tv.setText(data);
}
}
Activity2.java
package com.firstproject.aditya;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Activity2 extends Activity implements View.OnClickListener {
Button startDate, targetDate, remDate, save, cancel;
TextView goalInfo, title, des, stDate, tgDate,rdDate;
EditText edTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.act2);
initialize();
startDate.setOnClickListener(this);
cancel.setOnClickListener(this);
targetDate.setOnClickListener(this);
save.setOnClickListener(this);
remDate.setOnClickListener(this);
/*
* Bundle gotBasket = getIntent().getExtras(); String
* gotBread1=gotBasket.getString("key"); edsd.setText(gotBread1);
*/
}
private void initialize() {
// TODO Auto-generated method stub
startDate = (Button) findViewById(R.id.bStart);
targetDate = (Button) findViewById(R.id.bTarg);
remDate = (Button) findViewById(R.id.brem);
save = (Button) findViewById(R.id.bsave);
cancel = (Button) findViewById(R.id.bcancel);
goalInfo = (TextView) findViewById(R.id.tvGI);
title = (TextView) findViewById(R.id.tvTitle);
stDate = (TextView) findViewById(R.id.textViewStartDate);
tgDate = (TextView) findViewById(R.id.textViewTargetDate);
rdDate = (TextView) findViewById(R.id.textViewReminderDate);
edTitle = (EditText) findViewById(R.id.editText1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case (0):{
if (resultCode == RESULT_OK) {
Bundle bsket = data.getExtras();
String s = bsket.getString("answer");
stDate.setText(s);
}
break;
}
case (2):{
if (resultCode == RESULT_OK) {
Bundle bsket = data.getExtras();
String s = bsket.getString("answer");
tgDate.setText(s);
}
break;
}
case (1):{
if (resultCode == RESULT_OK) {
Bundle bsket = data.getExtras();
String s = bsket.getString("answer");
rdDate.setText(s);
}
break;
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == cancel) {
Intent canc = new Intent("com.firstproject.aditya.ACTIVITY1");
startActivity(canc);
}
if (v == startDate) {
Intent sdate = new Intent(Activity2.this,DatePick.class);
startActivityForResult(sdate,0);
}
if (v == targetDate) {
Intent tdate = new Intent(Activity2.this,DatePick.class);
startActivityForResult(tdate,2);
}
if (v == remDate) {
Intent rdate = new Intent(Activity2.this,DatePick.class);
startActivityForResult(rdate,1);
}
switch(v.getId()){
case R.id.bsave:
boolean didItWork=true;
try{
String gTitle=edTitle.getText().toString();
String dateS=stDate.getText().toString();
String dateT=tgDate.getText().toString();
String dateR=rdDate.getText().toString();
Database entry =new Database(Activity2.this);
entry.open();
entry.createEntry(gTitle,dateS,dateT,dateR);
entry.close();
}catch(Exception e){
didItWork=false;
String error=e.toString();
Dialog d =new Dialog(this);
d.setTitle("Dang it!");
TextView txtV=new TextView(this);
txtV.setText(error);
d.setContentView(txtV);
d.show();
}finally{
if(didItWork){
Dialog d =new Dialog(this);
d.setTitle("Heck Yeah!");
TextView txtV=new TextView(this);
txtV.setText("Success");
d.setContentView(txtV);
d.show();
}
}
break;
case R.id.bview:
Intent i=new Intent("com.firstproject.aditya.VIEW");
startActivity(i);
break;
}
}
}
Database.java
package com.firstproject.aditya;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "goals_title";
public static final String KEY_STDATE = "start_date";
public static final String KEY_TGDATE = "target_date";
public static final String KEY_RDDATE = "reminder_date";
private static final String DATABASE_NAME = "GoalInformation";
private static final String DATABASE_TABLE = "GoalTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private android.database.sqlite.SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(android.database.sqlite.SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TITLE
+ " TEXT NOT NULL, " + KEY_STDATE + " TEXT NOT NULL, "
+ KEY_TGDATE + " TEXT NOT NULL, " + KEY_RDDATE
+ " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(android.database.sqlite.SQLiteDatabase db,
int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Database(Context c) {
ourContext = c;
}
public Database open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String gTitle, String dateS, String dateT,
String dateR) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TITLE, gTitle);
cv.put(KEY_STDATE, dateS);
cv.put(KEY_TGDATE, dateT);
cv.put(KEY_RDDATE, dateR);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_TITLE, KEY_STDATE,
KEY_TGDATE, KEY_RDDATE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTitle = c.getColumnIndex(KEY_TITLE);
int iStdate = c.getColumnIndex(KEY_STDATE);
int iTgdate = c.getColumnIndex(KEY_TGDATE);
int iRddate = c.getColumnIndex(KEY_RDDATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iTitle)
+ " " + c.getString(iStdate) + " " + c.getString(iTgdate)
+ " " + c.getString(iRddate) + "\n";
}
return result;
}
}
I don't know whether this answer is helpful or not.
When I started to use a SQLite connection I tried using the "query" method like you but had several problems (seems like some probs are similar to this one).
I started using the rawQuery method and everything is working now.
Possible I'm just failing but this was the solution for my problems.

Updating specific column using a spinner widget

I am trying to update current credits column of the only row in the database using a drop down spinner which gets values from an arraylist. Very unsure about how to go about doing this operation. Thank you for any help in advance.
My database code:
package com.example.parkangel;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " TEXT NOT NULL, " + KEY_CREDITS + " TEXT
NOT NULL);");
}
#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);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
}
My main activity code I will be doing the operation through:
package com.example.parkangel;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class Balance extends Activity{
Button add;
TextView display;
Spinner spinner3;
String[] money = {"Select amount", "£1", "£2", "£5", "£10"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
db.close();
tv.setText(data);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
Your question is fairly compound, getting selected field from spinner, updating database... I'm not going to provide a complete answer, but this should get you started:
This is how you would get the selected field from the spinner, which you can then use to update your database. One word of warning, I believe setOnItemSelectedListener is called when it is initially set, so you may need to ignore the first call.
Spinner spinner;
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2,
long arg3) {
if(! (view instanceof TextView)){
// view is probably a textview, but record type if not.
System.out.println("incorrect view type " + view.getClass().getSimpleName());
return;
}
EditText et = (EditText) view;
String fieldName = et.getText().toString().trim();
//Now we got selected name, send name
//to a function that updates our database.
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I didn't find the problem but I can tell you that your code is VERY INEFFICIENT. You are using String to build your result in the getData method. Each time you try to append the new data (Row) to the old one you are creating a new string to hold the new data. If you are retrieving 1000 row from the database, this means that you are creating 1000 string to build the final one. I recommend using StringBuilder instead as following:
StringBuilder strBuilder= new StringBuilder();
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
strBuilder.append( c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname)
+ " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n");
}
return str= strBuilder.toString();
Here is an example of how to insert into your DB:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PFNAME , editText1.getText().toString());
values.put(KEY_PSNAME , stringArrayList.get(position));
values.put(KEY_CARD , "12345677");
values.put(KEY_CREDITS , "55");
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
db.close(); // Closing database connection

Content of the result of aggregation query not returned

I am a begineer and I want to allow just one user to sign up as per the demand of my project.
The SIGNUP.java is meant to accomplish it using DbHelper.java but things work fine for
c.getCount()
but not for
Integer.parseInt(c.getString(0))
SIGNUP.java reads:
package com.bishal.android.taskmanager;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SIGNUP extends Activity {
Button register;
private EditText etName;
private EditText etEmail;
//private EditText etUsername;
private EditText etPassword;
private DbHelper dbhelper;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbhelper=new DbHelper(this);
etName=(EditText)findViewById(R.id.edit_name);
etEmail=(EditText)findViewById(R.id.edit_email);
etPassword=(EditText)findViewById(R.id.edit_signup_password);
register=(Button)findViewById(R.id.signup);
final boolean bregister=(dbhelper.NoOfUser()==0)?true:false;
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//String UserNameValue=etUsername.getText().toString();
String NameValue=etName.getText().toString();
String EmailValue=etEmail.getText().toString();
String PasswordValue=etPassword.getText().toString();
//Toast.makeText(SIGNUP.this,dbhelper.ThereIsUser(), Toast.LENGTH_LONG).show();
if (bregister){
ACCOUNT_INFO account=new ACCOUNT_INFO(NameValue,EmailValue,PasswordValue);
if(NameValue.trim().length()>0 && EmailValue.trim().length() > 0 && PasswordValue.trim().length() >0){
if(dbhelper.eMailValidation(EmailValue)){
if(dbhelper.validateregister(EmailValue)){
dbhelper.addAccount(account);
Toast.makeText(SIGNUP.this, "Your account has been sucessfully created.", Toast.LENGTH_LONG).show();
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Username/Email already exists.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this,"Signup failed..", "Email address is not in such form.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Please enter empty fields.", false);
}
}
}
});
}
}
DbHelper.java reads(why 'count' is not returned as count of number of rows in table?):
package com.bishal.android.taskmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DbHelper extends SQLiteOpenHelper{
private static final String TAG=DbHelper.class.getSimpleName();
public static final String DB_NAME="Store Account.db";
public static final int DB_VERSION=1;
public static final String TABLE="Account_Info";
public static final String COL_ID="Id"; //special for ID
public static final String COL_NAME="Name";
public static final String COL_EMAIL="Email";
//public static final String COL_UNAME="Username";
public static final String COL_PASSWORD="Password";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_ACCOUNT_INFORMATION = "CREATE TABLE " + TABLE + "("
+ COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " String,"
+ COL_EMAIL + " String," + COL_PASSWORD + " String" + ")";
Log.d(TAG, "onCreate sql: "+CREATE_ACCOUNT_INFORMATION);
db.execSQL(CREATE_ACCOUNT_INFORMATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exists " + TABLE);
Log.d(TAG,"onUpdate dropped table "+ TABLE);
onCreate(db);
}
void addAccount(ACCOUNT_INFO account){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COL_NAME,account.getNAME());
values.put(COL_EMAIL,account.getEMAIL());
//values.put(COL_UNAME, account.getUSERNAME());
values.put(COL_PASSWORD, account.getPASSWORD());
db.insert(TABLE, null, values);
db.close();
}
public boolean validateuser(String email,String password){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email +"'AND "+COL_PASSWORD+"='" + password+"'" , null);
if(c.getCount()>0)
return true;
else
return false;
}
public boolean validateregister(String email){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email+"'" , null);
if(c.getCount()>0)
return false;
else
return true;
}
public boolean eMailValidation(String emailValue) {
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern=Pattern.compile(EMAIL_PATTERN);;
Matcher matcher;
matcher = pattern.matcher(emailValue);
return matcher.matches();
}
public int NoOfUser() {
Cursor c=getReadableDatabase().rawQuery("SELECT count(*) FROM " + TABLE, null);
int count=Integer.parseInt(c.getString(0));
return count;
}
}

Categories