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.
Related
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();
}
});
}
}
I am having two classes SqlLiteExample.javaand HotOrNot.java.First one is for creating interface and second one is for Database creation.
SqlLiteExample.java
package com.thenewboston;
import android.app.Activity;
import android.app.Dialog;
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 SqlLiteExample extends Activity implements OnClickListener{
EditText etName,etHotness;
Button btnSave,btnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqliteexample);
etName=(EditText) findViewById(R.id.editText1);
etName=(EditText) findViewById(R.id.editText2);
btnSave=(Button) findViewById(R.id.btnSQLUPDATE);
btnView=(Button) findViewById(R.id.btnSQLVIEW);
btnSave.setOnClickListener(this);
btnView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btnSQLUPDATE:
boolean didItWork=true;
try{
String name=etName.getText().toString();
String hotness=etHotness.getText().toString();
HotOrNot entry= new HotOrNot(SqlLiteExample.this);
entry.open();
entry.createEntry(name,hotness);
entry.close();
}catch(Exception e){
didItWork= false;
}finally{
if(didItWork){
Dialog d= new Dialog(this);
d.setTitle("Heck yea");
System.out.println("testing");
TextView tv= new TextView(this);
tv.setText("sucess");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.btnSQLVIEW:
break;
}
}
}
HotOrNot.java
package com.thenewboston;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class HotOrNot {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_HOTNESS = "persons_hotness";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourhelper;
private final Context ourContext;
private 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(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_HOTNESS + "TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST "+ DATABASE_TABLE);
onCreate(db);
}
}
public HotOrNot(Context c) {
ourContext = c;
}
public HotOrNot open() throws SQLException{
ourhelper = new DbHelper(ourContext);
ourDatabase= ourhelper.getWritableDatabase();
return this;
}
public void close(){
ourhelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv= new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
}
Problem in that whenever I press btnSave is should display a dilog which is defined in finally block of case R.id.btnSQLUPDATE:but it is not.I have tried to debug the code,after executing HotOrNot entry= new HotOrNot(SqlLiteExample.this); in the same case it is moving into catch block and catches exception.I am uable find where I am doing wrong.
I think you got NPL(null pointer exeption) in this line:
String hotness=etHotness.getText().toString();
you did not findViewById "etHotness" , look at your code:
in onCreate() you write this:
etName=(EditText) findViewById(R.id.editText1);
etName=(EditText) findViewById(R.id.editText2);
shoud change to:
etName=(EditText) findViewById(R.id.editText1);
etHotness=(EditText) findViewById(R.id.editText2);
I personnally use AlertDialog with AlertDialog.Builder for this kind of situation. Works pretty well...
new AlertDialog.Builder(this)
.setTitle("Your title")
.setMessage("Your message")
.setPositiveButton("OK", mOnClickListener)
.create()
.show();
You can also set a list of clickable item as view, or a list of checkboxes or radiobuttons with methods setAdapter, setSingleChoiceItems and setMultiChoiceItems. I find it simplier to use.
I use AlertDialog, it's better solution. Use this code:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View viewDialog = inflater.inflate(R.layout.alertdialog_gameover, null);
TextView title = (TextView)viewDialog.findViewById(R.id.title);
title.setText("Successfully");
builder.setView(viewDialog)
.setPositiveButton("Play again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Set something for positive
}
})
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//set something for negative
}
});
//create dialog
builder.create();
//show dialog
builder.show();
Edit:
try to change:
}catch(Exception e){
didItWork= false;
}
to:
}catch(Exception e){
didItWork= true;
}
your code for Dialog work for me.
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.
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
I was researching on how to add tables in an sqlite database for more information but I can't have a grip on how it was truly done.
I have this code:
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "SCORING";
public static final String MYDATABASE_TABLE = "SCORING_TABLE";
public static final String MYDATABASE_TABLE1 = "Assessment";
public static final int MYDATABASE_VERSION = 3;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
//create table SCORING (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_CONTENT1 + " text not null, "
+ KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + "text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String content1, String content2, String content3){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT1, content1);
contentValues.put(KEY_CONTENT2, content2);
contentValues.put(KEY_CONTENT3, content3);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2, KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#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
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE SCORING_TABLE ADD COLUMN Content4 TEXT");
}
}
}
}
and for the second one I'm having a hard time inputting data to the second table
package com.example.database;
import com.example.database.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidSQLite extends Activity {
EditText inputContent2;
TextView textView1, textView2;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
inputContent2 = (EditText)findViewById(R.id.content2);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2, R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int a=Integer.parseInt(textView1.getText().toString());
int b=a+2;
String s1 = String.valueOf(b);
textView1.setText(s1);
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
String data1 = textView1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = textView2.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
}
I personally found using ContentProviders to be a clearer and easier to maintain way to manage multiple tables.
There is a nice article here that explains ContentProviders and other ways of dealing with android database/
http://www.vogella.com/articles/AndroidSQLite/article.html#tutorialusecp