I have the following error
"/SQLiteLog﹕ (1) near "TABLEusers": syntax error
System.err﹕ android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(_id(INTEGER PRİMARY KEY AUTOINCREMENT ,u_nameTEXT NOT NULL,u_passTEXT NOT NULL);"
1023-1023/com.example.dogruprint.dogruprint2 E/SQLiteLog﹕ (1) near ")": syntax error
--------------------- DATABASE.java -------------------------------------
package com.example.dogruprint.dogruprint2;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.sql.SQLException;
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "u_name";
public static final String KEY_PASS = "u_pass";
private static final String DB_NAME = "app";
private static final String DB_TABLE = "users";
private static final int version = 1;
private SQLiteDatabase ourDatabase;
private DBHelper ourHelper;
private Context ourContext;
private SQLiteDatabase writableDatabase;
public Database(Context context) {
ourContext = context;
}
public SQLiteDatabase getWritableDatabase() {
return writableDatabase;
}
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context)
{
super(context, DB_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
/* db.execSQL("CREATE TABLE" + DB_TABLE + "("
+ KEY_ROWID + "(INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ KEY_NAME + "TEXT NOT NULL,"
+ KEY_PASS + "TEXT NOT NULL);");
*/
String CREATE_USERS_TABLE = "CREATE TABLE " + DB_TABLE + "(" + KEY_ROWID +
" INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PASS + " TEXT,"
+ ");";
db.execSQL(CREATE_USERS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + DB_TABLE);
}
}
public Database open() throws SQLException {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public Database close() {
ourHelper.close();
return this;
}
public void addThat(String name, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_PASS, pass);
ourDatabase.insert(DB_TABLE, null, cv);
}
}
------------------------------ siparisekle.java ----------------------------
package com.example.dogruprint.dogruprint2;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.sql.SQLException;
import static android.R.*;
public class siparisekle extends Activity {
private AutoCompleteTextView act1, act2, act3;
private EditText edittxt1;
EditText etName,etPass;
TextView tvResult;
Button bSave;
Button bShow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_siparisekle);
install_elements();
final Database db = new Database(this);
bSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean ok = true;
String name = etName.getText().toString();
String pass = etPass.getText().toString();
try
{
db.open();
db.addThat(name, pass);
tvResult.setText(name + "Eklendi");
db.close();
}
catch (Exception e)
{
ok =false;
e.printStackTrace();
tvResult.setText("Sorun var");
}
finally
{
if(ok)
{
Dialog d =new Dialog(siparisekle.this);
TextView tv = new TextView(siparisekle.this);
tv.setText("BASARILI");
d.setTitle("Sonuç");
d.setContentView(tv);
d.show();
}
}
}
});
}
protected void install_elements()
{
etName = (EditText) findViewById(R.id.etName);
etPass= (EditText) findViewById(R.id.etPass);
tvResult= (TextView) findViewById(R.id.tvResult);
bSave= (Button) findViewById(R.id.bSave);
bShow= (Button) findViewById(R.id.bShow);
}
}
This was you problem
db.execSQL("CREATE TABLE" + DB_TABLE + "("
Then you fixed it
String CREATE_USERS_TABLE = "CREATE TABLE " + DB_TABLE + "(" ....
By adding the missing space.
But you have to remove the last comma here:
" TEXT,"
+ ");";
The semicolon is only useless, not harmful.
But the comma is an error and will cause problems.
But you didn't fix this:
db.execSQL("DROP TABLE IF EXIST" + DB_TABLE);
You need a space here too
db.execSQL("DROP TABLE IF EXIST " + DB_TABLE);
Anyway, now you have to uninstall and reinstall your app.
Create table query :
private static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ FNAME + " VARCHAR(255) , "
+ LNAME + " VARCHAR(255) ,"
+ PASSWORD + " text ,"
+ EMAIL + " VARCHAR(255) UNIQUE ,"
+ BIRTHDAY + " VARCHAR(255) ,"
+ GENDER + " VARCHAR(255) ,"
+ IMAGE + " text );";
I'm pretty sure you don't need the semi colon at the end your CREATE_USERS_TABLE String
Related
I am currently building a password manager app for myself. I plan to save the passwords in a SQLite database. For that I use this code:
package com.example.passwordmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String COLUMN_PASSWORD = "password";
public static final String PASSWORDS_TABLE = COLUMN_PASSWORD + "s_table";
public static final String COLUMN_ID = "id";
public static final String COLUMN_SERVICE = "service";
public static final String COLUMN_CREATION_DATE = "creation_date";
public static final String COLUMN_USED_NAME = "used_name";
public static final String COLUMN_USED_EMAIL = "used_email";
public DatabaseHelper(#Nullable Context context) {
super(context, "passwordManager.db", null,1);
Log.d("DatabaseHelper","Constructor reached");
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE "+ PASSWORDS_TABLE + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_SERVICE + " VARCHAR(40), " + COLUMN_PASSWORD + " VARCHAR(40), " + COLUMN_CREATION_DATE + " VARCHAR(11), " + COLUMN_USED_NAME + " VARCHAR(40), " + COLUMN_USED_EMAIL + " VARCHAR(40), master VARCHAR(20), firstTime BOOLEAN)";
Log.d("DatabaseHelper","OnCreate1 reached");
db.execSQL(createTableStatement);
Log.d("DatabaseHelper","OnCreate2 reached");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+PASSWORDS_TABLE);
onCreate(db);
}
public boolean addToTable(Registration profile){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PASSWORD,profile.hashedPassword);
cv.put(COLUMN_SERVICE,profile.service);
cv.put(COLUMN_CREATION_DATE,profile.creation_date);
cv.put(COLUMN_USED_NAME,profile.used_name);
cv.put(COLUMN_USED_EMAIL,profile.used_email);
long insert = db.insert(PASSWORDS_TABLE, null, cv);
if(insert==-1){
return true;
}else{
return false;
}
}
}
The problem with this code is, it just doesn't create the database or the folder of the database in data\data\com.example.passwordmanager. I tried outputting which methods it will reached when the constructor is called and I realized that it never reaches the onCreate method.
The DatabaseHelper class is only called once so for:
package com.example.passwordmanager;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class CreatingNewEntryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creating_new_entry);
DatabaseHelper dh = new DatabaseHelper(CreatingNewEntryActivity.this);
}
Is this a problem with the code? Do I have to give permissions in the manifest.xml? Did I mess something up with the emulator? The App starts fine, it just doesn't create the database.
You need to call getWritableDatabase() or getReadableDatabase() on your database helper to make the framework create the database file and trigger onCreate(). Just calling the constructor is not enough.
See also: When is SQLiteOpenHelper onCreate() / onUpgrade() run?
Is there a way to grab a column from the database created, and store the
values found in the column into an array?
My main goal, is to get values in from a column, and store them into a spinner.
Look below for code!
PatientDbHelper.java
package tanav.sharma;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tanav on 11/4/2016.
*/
public class PatientDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "PATIENTINFO.db";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY = "CREATE TABLE "
+ PatientInfo.NewPatientInfo.TABLE_NAME + " ("
+ PatientInfo.NewPatientInfo.PATIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PatientInfo.NewPatientInfo.PATIENT_FNAME+ " TEXT,"
+ PatientInfo.NewPatientInfo.PATIENT_LNAME+" TEXT,"
+ PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT+" TEXT);";
private static final String CREATE_QUERY_TEST =
"CREATE TABLE "
+ TestInfo.NewTestInfo.TABLE_TEST_NAME + " ("
+ TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE + " TEXT,"
+ TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL + " TEXT,"
+ TestInfo.NewTestInfo.TEST_RESPITORY_RATE +" TEXT,"
+ TestInfo.NewTestInfo.TEST_HEART_RATE +" TEXT);";
public PatientDbHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS","Database created / opened ...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
db.execSQL(CREATE_QUERY_TEST);
Log.e("DATABASE OPERATIONS","Table created...");
}
public void addInformations(int id, String fname, String lname, String department, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
if ( id != 0 ){ contentValues.put(PatientInfo.NewPatientInfo.PATIENT_ID, id); }
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_FNAME,fname);
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_LNAME,lname);
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT,department);
db.insert(PatientInfo.NewPatientInfo.TABLE_NAME, null,contentValues);
Log.e("DATABASE OPERATIONS","One in row inserted...");
}
public void addTestInformation(/*String BP*/ int BL, int RR, int HR, SQLiteDatabase db){
ContentValues contentTestValues = new ContentValues();
//contentTestValues.put(TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE, BP);
contentTestValues.put(TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL,BL);
contentTestValues.put(TestInfo.NewTestInfo.TEST_RESPITORY_RATE, RR);
contentTestValues.put(TestInfo.NewTestInfo.TEST_HEART_RATE, HR);
db.insert(TestInfo.NewTestInfo.TABLE_TEST_NAME, null, contentTestValues);
Log.e("DATABASE OPERATIONS", "One in row inserted...");
}
/* public Cursor getPatientDepartment(String departments, SQLiteDatabase sqLiteDatabase){
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_LNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
String selection = PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT+ " LIKE ?";
String[] selection_args = {departments};
Cursor cursor = sqLiteDatabase.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}*/
public Cursor getPatientsId(int patient_id,SQLiteDatabase sqLiteDatabase){
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_ID, PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
String selection = PatientInfo.NewPatientInfo.PATIENT_ID+ " LIKE ?";
String convert = String.valueOf(patient_id);
String[] selection_args = {convert};
Cursor cursor = sqLiteDatabase.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_LNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
cursor = db.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
public Cursor getTestInformation(SQLiteDatabase db){
Cursor cursorTest;
String[] testProjections = {TestInfo.NewTestInfo.TEST_HEART_RATE, TestInfo.NewTestInfo.TEST_RESPITORY_RATE, TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL, TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE};
cursorTest = db.query(TestInfo.NewTestInfo.TABLE_TEST_NAME,testProjections,null,null,null,null,null);
return cursorTest;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Above is my Database handler class, I want to grab the column PATIENT_FNAME and store all those values into an Array. Then Later on, in my AddTest.java file, i want to display these values into an spinner.
Below is my AddTest.java
package tanav.sharma;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddTest extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton radioButton;
EditText etBL, etRR, etHBR;
Spinner patients;
Context context;
PatientDbHelper patientDbHelper;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_test);
getSupportActionBar().setTitle(R.string.add_test);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etBL = (EditText) findViewById(R.id.etBOL);
etRR = (EditText) findViewById(R.id.etRR);
etHBR = (EditText) findViewById(R.id.etHBR);
patients = (Spinner) findViewById(R.id.spinner);
}
public void addTest(View view){
radioGroup = (RadioGroup) findViewById(R.id.radio);
Button addTest = (Button) findViewById(R.id.addTest);
addTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(selectedId);
}
});
//String BP = radioButton.getText().toString();
int BL = Integer.parseInt(etBL.getText().toString());
int RR = Integer.parseInt(etRR.getText().toString());
int HR = Integer.parseInt(etHBR.getText().toString());
patientDbHelper = new PatientDbHelper(this);
sqLiteDatabase = patientDbHelper.getWritableDatabase();
patientDbHelper.addTestInformation(BL,RR,HR,sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_LONG).show();
patientDbHelper.close();
}
}
You can do something like
List<String> names = new ArrayList<>();
Cursor cursor = patientDbHelper.getInformations(sqLiteDatabase);
if (cursor != null){
while(cursor.moveToNext()){
names.add(cursor.getString(cursor.getColumnIndex(PatientInfo.NewPatientInfo.PATIENT_FNAME)));
}
cursor.close();
}
I've built a database class in Android using SQLite, so far it just creates a database and inputs data, however the only log report I see is that the data has been input, but the log never shows for the database creation.
I have also seen people have a .db file in their assets folder, mine is not created.
so:
1) How come it's not showing the log error for building the database, and also is there meant to be a .db file created through SQLite? It's my first time using it.
2) If it is creating, how can I call the List from the getData() method and output it in MainActivity? I've tried using intents but once I realised I wasn't getting the log report from the database creation so I need that sorted before anything.
MainActivity.java
public class MainActivity extends Activity {
Intent appIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB db = new DB(this);
db.insertStudent("T", "T", 5, "T", "T", "T");
List<tableStudents> outputList = db.getData();
}
DB.java
package com.example.project;
import java.util.ArrayList;
import java.util.List;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Modules + "TEXT");
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Password, password);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
//Log for admin insert
Log.d("DB", "Inserted Successfully");
return true;
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Matt Murphy please go through this link for each detail for your project
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/.
The aim is to retrieve the car park names from the car park tables columns 'CPNAME' and put those rows of names in another class' arraylist which a spinner will display.
The problem is apparently with my getCpNames() method, specifically on this line:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_CPNAME, null, null, null,
null);
The errors I get on LogCat:
Caused by: java.lang.NullPointerException
at com.example.parkangel.DbHelper.getCpnames(DbHelper.java:93)
at com.example.parkangel.BookTicket.<init>(BookTicket.java:19)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
My database class code:
package com.example.parkangel;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper
{
private static DbHelper dbHelper;
private Context ourContext;
private static DbHelper instance;
private static SQLiteDatabase ourDatabase;
private static final String DATABASE_NAME = "CPDB.db";
private static final String DATABASE_TABLE = "CPTable";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CPNAME = "cpname";
public static final String KEY_COST = "cost";
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
this.ourContext = context;
}
public static DbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new DbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CPNAME + " TEXT NOT NULL, " + KEY_COST + " TEXT NOT NULL);");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('1','Learning
Resource Center','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('2','Park and
Ride','1');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('3','de
Havilland Campus','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('4','Multi
Storey Building','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values
('5','Reception','2');");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized DbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen());
this.ourDatabase = getWritableDatabase();
return this;
}
public static String[] getCpnames()
{
String[] columns = new String[] {KEY_ID, KEY_CPNAME, KEY_COST};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_CPNAME,
null, null, null, null);
ArrayList<String> list = new ArrayList<String>();
if (c != null)
{
c.moveToFirst();
do
{
list.add(c.getString(0));
}
while (c.moveToNext());
}
if (ourDatabase == null) System.out.println ("is null");
return list.toArray(new String[]{});
}
}
This is the class and arraylist I am calling getCpnames() into:
package com.example.parkangel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class BookTicket extends Activity implements OnClickListener{
Spinner spinner, spinner2;
DbHelper dbhelper = DbHelper.getInstance(this);
String[] carParks = DbHelper.getCpnames();
I am beginner, so apologies for any amateur mistakes. Thank you in advance!
You never called DbHelper.open();
BTW, I also see a potential problem here
public synchronized DbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen());
this.ourDatabase = getWritableDatabase();
return this;
}
especially on this line
if(ourDatabase == null || !ourDatabase.isOpen());
The semicolon ";" at the end of line makes the if statement ineffective
The most likely explanation is that ourDatabase is null. You failed to call DBHelper.open() to set it.
Kohli.java
package com.kohli;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
public class KohlifActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("KOHLIActivity", "qwert11111111");
setContentView(R.layout.main);
Log.i("KOHILActivity", "qwert22222222222");
DbHelper1 DbHelper=new DbHelper1(this) ;
Log.i("KOHLIfActivity", "qwert3333333333");
}
}
DbHelper1.java
package com.kohli;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DbHelper1 extends SQLiteOpenHelper
{
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
Log.d(TAG, "constructor111111");
//System.out.println("dbhelper constructor");
}
// Called only once, first time the DB is created
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + " (" + C_ID + " int primary key, "
+ C_CREATED_AT + " int, " + C_USER + " text, " + C_TEXT + " text)";
db.execSQL(sql);
Log.d(TAG, "onCreated sql:22222222 ");
//System.out.println("dbhelper oncreate");
}
// Called whenever newVersion != oldVersion
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Typically do ALTER TABLE statements, but...we're just in development,
// so:
db.execSQL("drop table if exists " + TABLE); // drops the old database
Log.d(TAG, "onUpdated 33333333");
//System.out.println("dbhelper onupgrade");
onCreate(db); // run onCreate to get new database
}
}
i wrote the following code to make a database with a table... the output at logcat is :: qwert111111 qwert22222 constructor111111 qwert3333 .. that is the oncreate function is not being called so the database is also not created...
The database isn't actually created until you call getWritableDatabase() on the
dbHelper object.