I am using a simple demo program, I am creating Database, then a table and trying to add values to the table
What i am able to do::
I am able to create table in sqlite
What i am not able to do::
I am not able to insert values values into it
MainActivity.java
public class MainActivity extends Activity{
Button addUser;
SqliteAdapter helper;
EditText usrName,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new SqliteAdapter(this);
addUser=(Button) findViewById(R.id.button1);
usrName=(EditText) findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
}
public void addUser(View view){
Log.d("LOG-MSG", "Onclick detected");
helper.insertData(usrName.getText().toString(), pwd.getText().toString());
}
}
SqliteAdapter.java
public class SqliteAdapter{
SqliteHelper helper;
ContentValues cv;
SQLiteDatabase db;
public SqliteAdapter(Context context){
helper=new SqliteHelper(context);
}
public void insertData(String name,String password){
db=helper.getWritableDatabase();
Log.d("LOG-MSG", "insertDataMethod Entry");
try {
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password inserted");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-EXCEPTION", e.toString());
}
db.insert(SqliteHelper.TABLE_NAME, null, cv);
}
static class SqliteHelper extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME="MyDatabase";
private final static String TABLE_NAME="MyTable";
private static final int DATABASE_VERSION=1;
private final static String ID="_id";
private final static String NAME="name";
private final static String PASSWORD="password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(225), "+PASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
Log.d("LOG-MSG", "Constructor Called");
Message.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("LOG-MSG", "OnCreate Called");
Message.message(context, "OnCreate Called");
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onUpgrade", e.toString());
Message.message(context, "onUpgrade Called");
}
onCreate(db);
}
}
}
Log::
04-18 13:45:19.567: D/LOG-MSG(3371): Constructor Called
04-18 13:45:20.007: D/gralloc_goldfish(3371): Emulator without GPU emulation detected.
04-18 13:45:20.107: W/TextLayoutCache(3371): computeValuesWithHarfbuzz -- need to force to single run
04-18 13:46:22.747: D/LOG-MSG(3371): Onclick detected
04-18 13:46:22.809: D/LOG-MSG(3371): insertDataMethod Entry
04-18 13:46:22.809: D/LOG-MSG-EXCEPTION(3371): java.lang.NullPointerException
04-18 13:46:22.817: I/SqliteDatabaseCpp(3371): sqlite returned: error code = 1, msg = near "null": syntax error, db=/data/data/com.example.sqlitedatabasedemo/databases/MyDatabase
{After EDIT}
MainActivity.java
public class MainActivity extends Activity{
Button addUser;
SqliteAdapter helper;
EditText usrName,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new SqliteAdapter(this);
addUser=(Button) findViewById(R.id.button1);
usrName=(EditText) findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
}
public void addUser(View view){
Log.d("LOG-MSG", "Onclick detected");
long recievedValue=helper.insertData(usrName.getText().toString(), pwd.getText().toString());
if(recievedValue<0){
Log.d("LOG-MSG", "NotInserted");
}else
{
Log.d("LOG-MSG", "Inserted");
}
}
}
SqliteAdapter.java
public class SqliteAdapter{
SqliteHelper helper;
ContentValues cv;
SQLiteDatabase db;
public SqliteAdapter(Context context){
helper=new SqliteHelper(context);
}
public long insertData(String name,String password){
db=helper.getWritableDatabase();
Log.d("LOG-MSG", "insertDataMethod Entry");
cv=new ContentValues();
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name="+name+"inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password="+password+"inserted");
long result=db.insert(SqliteHelper.TABLE_NAME, null, cv);
return result;
}
static class SqliteHelper extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME="MyDatabase";
private final static String TABLE_NAME="MyTable";
private static final int DATABASE_VERSION=1;
private final static String ID="_id";
private final static String NAME="name";
private final static String PASSWORD="password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(225), "+PASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
Log.d("LOG-MSG", "Constructor Called");
Message.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("LOG-MSG", "OnCreate Called");
Message.message(context, "OnCreate Called");
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}
Log::
04-18 14:21:59.937: D/LOG-MSG(13661): Onclick detected
04-18 14:22:00.337: D/LOG-MSG(13661): insertDataMethod Entry
04-18 14:22:00.337: D/LOG-MSG(13661): Name=usainserted
04-18 14:22:00.337: D/LOG-MSG(13661): password=obamainserted
04-18 14:22:00.377: D/LOG-MSG(13661): Inserted
problem:: When i check the DDMS ....i can see the database. when i see it in query browser there are no values inserted .... why is this happening ... ive also tried to debug possible log statements
You haven't initialized your ContentValues cv object. There's an NPE you catch and then you proceed with attempting to insert with null ContentValues reference, causing the exception that terminates the app.
Add cv = new ContentValues() to your insert code.
Don't catch Exception. Most of the time it just hides the problems you should be fixing.
Similarly in onCreate() and onUpgrade() you should not catch SQLException but just let it propagate to the caller.
It seems you are not making the instame of ContentValues . Try to do as below
public void insertData(String name,String password){
db=helper.getWritableDatabase();
Log.d("LOG-MSG", "insertDataMethod Entry");
try {
cv = new ContentValues ();
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password inserted");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-EXCEPTION", e.toString());
}
db.insert(SqliteHelper.TABLE_NAME, null, cv);
}
hi you have a problem that ContentValues cv is not instantiated properly.
please add the line cv = new ContentValues ();
use the following code
public class SqliteAdapter{
SqliteHelper helper;
ContentValues cv;
SQLiteDatabase db;
public SqliteAdapter(Context context){
helper=new SqliteHelper(context);
}
public void insertData(String name,String password){
db=helper.getWritableDatabase();
cv = new ContentValues ();
Log.d("LOG-MSG", "insertDataMethod Entry");
try {
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password inserted");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-EXCEPTION", e.toString());
}
db.insert(SqliteHelper.TABLE_NAME, null, cv);
}
static class SqliteHelper extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME="MyDatabase";
private final static String TABLE_NAME="MyTable";
private static final int DATABASE_VERSION=1;
private final static String ID="_id";
private final static String NAME="name";
private final static String PASSWORD="password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(225), "+PASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
Log.d("LOG-MSG", "Constructor Called");
Message.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("LOG-MSG", "OnCreate Called");
Message.message(context, "OnCreate Called");
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onUpgrade", e.toString());
Message.message(context, "onUpgrade Called");
}
onCreate(db);
}
}
}
Related
I want to open my database with SQLite. But when attempting to take data from a TextInputEditText and put it into the database it throws NPE at db = this.getWritableDatabase();
Seems that most of the time this is caused by the context being null. But it is not null and I checked it with debugger. (myDB = new DatabaseHelper(this);)
(I have tried all other questions about this problem and my situation must be different because they did not help.)
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
TextInputEditText inputEmail;
TextInputEditText inputPass;
Button btn_login;
Button btn_signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myDB = new DatabaseHelper(this);
} catch (Exception e) {
System.out.print("Exception occurred");
}
btn_signup = findViewById(R.id.btn_signup);
btn_login = findViewById(R.id.btn_login);
addData();
}
public void addData() {
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = findViewById(R.id.editTextEmail);
inputPass = findViewById(R.id.editTextPass);
//try {
myDB.insertData(inputEmail.getText().toString(),
inputPass.getText().toString());
Toast.makeText(MainActivity.this, "Data Inserted",
Toast.LENGTH_LONG).show();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
});
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Login_android.db";
public static final String TABLE_NAME = "login_table.db";
public static final String COL1 = "ID";
public static final String COL2 = "EMAIL";
public static final String COL3 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +" (ID INTEGER PRIMARY KEY
AUTOINCREMENT, EMAIL TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String email, String password) {
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//db.isOpen();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, email);
contentValues.put(COL3, password);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
}
Exception
12-06 23:39:12.799 26304-26304/com.example.ryan.temporaryname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryan.temporaryname, PID: 26304
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
at com.example.ryan.temporaryname.DatabaseHelper.insertData(DatabaseHelper.java:45)
at com.example.ryan.temporaryname.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I think the problem is about TABLE_NAME - "login_table.db" suggests a table named "db" in a database named "login_table", which does not exist, and a null database object is returned.
Please try to change the name.
i think you should ( if this is not a test sqlite app) create a singleton by create a App() class and initialize the database in there.Try to firgure out your problem too
I am building a training log that uses an sqlite database to save what the user inputs. Currently, I only have an add method that appends to the database, but am unsure as to how to create a delete method that removes the row created. The user data is initially created and added in TrainingLogCreate (class), which accesses DBAdapter's (Class) add method. What can I add to my remove method in DBAdapter to be able to remove a user entry?
TrainingLogCreate:
public class TrainingLogCreate extends AppCompatActivity {
EditText nameTxt;
EditText posTxt;
Button savebtn;
Context context = this;
public TrainingLogCreate() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_log_create);
savebtn = (Button) findViewById(R.id.saveButton);
nameTxt = (EditText) findViewById(R.id.exercizeActivity);
posTxt = (EditText) findViewById(R.id.exercizeDetails);
final DBAdapter db = new DBAdapter(this);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String datetime;
try {
Date date = new Date();
datetime = dateFormat.format(date);
} finally {
}
final String dateTxt = datetime;
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//OPEN
db.openDB();
//INSERT
long result = db.add(nameTxt.getText().toString(), posTxt.getText().toString(), dateTxt.toString());
if (result > 0) {
nameTxt.setText("");
posTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
//CLOSE DB
db.close();
//Open Fragment
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.training_create_menu, menu);
getActionBar().show();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_save:
//add save functionality
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DBAdapter:
public class DBAdapter {
//COLUMNS
static final String ROWID="id";
static final String NAME = "name";
static final String POSITION = "position";
static final String DATE = "date";
//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,position TEXT NOT NULL,date TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(FragmentActivity ctx) {
// TODO Auto-generated constructor stub
this.c=ctx;
helper=new DBHelper(c);
}
// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context ) {
super(context, DBNAME, null, DBVERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(CREATE_TB);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("DBAdapetr","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
// OPEN THE DB
public DBAdapter openDB()
{
try
{
db=helper.getWritableDatabase();
}catch(SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
//CLOSE THE DB
public void close()
{
helper.close();
}
//INSERT INTO TABLE
public long add(String name,String pos, String date)
{
try
{
ContentValues cv=new ContentValues();
cv.put(NAME, name);
cv.put(POSITION, pos);
cv.put(DATE, date);
return db.insert(TBNAME, ROWID, cv);
}catch(SQLException e)
{
e.printStackTrace();
}
return 0;
}
//REMOVE FROM TABLE
public long remove(String name)
{
}
//GET ALL VALUES
public Cursor getAllNames()
{
String[] columns={ROWID,NAME,POSITION,DATE};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
You can have a delete method like this
public void deleteInterestId(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TIMEKEEPER, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You have to pass the id which you want to delete. You have to customize this method a bit but it will give you an idea
And the most important thing for delete is that you have to also create a column named id and increase it's value as record are inserted. Because you can't delete on base of id that is created automatically by database
I made an android eclipse project that uses SQLite as a database.
Some errors occur when I try to run the project on the phone. When I click the view button(to view my database), The application says:
no columns in my database.
Why does it happen?
Data Layer:
public class Translator {
public static final String KEY_ROWID ="_id";
public static final String KEY_DESC ="page_desc";
private static final String DATABASE_NAME ="Translatordb";
private static final String DATABASE_TABLE ="pageTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " STRING PRIMARY KEY, " +
KEY_DESC + " TEXT NOT NULL);"
);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Translator(Context c){
ourContext = c;
}
public Translator open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String id, String description){
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID,id);
cv.put(KEY_DESC,description);
return ourDatabase.insert(DATABASE_TABLE,null, cv);
}
public long createEntry1(String id, String description){
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID,"P01");
cv.put(KEY_DESC,"Snow White");
return ourDatabase.insert(DATABASE_TABLE,null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID,KEY_DESC};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns,null,null,null,null,null);
String result =" ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iDescription = c.getColumnIndex(KEY_DESC);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result =result + c.getString(iRow)+ " " +c.getString(iDescription) +" \n";
}
return result;
}
main Activity.java
public class MainActivity extends Activity implements OnClickListener {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view =(Button) findViewById(R.id.viewSQL);
view.setOnClickListener(this);
}
//product qr code mode
public void scanQR(View v) {
try {
//start the scanning activity from the com.google.zxing.client.android.SCAN intent
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
//on catch, show the download dialog
showDialog(MainActivity.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
//alert dialog for downloadDialog
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
//on ActivityResult method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//get the extras that are returned from the intent
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
toast.show();
}
}
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.viewSQL:
Translator entry = new Translator(MainActivity.this);
entry.open();
entry.close();
Intent i = new Intent("com.example.scanner.SQLVIEW");
startActivity(i);
break;
}
}
SQLView.java
public class SQLView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv =(TextView) findViewById(R.id.tvSQLint);
Translator info = new Translator(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
this is my error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.scanner/com.example.scanner.SQLView}:
android.database.sqlite.SQLiteException: no such column: page_desc
(code 1):, while compiling: SELECT _id, page_desc FROM pageTable
What is my error?
Try this
public class Translator extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public Translator(Context applicationcontext) {
super(applicationcontext, "androidsqlite.db", null, 1);
Log.d(LOGCAT, "Created Translator Database");
}
public static final String KEY_ROWID = "_id";
public static final String KEY_DESC = "page_desc";
private static final String DATABASE_TABLE = "pageTable";
private SQLiteDatabase ourDatabase;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " STRING PRIMARY KEY, " + KEY_DESC + " TEXT NOT NULL);");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public long createEntry(String id, String description) {
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID, id);
cv.put(KEY_DESC, description);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public long createEntry1(String id, String description) {
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID, "P01");
cv.put(KEY_DESC, "Snow White");
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_DESC };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = " ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iDescription = c.getColumnIndex(KEY_DESC);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " "
+ c.getString(iDescription) + " \n";
}
return result;
}
}
I'm Developing an android app in which there are Login activity and a Questionnaire activity contains Questions which as radio Buttons and also a Button(Next).So now I wanted to create a database to store the values of the respective fields. I've typed the code for dataHandler and Login.java now the problem is i wanted to know whether the table has been created and also how to view my table please help me and also please check whether my code is correct.
Thanks in Advance.
Here is code for the DatabaseAdapter.java
public class DatabaseAdapter {
DatabaseHandler dbhandler;
public DatabaseAdapter(Context context){
dbhandler =new DatabaseHandler(context);
}
public long insertData(String name,String desig,String years,String dept)
{
SQLiteDatabase db=dbhandler.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(DatabaseHandler.NAME, name);
content.put(DatabaseHandler.DESIGNATION,desig);
content.put(DatabaseHandler.YEARS, years);
content.put(DatabaseHandler.DEPARTMENT, dept);
long id=db.insertOrThrow(DatabaseHandler.TABLE_NAME, null, content);
return id;
}
static class DatabaseHandler extends SQLiteOpenHelper {
private static final String NAME="name";
private static final String DESIGNATION="desig";
private static final String YEARS="years";
private static final String DEPARTMENT="dept";
private static final String TABLE_NAME="visteon";
private static final String DATA_BASE_NAME="VisteonSurvey";
private static final int DATABASE_VERSION=2;
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+NAME+" VARCHAR(255),"+DESIGNATION+"text not null,"+YEARS+" text not null,"+DEPARTMENT+" text not null);";
public DatabaseHandler(Context context)
{
super(context,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL("DROP TABLE IF EXISTS visteon");
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is code for Login.java
public void OnClickListener(View v)
{
name=(EditText)findViewById(R.id.editText1);
years1=(RadioButton)findViewById(R.id.radioButton3);
years2=(RadioButton)findViewById(R.id.radioButton4);
years3=(RadioButton)findViewById(R.id.radioButton5);
manager=(RadioButton)findViewById(R.id.radioButton1);
teamleader=(RadioButton)findViewById(R.id.radioButton2);
rg1=(RadioGroup)findViewById(R.id.Designation);
rg2=(RadioGroup)findViewById(R.id.Years);
dept=(Spinner)findViewById(R.id.spinner1);
proceed = (Button)findViewById(R.id.button1);
proceed.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (validationSuccess())
{
if(manager.isChecked())
{
Intent managerIntent = new Intent(getApplicationContext(), ManagerQuestionnaire1.class); // <----- START "SEARCH" ACTIVITY
startActivityForResult(managerIntent, 0);
}
else
{
Intent teamleaderIntent = new Intent(getApplicationContext(), TeamleaderQuestionnaire1.class); // <----- START "TYPE ENTRIES OUT" ACTIVITY
startActivityForResult(teamleaderIntent, 0);
}
}
else {
AlertDialog();
}
String user=name.getText().toString();
String designation=rg1.getContext().toString();
String experience=rg2.getContext().toString();
String department=dept.getContext().toString();
long id= DatabaseHandler.insertData (user, designation, experience, department);
Toast.makeText(getBaseContext(),"Form Updated",Toast.LENGTH_LONG).show();
}
});
I wish to query my username against an already existing table in the database. But when I executed my code, my app force closed due to "SQLite returned error code: 1, msg = near "=": syntax error.
Here is the DBAdapter.java file
package com.example.usernammepassword;
import android.content.ContentValues;
public class DBAdapter {
public static final String KEY_NAME = "UserName";
public static final String KEY_PASS = "Password";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "Test";
private static final String DATABASE_TABLE = "UsernamePassword";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table if not exists UsernamePassword (UserName text not null primary key, Password text not null);";
private final Context context;
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 db1) {
try {
db1.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public DBAdapter open() throws SQLException {
public void close() {
public long insertNewUser(String UserName, String Password) {
public boolean deleteUser(String UserName)
public Cursor getAllUserNamesAndPasswords()
{
return db.query(DATABASE_TABLE, new String[] { KEY_NAME,
KEY_PASS}, null, null, null, null, null);
}
public Cursor getPasswordForUserName(String UserName) throws SQLException
public boolean updatePasswordForUserName( String UserName, String Password) {
}
And the MainActivity.java file
package com.example.usernammepassword;
import android.os.Bundle;
public class MainActivity extends Activity {
private String md5(String in) {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText text = (EditText)findViewById(R.id.editText1);
EditText text1 = (EditText)findViewById(R.id.editText2);
String userid = text.getText().toString();
String pass = text1.getText().toString();
Toast.makeText(MainActivity.this,"Entered "+userid+" and password entered is "+pass,Toast.LENGTH_LONG).show();
pass = md5(pass + "#string/salt");
Toast.makeText(MainActivity.this,"Password after adding a salt and md5 hashing is now equal to " + pass,Toast.LENGTH_LONG).show();
DBAdapter db = new DBAdapter(MainActivity.this);
db.open();
Cursor c = db.getPasswordForUserName(userid);
if(c.moveToFirst())
{
if(c.getString(1) == pass)
{
Toast.makeText(MainActivity.this, "Authentication Succeded", Toast.LENGTH_SHORT).show();
//proceed
}
else
{
Toast.makeText(MainActivity.this, "#string/AuthFail", Toast.LENGTH_SHORT).show();
//AuthFailure
}
}
else
{
Toast.makeText(MainActivity.this,"#string/UserNotFound", Toast.LENGTH_SHORT).show();
//where to from here
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
}
The Logcat:
You probably updated your table name from something to UserNamePassword, but didn't change the DATABASE_VERSION, which will trigger onUpgrade().
Of course onUpgrade() has to be implemented as well to create the appropriate table.