Data not inserted into SQLite database on android? - java

I have developed an Android database application.
The problem is that when I click the add button then a message shows that data was successfully added.
But the data is not inserted into the database.
I then open the database with SQLite viewer and there I can't find any of the data I inserted...
Register page code :
package com.example.dbapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Register extends Activity {
Button add;
TextView b,c;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
add = (Button) findViewById(R.id.btnReg);
b = (TextView) findViewById(R.id.etName);
c = (TextView) findViewById(R.id.etOccu);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String name = b.getText().toString();
String occ = c.getText().toString();
DataCon entry = new DataCon(Register.this);
entry.open();
entry.createEntry(name, occ);
entry.close();
Toast toast = Toast.makeText(getApplicationContext(), "Sucess", Toast.LENGTH_SHORT);
toast.show();
}
catch(Exception e) {
String err = e.toString();
Toast toast = Toast.makeText(getApplicationContext(), err, Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
Database Connection code :
package com.example.dbapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataCon {
public static final String rowid = "_id";
public static final String name = "persons_name";
public static final String hot = "persons_hotness";
private static final String DB_NAME = "myDB";
private static final String DB_TABLE = "tbl_me";
private static final int DB_VER = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DB_TABLE + " (" + rowid +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + name + "TEXT NOT NULL, " +
hot + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " +DB_TABLE);
onCreate(db);
}
}
public DataCon(Context c) {
ourContext = c;
}
public DataCon open() {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name2, String occ) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(name, name2);
cv.put(hot, occ);
return ourDatabase.insert(DB_TABLE, null, cv);
}
}
Now how can I solve the problem? thanks

An error in your sql. You haven't provide space between column name and type. Correct one should be
db.execSQL("CREATE TABLE " + DB_TABLE + " (" + rowid +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + name + " TEXT NOT NULL, " +
--------------------------- ^
hot + " TEXT NOT NULL);");`

Related

How To Add data to another table only if a checkbox is checked using Sqlite database?- android studio

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
}
}
});

how to update integer value in sqlite android

i am having problem with the updation part of the below code. insertion is working properly. when i added the update method for addition/subtraction of the integer stored in the database, the code is no longer working. it says the app has closed unfortunately. the app is not even opening. please check the update method and make sufficient changes.
first i used this code to accept name and email. then this code was changed to accept a number and email. variable name and column name has not been changed. please dont get confused with these.
thank you.
MainActivity.java
package com.sqltut;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save,load,updatebtn;
EditText name,email,update;
DataHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save=(Button) findViewById(R.id.save);
load=(Button) findViewById(R.id.load);
name=(EditText) findViewById(R.id.name);
email=(EditText) findViewById(R.id.email);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName=name.getText().toString();
String getEmail=email.getText().toString();
int number = Integer.parseInt(getName);
handler=new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(number, getEmail);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getEmail;
Integer getName;
getName=0;
getEmail="";
handler=new DataHandler(getBaseContext());
handler.open();
Cursor C=handler.returnData();
if(C.moveToFirst())
{
do
{
getName=C.getInt(0);
getEmail=C.getString(1);
}while(C.moveToNext());
}
handler.close();
Toast.makeText(getBaseContext(), "Name:"+getName+" And Email:"+getEmail,Toast.LENGTH_LONG).show();
}
});
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int number,flag=0; //flag to check for addition or subtraction
String getupdate=update.getText().toString();
number=Integer.parseInt(getupdate);
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(number,flag);
//subtraction: flag=0, addition: flag=1
handler.close();
}
});
//to call next activity
/* Button createAppointment = (Button)findViewById(R.id.Next);
createAppointment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, Page2.class);
MainActivity.this.startActivity(myIntent);
}
});
*/ }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
DataHandler.java
package com.sqltut;
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 DataHandler {
public static final String NAME="name";
public static final String EMAIL="email";
public static final String TABLE_NAME="mytable";
public static final String DATA_BASE_NAME="mydatabase";
public static final int DATABASE_VERSION=1;
public static final String TABLE_CREATE="create table mytable(name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{
this.ctx = ctx;
dbhelper=new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS mytable ");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(Integer name, String email)
{
ContentValues content=new ContentValues();
content.put(NAME, name);
content.put(EMAIL,email);
return db.insert(TABLE_NAME, null, content);
}
public void updateData(Integer number,Integer flag)
{
db = dbhelper.getReadableDatabase();
String select = "select name from " + TABLE_NAME ;
Cursor c = db.rawQuery(select, null);
int current=0;
if (c.moveToFirst()) {
current= Integer.parseInt(c.getString(0));
}
if(flag==0)//subtraction
{
current=current-number;
}
else//addition
{
current=current+number;
}
c.close();
db.close();
db = dbhelper.getReadableDatabase();
ContentValues content=new ContentValues();
content.put(NAME, current);
db.update(TABLE_NAME, content,null,null);
}
public Cursor returnData()
{
return db.query(TABLE_NAME, new String[] {NAME,EMAIL}, null, null, null, null, null);
}
}
Edited updateData()
public void updateData(Integer value,Integer flag)
{
db = dbhelper.getReadableDatabase();
String selectQuery = "select balance from " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
int current = 0;
if (cursor.moveToFirst()) {
current= Integer.parseInt(cursor.getString(0));
}
if(flag==0){
current = current-value;
}else {
current = current+value ;
}
cursor.close();
db.close();
try{
db = dbhelper.getWritableDatabase();
String rawQuery = "update mytable set balance="+current;
db.rawQuery(rawQuery, null);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Code worked. db.rawQuery(rawQuery, null); changed to db.execSQL(rawQuery);
You can update any value in your table by below method:
public void updateInteger(Integer newID)
{
try{
sqliteDb = appDb.getWritableDatabase();
String rawQuery = "update <table_name> set id="+newID;
sqliteDb.rawQuery(rawQuery, null);
Log.v(TAG, "ID updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

Can't instantiate Class and no empty constructor error

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()
{
}

Simple Android App SQLite login [duplicate]

This question already has an answer here:
SQL Lite android app login
(1 answer)
Closed 9 years ago.
I have an on going issue with my SQLite login for my app. I have a simple DBHandler class that has created a database, inside the database I have stored a single user: Username: test Password: 1234
I also have a LogInScreen class that handles the view of the login and also will hold the methods to authenticate the login.
I want the user to enter their login details into the text fields and when they press the login button to verify this against my database. As you can see in the attached image.
I already have the username stored and this is my code
The code does work but as you can see in the LogInScreen class it is not checking against my database but the actual text fields. Unfortunately I am completely new to SQLite and programming so I just can not figure it out. Any help will be highly appreciated :)
package com.C05025.noughtsandcrosses;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "userDB.db";
private static final String TABLE_USERS = "users";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_PASSWORD = "password";
public DBHandler(Context context, String name, CursorFactory factory,
int version) {
//super(context, name, factory, version);
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "("
+ " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT,"
+ COLUMN_PASSWORD + " INTEGER" + ")";
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public void addUser(LogIn user) {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, user.getName());
values.put(COLUMN_PASSWORD, user.getPassword());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_USERS, null, values);
db.close();
}
public LogIn findUser(String Username) {
String query = "Select * FROM " + TABLE_USERS + " WHERE " + COLUMN_NAME + " = \"" +
Username + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
LogIn User = new LogIn();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
User.setName(cursor.getString(1));
User.setPassword(Integer.parseInt(cursor.getString(2)));
cursor.close();
} else {
User = null;
}
db.close();
return User;
}
}
LoginScreen Class:
package com.C05025.noughtsandcrosses;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class LogInScreen extends Activity {
EditText txtUsername;
EditText txtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
txtUsername = (EditText) findViewById(R.id.EditUsername);
txtPassword = (EditText) findViewById(R.id.EditPassword);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void newLogIn(View view) {
if(txtUsername.getText().toString().equals("test") &&
txtPassword.getText().toString().equals("1234")){
Intent i = new Intent(LogInScreen.this, MainMenu.class);
startActivity(i);
LogInScreen.this.finish();
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
}
}
}
Even though I don't really understand the problem and I'd love to see the stacktrace, this is a wonderful guide you can use on how to add login and registration to your application using SQLite, MySQL and PHP.

Getting an error while creating new instance SQLITE

i have an error while making a creating a new instance for writing data to my database SQLlite
this is the code of my database class
package com.example.tttt;
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 info {
public static final String key_nom = "nom_personne";
public static final String key_id = "id_personne";
public static final String key_prenom = "prenom_personne";
private static final String DATABASE_NAME = "infodb";
private static final String DATABASE_TABLE = "infotable";
private static final int DATABASE_VERSION = 1 ;
private DbHelper ourHelper;
private 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_id + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
key_nom + " TEXT NOT NULL, " +
key_prenom + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public info open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String prenom) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(key_nom, name);
cv.put(key_prenom, prenom);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
in my class activity i wrote
info entry = new info(this);
entry.open();
entry.createEntry(name , prenom );
entry.close();
i had a error on info entry = new info(this);
the message error : " The constructor info(new View.OnClickListener(){}) is undefined "
when i change to info entry = new info(intro.this);
i got: "The constructor info(intro) is undefined"
the full intro activity where i try get information from the user and send them to the database
package com.example.tttt;
import com.example.tttt.R.layout;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.DropBoxManager.Entry;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class intro extends Activity {
Button sqlupdate,sqlview,sqlsearch;
EditText sqlnom, sqlprenom,sqltextsearch ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
sqlnom = (EditText)findViewById(R.id.nomenter);
sqlprenom = (EditText)findViewById(R.id.prenomenter);
sqlupdate = (Button) findViewById(R.id.button1);
sqlview = (Button) findViewById(R.id.button2);
// sqlsearch = (Button) findViewById(R.id.button3);
// sqltextsearch = (EditText)findViewById(R.id.editText1);
sqlupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean diditwork = true ;
try{
String name = sqlnom.getText().toString();
String prenom = sqlprenom.getText().toString();
entry = new info();
entry.open();
entry.createEntry(name , prenom );
entry.close();
}catch (Exception e ){
diditwork = false ;
String error = e.toString();
Dialog d = new Dialog(intro.this);
d.setTitle(" merde ");
TextView tv = new TextView(intro.this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if (diditwork){
Dialog d = new Dialog(intro.this);
d.setTitle(" okkk ");
TextView tv = new TextView(intro.this);
tv.setText(" ok yes ");
d.setContentView(tv);
d.show();
}
}
}
});
sqlview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent open = new Intent("android.intent.action.SQLVIEW");
startActivity(open);
}
});
sqlsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
/*String s = sqltextsearch.getText().toString();
info se = new info();
se.open();
String returne = se.search();
*/
}
});
}
}
you have to initialize the info class without parameters:
info entry = new info();
btw. It is common in class names to write the first letter uppercase: Info
Furthermore. If you dont have more code in info your application will throw a NullPointerException here ourDatabase.insert(DATABASE_TABLE, null, cv);
Here in the Class Info there is no Constructor with an Argument of type Intro
Create one if you really need to have the instance of the class Intro at Class Info.
public Info(Intro intro){
}
Else Create a Constructor without any argument passed.
Info entry = new Info(this);
Always try to follow the naming Conventions, its not a good way to program in any way you like. http://www.oracle.com/technetwork/java/codeconv-138413.html

Categories

Resources