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.
Related
Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Try removing space from your column name's
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
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 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.
I`m trying to make sure that the username value stored in my database is not repeating, and if it is repeated, a toast will inform the user that the username is already taken, how can I do so?
My DBAdapter:
package com.nyp.reddot5;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
// PartyItems table name
private static final String TABLE_NAME = "login";
// PartyItems Table Columns names
private static final String ID = "id";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String EMAIL = "email";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password, String email)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("EMAIL", email);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
My SignUPActivity
package com.nyp.reddot5;
import com.nyp.reddot5.R;
import com.nyp.reddot5.R.id;
import com.nyp.reddot5.R.layout;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editTextEmail;
Button btnCreateAccount, tcbutton, backb;
CheckBox TCcb;
Context mcursor;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
tcbutton=(Button)findViewById(R.id.tcbutton);
backb=(Button)findViewById(R.id.backb);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editTextEmail=(EditText)findViewById(R.id.editTextEmail);
TCcb=(CheckBox)findViewById(R.id.TCcb);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String email=editTextEmail.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
if(editTextUserName.getText().toString().length() < 7){
editTextUserName.setError(getString(R.string.error_field_required_user));
}
if(editTextPassword.getText().toString().length() < 5){
editTextPassword.setError(getString(R.string.error_field_required_pw));
}
if(TCcb.isChecked() == false){
Toast.makeText(getApplicationContext(), "You must agree to the terms and conditions!", Toast.LENGTH_LONG).show();
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password, email);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
tcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intent=new Intent(getApplicationContext(),TCActivity.class);
startActivity(intent);
}
});
backb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
You should use the UNIQUE constraint to the user name field in you DB. That way you make sure all values in the collumn are different (you can achieve the same thing making it PK but maybe your ussing another primary key). As for the toast, Im not sure which exception is thrown when the unique constraint is broken, but you should catch that exception, infomr the UI tier and throw the toast.
It throws a SQLiteConstraintException:
try{
db.insertOrThrow("LOGIN", null, newValues); // the normal insert may not throw an error
}catch(SQLiteConstraintException e){
Toast.makeText(context(), "User already on database", Toast.LENGTH_SHORT).show();
}
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