When the user presses Register button, the details he input will be saved into the database but it doesnt show anything.
Is there something wrong with my code? Why can't i see the data i inserted into the database? It doesnt crashes or something.
DBAdapter
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;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_FNAME = "fname";
public static final String KEY_LNAME = "lname";
public static final String KEY_MNAME = "mname";
public static final String KEY_CONTACTNUM = "contactNum";
public static final String KEY_LICENSE = "license";
public static final String KEY_USER = "username";
public static final String KEY_PASS = "password";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "sampleForFinals";
private static final String DATABASE_TABLE = "drivers";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table drivers (_id integer primary key autoincrement, "
+ "fname text not null, lname text not null, "
+ "mname text not null, contactNum text not null," +
"license text not null, username text not null, password text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS drivers");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a driver's information into the database---
public long insertDriver(String fname, String lname, String mname, String contactNum, String license, String user, String pass)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_FNAME, fname);
initialValues.put(KEY_LNAME, lname);
initialValues.put(KEY_MNAME, mname);
initialValues.put(KEY_CONTACTNUM, contactNum);
initialValues.put(KEY_LICENSE, license);
initialValues.put(KEY_USER, user);
initialValues.put(KEY_PASS, pass);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
Register
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.ftlibrary.Fit;
public class Register extends Activity {
EditText firstname,lastname, middlename, contactNum, license, username, password;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Fit.FitSetClientKey("SZIERAINE1527");
Fit.FitSetAppName("sampleForFinals");
firstname = (EditText) findViewById(R.id.et_firstname);
lastname = (EditText) findViewById(R.id.et_lastname);
middlename = (EditText) findViewById(R.id.et_middlename);
contactNum = (EditText) findViewById(R.id.et_contactNumber);
license = (EditText) findViewById(R.id.et_license);
username = (EditText) findViewById(R.id.et_username);
password = (EditText) findViewById(R.id.et_password);
register = (Button) findViewById(R.id.btn_register);
register.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
DBAdapter db = new DBAdapter(Register.this);
String fname = firstname.getText().toString();
String lname = lastname.getText().toString();
String mname = middlename.getText().toString();
String contact = contactNum.getText().toString();
String plate = license.getText().toString();
String user = username.getText().toString();
String pass = password.getText().toString();
db.open();
long id = db.insertDriver(fname, lname, mname, contact, plate, user, pass);
db.close();
}
});
}
}
Why can't i see any record in the database? TT TT
Related
I'm building an application for a barber shop and im on a part now where I am creating an appointment and saving the data from that appointment, however when I go to click add to create the appointment, the application crashes and I left with this error;
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 2 rows, 3 columns.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ie.app.barbershop, PID: 31270
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at ie.app.barbershop.TableControllerAppointments.read(TableControllerAppointments.java:46)
at ie.app.barbershop.Landing.readRecords(Landing.java:47)
at ie.app.barbershop.OnClickListenerCreateAppointment$1.onClick(OnClickListenerCreateAppointment.java:38)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I/Process: Sending signal. PID: 31270 SIG: 9
Application terminated.
Here is my class for TableControllerAppointments.java
package ie.app.barbershop;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class TableControllerAppointments extends DatabaseHandler {
public TableControllerAppointments(Context context) {
super(context);
}
public boolean create(ObjectAppointment objectAppointments) {
ContentValues values = new ContentValues();
values.put("fullname", objectAppointments.fullName);
values.put("contactno", objectAppointments.contactNumber);
SQLiteDatabase db = this.getWritableDatabase();
boolean createSuccessful = db.insert("appointments", null, values) > 0;
db.close();
return createSuccessful;
}
public List<ObjectAppointment> read() {
List<ObjectAppointment> recordsList = new ArrayList<>();
String sql = "SELECT * FROM Appointments ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
int contactNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex("contactno")));
ObjectAppointment objectAppointment = new ObjectAppointment();
objectAppointment.fullName = fullName;
objectAppointment.contactNumber = contactNumber;
recordsList.add(objectAppointment);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return recordsList;
}
public int count() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "SELECT * FROM appointments";
int recordCount = db.rawQuery(sql, null).getCount();
db.close();
return recordCount;
}
}
And here is my class for OnClickListenerCreateAppointment.java
package ie.app.barbershop;
import android.view.View;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class OnClickListenerCreateAppointment implements View.OnClickListener {
public ObjectAppointment objectAppointment;
#Override
public void onClick(View view){
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.appointment_input_form, null, false);
final EditText editTextFullName = formElementsView.findViewById(R.id.editTextFullName);
final EditText editTextContactNumber = formElementsView.findViewById(R.id.editTextContactNumber);
ObjectAppointment objectAppointment = new ObjectAppointment();
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Appointment")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String fullname = editTextFullName.getText().toString();
String contactno = editTextContactNumber.getText().toString();
((Landing) context).countRecords();
((Landing) context).readRecords();
dialog.cancel();
}
}).show();
boolean createSuccessful = new TableControllerAppointments(context).create(objectAppointment);
if(createSuccessful){
Toast.makeText(context, "Appointment Information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save appointment information", Toast.LENGTH_SHORT).show();
}
}
}
and this is my Landing.java class
package ie.app.barbershop;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.List;
public class Landing extends AppCompatActivity{
public Button buttonProducts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_landing);
countRecords();
buttonProducts = findViewById(R.id.buttonProducts);
Button buttonCreateAppointment = findViewById(R.id.buttonCreateAppointment);
buttonCreateAppointment.setOnClickListener(new OnClickListenerCreateAppointment());
buttonProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Landing.this, Products.class));
}
});
}
public void readRecords() {
LinearLayout linearLayoutRecords = findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<ObjectAppointment> appointments = new TableControllerAppointments(this).read();
if (appointments.size() > 0) {
for (ObjectAppointment obj : appointments) {
String fullName = obj.fullName;
int contactNumber = obj.contactNumber;
String textViewContents = fullName + " - " + contactNumber;
TextView textViewAppointmentItem= new TextView(this);
textViewAppointmentItem.setPadding(0, 10, 0, 10);
textViewAppointmentItem.setText(textViewContents);
textViewAppointmentItem.setTag(Integer.toString(contactNumber));
linearLayoutRecords.addView(textViewAppointmentItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
public void countRecords(){
int recordCount = new TableControllerAppointments(this).count();
TextView textViewRecordCount = findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
}
Database Handler Class
package ie.app.barbershop;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS students";
db.execSQL(sql);
onCreate(db);
}
}
The -1 is being returned from getColumnIndex meaning that the column firstname
doesn't exist in the cursor in the following line.
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
You create the table using :-
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
Where the columns are id fullname and contactno.
--
Fix
To fix this change to use :-
String fullName = cursor.getString(cursor.getColumnIndex("fullname"));
Additional
Better still define column and tables names as constants and always refer to them.
e.g.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public static final String TABLE_NAME = "appointments";
public static final String COL_ID = "id";
public static final String COl_FULLNAME = "fullname";
public static final String COL_CONTACTNO = "contactno";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME +
"( " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_FULLNAME + " TEXT, " +
COL_CONTACTNO + " NUMBER ) ";
db.execSQL(sql);
}
.... and so on
and later as one example :-
String fullName = cursor.getString(cursor.getColumnIndex(DatabaseHandler.COL_FULLNAME));
Here is my code
Databasehandler.java
package com.example.mybucky.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.prefs.Preferences;
/**
* Created by Satyajeet Sen on 20/12/2016.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Register.db" ;
private static final int DATABASE_VERSION = 1 ;
private static final String TABLE_REGISTER = "REGISTER";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
private static final String COL_USERNAME = "username";
private static final String COL_PASSWORD = "password";
private static final String COL_AGE = "age";
SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_REGISTER_TABLE = "CREATE TABLE " + TABLE_REGISTER + "("
+ COL_ID + " INTEGER PRIMARY KEY ," + COL_NAME + " TEXT ,"
+ COL_USERNAME + " TEXT ," + COL_PASSWORD + " TEXT ," + COL_AGE + " INTEGER "+")";
db.execSQL(CREATE_REGISTER_TABLE);
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
this.onCreate(db);
}
public void insertDetails(LoginRegisterBean l){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query ="SELECT * FROM "+TABLE_REGISTER;
Cursor cursor =db.rawQuery(query,null);
int count=cursor.getCount();
values.put(COL_ID,count);
// Contact Name
values.put(COL_NAME, l.getName());
values.put(COL_USERNAME, l.getUsername());
values.put(COL_PASSWORD, l.getPassword());
values.put(COL_AGE, l.getAge());
db.insert(TABLE_REGISTER,null,values);
db.close();
}
public String searchPass(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
b="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public String searchUser(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
a="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return a;
}
LoginRegisterBean getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_REGISTER, new String[] { COL_ID,
COL_USERNAME,COL_AGE }, COL_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
LoginRegisterBean retrievecontact = new LoginRegisterBean(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)));
// return contact
return retrievecontact;
}
}
UserAreaActivity.java 2edit texts one for age and other for username. Aim:-to display values of age nd username from database to edittext
package com.example.mybucky.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
import com.example.mybucky.myapplication.R;
import java.util.ArrayList;
import java.util.List;
public class UserAreaActivity extends AppCompatActivity {
DatabaseHandler helper = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final EditText etUsername = (EditText) findViewById(R.id.username);
final EditText etAge = (EditText) findViewById(R.id.age);
final TextView tvwelcome = (TextView) findViewById(R.id.tvwelcome);
public void retrievefromdb(LoginRegisterBean l){
List<LoginRegisterBean> lst =new ArrayList<LoginRegisterBean>();
for(int i=0;i<3;i++){
lst.add( helper.getContact(i));
}
}
}
}
I have a method returning a single contact in Databasehandler class but i dont need password to be displayed. Display fields only age and username in activity UserAreaActivity.
Welcome user!Your age is
age
---edit field------
username
---edit field-----
I have made a register activity for a student attendance app, where the faculty is registered only if the "faculty checkbox" is checked. The faculty info should be added to a faculty table. If the checkbox is not checked then by default, the info will be entered to student table. So 1 database and 2 tables.
This is the register activity:
This is the Database helper code where i wanna add data to faculty table only if the faculty checkbox is checked in the insertData method.. but I don't know how to do this. Am a newbie at android studio.
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="Register.db";
public static final String TABLE_STUDENT ="Register_student";
public static final String TABLE_FACULTY ="Register_faculty";
public static final String COL_1 ="Name";
public static final String COL_2 ="Username";
public static final String COL_3 ="Password";
private static final String CREATE_TABLE_STUDENT = "CREATE TABLE "
+ TABLE_STUDENT + "(" + COL_1
+ " TEXT," + COL_2 + "TEXT," + COL_3
+ " TEXT" + ")";
private static final String CREATE_TABLE_FACULTY = "CREATE TABLE "
+ TABLE_FACULTY + "(" + COL_1
+ " TEXT," + COL_2 + "TEXT," + COL_3
+ " TEXT" + ")";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT );
db.execSQL(CREATE_TABLE_FACULTY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FACULTY);
onCreate(db);
}
public void insertData(String name, String username, String password)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,username);
contentValues.put(COL_3, password);
db.insert(TABLE_STUDENT,null,contentValues);
}
}
My register.java page
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class register extends AppCompatActivity {
Button register;
CheckBox faculty;
EditText editName, editUName, editPass;
DatabaseHelper myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
myDB = new DatabaseHelper(this);
editName = (EditText) findViewById(R.id.editText3);
editUName = (EditText) findViewById(R.id.editText7);
editPass = (EditText) findViewById(R.id.editText5);
faculty = (CheckBox) findViewById(R.id.checkBox38);
register = (Button) findViewById(R.id.button2);
register();
}
public void register() {
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted=
myDB.insertData(editName.getText().toString(),
editUName.getText().toString(),
editPass.getText().toString(), faculty.isChecked());
if(isInserted==true)
{
Toast.makeText(getApplicationContext(), "Data added",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Data not added",
Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(register.this, login.class);
startActivity(i);
Toast.makeText(getApplicationContext(), "You have been
registered", Toast.LENGTH_SHORT).show();
}
});
}
}
Set an integer flag to 0 if checkbox is not checked and 1 if checkbox is checked.
Send this flag to insertData() function as shown below:
public void insertData(String name, String username, String password, int flag)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,username);
contentValues.put(COL_3, password);
if(flag==0)
{
db.insert(TABLE_STUDENT,null,contentValues);
}
else if(flag==1)
{
db.insert(TABLE_FACULTY,null,contentValues);
}
}
Take Boolean variable if checkbox is checked set true else false for unchecked. Send variable to insertData() function like this.
public void insertData(String name, String username, String password, boolean checked) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,username);
contentValues.put(COL_3, password);
if(!checked)
db.insert(TABLE_FACULTY,null,contentValues);
else
db.insert(TABLE_STUDENT,null,contentValues);
}
// on register page
buttonRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (checkbox.isChecked()) {
//checkbox checked
} else {
//checkbox unchecked
}
}
});
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
I am a beginner to android.
I can't insert into database successfully with my database helper?
Here is my helper class code with the methods for inserting and finding a user
package com.example.tilmac.dbsql;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by TILMAC on 28-11-15.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "User.db";
private static final String TABLE_NAME = "users"; //final variables
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
public DatabaseHelper(Context context) //Constructor
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Create table statement is hardcoded,like this:
private static final String TABLE_CREATE = "create table users (name text not null, email text not null, uname text not null, pass text not null)";
I get an error which says column not found while inserting into database
public void insertUser(Contact c){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_UNAME, c.getUname());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String findPass(String s){
db = this.getReadableDatabase();
String query = "select uname, pass from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b="not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(s))
{
b=cursor.getString(1);
break;
}
}while(cursor.moveToNext());
}
return b;
}
#Override
public void onCreate(SQLiteDatabase db) { //OnCreate method
db.execSQL(TABLE_CREATE);
this.db = db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //onUpgrade Method
String query = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
//and here is my main activity
package com.example.tilmac.dbsql;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by TILMAC on 27-11-15.
*/
public class RegisterActivity extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
///Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
}
public void onRBClick(View v){
if(v.getId()==R.id.Rbutton)
{
EditText n = (EditText)findViewById(R.id.RETname);
EditText e = (EditText)findViewById(R.id.RETemail);
EditText u = (EditText)findViewById(R.id.RETuname);
EditText p1 = (EditText)findViewById(R.id.RETpass);
EditText p2 = (EditText)findViewById(R.id.RETrepass);
String name, email, uname, pass, repass;
name = n.getText().toString();
email = e.getText().toString();
uname = u.getText().toString();
pass = p1.getText().toString();
repass = p2.getText().toString();
if(pass.equals(repass))
{
Contact c = new Contact();
c.setName(name);
c.setEmail(email);
c.setUname(uname);
c.setPass(pass);
helper.insertUser(c);
}
else
{
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Passwords dont match", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
You added that column after a previous run.
Simply uninstall and reinstall your app.
I am making an application and I have made a class setup email.java in which I am saving the values entered by the user in sqlite database.But the class is not able to load and it is saying that:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.astrada/com.example.astrada.Setupemail}:
java.lang.InstantiationException: can't instantiate class com.example.astrada.Setupemail; no empty constructor
Here is my code:
package com.example.astrada;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.example.astrada.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Setupemail extends Activity implements OnClickListener {
EditText editEmail, editPhon1, editPhon2, editphone3, editphone4, uname,
useraddress;
TextView TitleInfo;
Button save;
SqlOpenHelper mHelper;
Cursor mCursor;
SimpleCursorAdapter mAdapter;
private final Context context;
private SqlOpenHelper DBHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "databaseofuser.db";
private static final String DATABASE_TABLE = "usertable";
private static final int DATABASE_VERSION = 1;
public static final String EMAIL_COLUMN = "email";
public static final String PHONE1_COLUMN = "phon1";
public static final String PHONE2_COLUMN = "phon2";
public static final String PHONE3_COLUMN = "phon3";
public static final String PHONE4_COLUMN = "phon4";
public static final String UNAME_COLUMN = "phon4";
public static final String UADDR_COLUMN = "phon4";
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + EMAIL_COLUMN + "," + PHONE1_COLUMN + ","
+ PHONE2_COLUMN + "," + PHONE3_COLUMN + "," + PHONE4_COLUMN + ","
+ UNAME_COLUMN + "," + UADDR_COLUMN + ");";
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setupemail);
editEmail = (EditText) this.findViewById(R.id.editEmail);
editPhon1 = (EditText) this.findViewById(R.id.editPhon1);
editPhon2 = (EditText) this.findViewById(R.id.editPhon2);
editphone3 = (EditText) this.findViewById(R.id.editPhon3);
editphone4 = (EditText) this.findViewById(R.id.editPhon3);
uname = (EditText) this.findViewById(R.id.nameofuser);
useraddress = (EditText) this.findViewById(R.id.addressofuser);
editPhon1.append("+91");
editPhon2.append("+91");
editphone3.append("+91");
editphone4.append("+91");
mHelper = new SqlOpenHelper(this);
save = (Button) this.findViewById(R.id.btnSaveData);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String email, phon1, phon2, phon3, phon4;
boolean isEntryValid, isPhon1Valid, isPhone2Valid;
if (v == save) {
email = editEmail.getText().toString();
phon1 = editPhon1.getText().toString();
phon2 = editPhon2.getText().toString();
phon3 = editphone3.getText().toString();
phon4 = editphone4.getText().toString();
if (isEmailIdValid(email) && isPhoneValid(phon1)
&& isPhoneValid(phon2)) {
if (phon1.equals(phon2) || phon1.equals(phon3)
|| phon1.equals(phon4) || phon2.equals(phon3)
|| phon2.equals(phon4) || phon3.equals(phon4)) {
Toast.makeText(getApplicationContext(),
" Can't enter same numbers!!", Toast.LENGTH_LONG)
.show();
} else {
// /Saveinto DB
ContentValues cv = new ContentValues();
cv.put(EMAIL_COLUMN, editEmail.getText().toString());
cv.put(PHONE1_COLUMN, editPhon1.getText().toString());
cv.put(PHONE2_COLUMN, editPhon2.getText().toString());
cv.put(PHONE3_COLUMN, editphone3.getText().toString());
cv.put(UNAME_COLUMN, uname.getText().toString());
cv.put(UADDR_COLUMN, useraddress.getText().toString());
mDb.insert(DATABASE_TABLE, null, cv);
mCursor.requery();
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Good Job!!",
Toast.LENGTH_LONG).show();
}
} else {
String x = "Invalid Entry!!\nProvide Information Properly..";
Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG)
.show();
editEmail.setText("");
}
}
// TODO Auto-generated method stub
}
private boolean isPhoneValid(String phon) {
final Pattern pattern = Pattern.compile(
"^([\\+](91))?([7-9]{1})([0-9]{9})$", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE);
Matcher match = pattern.matcher(phon);
if (match.matches()) {
return true;
} else {
return false;
}
}
private boolean isEmailIdValid(String Email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = Email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
public class SqlOpenHelper extends SQLiteOpenHelper {
public SqlOpenHelper() {
super(context, null, null, 0);
}
public SqlOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, null);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
public SQLiteOpenHelper open() throws SQLException {
mDb = DBHelper.getWritableDatabase();
return this;
}
public void colse() {
DBHelper.close();
}
public long insertContact(String email, String phon1, String phon2,
String phon3, String phon4, String name, String address) {
ContentValues initialValues = new ContentValues();
initialValues.put(EMAIL_COLUMN, email);
initialValues.put(PHONE1_COLUMN, phon1);
initialValues.put(PHONE2_COLUMN, phon2);
initialValues.put(PHONE3_COLUMN, phon3);
initialValues.put(PHONE4_COLUMN, phon4);
initialValues.put(UNAME_COLUMN, name);
initialValues.put(UADDR_COLUMN, address);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("TaskDBAdapter", "Upgrading from version" + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new
// version. Multiple previous versions can be handled by
// comparing oldVersion and newVersion values.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(db);
}
}
}
Activity should not have constructor! All should be done in lifecycle callbacks. Move content from ctor to onCreate() and remove ctor:
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
Drop this:
public Setupemail(Context ctx) {
this.context = ctx;
DBHelper = new SqlOpenHelper(context);
}
and delete context field. Setupemail class is inherited from Activity, it's a subclass of Context itself. If you want to reference Context you can use getBaseContext in inner class or even omit it at the Setupemail class.
you don't have an empty constructor. It needs to be defined when you define the other constructors
public Setupmail()
{
}