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.
Related
I was adding a list view to my database when in the end the database list view windows opens and crashes
Do you have any idea what this crash code mean? I can add code later if you need it
(Edit still no luck finding anything that could throw this command)
Can you check with a command any way?
Database form:
package com.example.laivumusis;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.example.laivumusis.KlausimuContracts.*;
import java.util.ArrayList;
import java.util.List;
public class KlausimynoDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Klausimynas.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public KlausimynoDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
KlausimuLentele.TABLE_NAME + " ( " +
KlausimuLentele._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KlausimuLentele.COLUMN_QUESTION + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION1 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION2 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION3 + " TEXT, " +
KlausimuLentele.COLLUMN_ANSWER_NR + " INTEGER" +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillKlausimuLentele();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + KlausimuLentele.TABLE_NAME);
onCreate(db);
}
public boolean addData (String pasirinkimas1){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KlausimuLentele.COLLUMN_OPTION1, pasirinkimas1);
long result = db.insert(KlausimuLentele.TABLE_NAME, null, contentValues);
if (result == -1){
return false;
}else{
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME,null );
return data;
}
private void fillKlausimuLentele() {
Klausimai q1 = new Klausimai("Kelintais metais buvo išleista java proogramavimo kalba?", "1991", "1995", "1989", 1);
addQuestion(q1);
Klausimai q2 = new Klausimai("Ar destytojas pasigailės mūsų?", "Priklauso nuo darbo", "Priklauso nuo pingų", "Prklauso nuo nuotaikos", 1);
addQuestion(q2);
Klausimai q3 = new Klausimai("Kai sunervina žaidimas koks geriausias būdas iš jo išeiti?", "Alt+F4", "Quit To desktop", "Ištraukti maitinimo laida",1);
addQuestion(q3);
Klausimai q4 = new Klausimai("A is correct again", "A", "B", "C", 1);
addQuestion(q4);
Klausimai q5 = new Klausimai("B is correct agian", "A", "B", "C", 2);
addQuestion(q5);
}
private void addQuestion(Klausimai klausimai) {
ContentValues cv = new ContentValues();
cv.put(KlausimuLentele.COLUMN_QUESTION, klausimai.getKlausimas());
cv.put(KlausimuLentele.COLLUMN_OPTION1, klausimai.getPasirinkimas1());
cv.put(KlausimuLentele.COLLUMN_OPTION2, klausimai.getPasirinkimas2());
cv.put(KlausimuLentele.COLLUMN_OPTION3, klausimai.getPasirinkimas3());
cv.put(KlausimuLentele.COLLUMN_ANSWER_NR, klausimai.getAtsakymoNr());
db.insert(KlausimuLentele.TABLE_NAME, null, cv);
}
public List<Klausimai> getAllQuestions() {
List<Klausimai> klausimuSarasas = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
Klausimai klausimai = new Klausimai();
klausimai.setKlausimas(c.getString(c.getColumnIndex(KlausimuLentele.COLUMN_QUESTION)));
klausimai.setPasirinkimas1(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION1)));
klausimai.setPasirinkimas2(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION2)));
klausimai.setPasirinkimas3(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION3)));
klausimai.setAtsakymoNr(c.getInt(c.getColumnIndex(KlausimuLentele.COLLUMN_ANSWER_NR)));
klausimuSarasas.add(klausimai);
} while (c.moveToNext());
}
c.close();
return klausimuSarasas;
}
}
But i think the problem is in here because this is the form which crashes:
package com.example.laivumusis;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ViewListData extends AppCompatActivity {
KlausimynoDatabaseHelper myDB;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editlistview_layout);
ListView listView = (ListView) findViewById(R.id.listView);
myDB = new KlausimynoDatabaseHelper(this);
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0) {
Toast.makeText(ViewListData.this,"Database tuščias!",Toast.LENGTH_LONG).show();
}else{
while (data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.laivumusis, PID: 3859
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Your object seems to be null while converting to string. use the following to check if null:
if (obj !=null){
//store in database
}
I'm building an application for a barber shop and im on a part now where I am creating an appointment and saving the data from that appointment, however when I go to click add to create the appointment, the application crashes and I left with this error;
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 2 rows, 3 columns.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ie.app.barbershop, PID: 31270
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at ie.app.barbershop.TableControllerAppointments.read(TableControllerAppointments.java:46)
at ie.app.barbershop.Landing.readRecords(Landing.java:47)
at ie.app.barbershop.OnClickListenerCreateAppointment$1.onClick(OnClickListenerCreateAppointment.java:38)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I/Process: Sending signal. PID: 31270 SIG: 9
Application terminated.
Here is my class for TableControllerAppointments.java
package ie.app.barbershop;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class TableControllerAppointments extends DatabaseHandler {
public TableControllerAppointments(Context context) {
super(context);
}
public boolean create(ObjectAppointment objectAppointments) {
ContentValues values = new ContentValues();
values.put("fullname", objectAppointments.fullName);
values.put("contactno", objectAppointments.contactNumber);
SQLiteDatabase db = this.getWritableDatabase();
boolean createSuccessful = db.insert("appointments", null, values) > 0;
db.close();
return createSuccessful;
}
public List<ObjectAppointment> read() {
List<ObjectAppointment> recordsList = new ArrayList<>();
String sql = "SELECT * FROM Appointments ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
int contactNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex("contactno")));
ObjectAppointment objectAppointment = new ObjectAppointment();
objectAppointment.fullName = fullName;
objectAppointment.contactNumber = contactNumber;
recordsList.add(objectAppointment);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return recordsList;
}
public int count() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "SELECT * FROM appointments";
int recordCount = db.rawQuery(sql, null).getCount();
db.close();
return recordCount;
}
}
And here is my class for OnClickListenerCreateAppointment.java
package ie.app.barbershop;
import android.view.View;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class OnClickListenerCreateAppointment implements View.OnClickListener {
public ObjectAppointment objectAppointment;
#Override
public void onClick(View view){
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.appointment_input_form, null, false);
final EditText editTextFullName = formElementsView.findViewById(R.id.editTextFullName);
final EditText editTextContactNumber = formElementsView.findViewById(R.id.editTextContactNumber);
ObjectAppointment objectAppointment = new ObjectAppointment();
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Appointment")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String fullname = editTextFullName.getText().toString();
String contactno = editTextContactNumber.getText().toString();
((Landing) context).countRecords();
((Landing) context).readRecords();
dialog.cancel();
}
}).show();
boolean createSuccessful = new TableControllerAppointments(context).create(objectAppointment);
if(createSuccessful){
Toast.makeText(context, "Appointment Information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save appointment information", Toast.LENGTH_SHORT).show();
}
}
}
and this is my Landing.java class
package ie.app.barbershop;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.List;
public class Landing extends AppCompatActivity{
public Button buttonProducts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_landing);
countRecords();
buttonProducts = findViewById(R.id.buttonProducts);
Button buttonCreateAppointment = findViewById(R.id.buttonCreateAppointment);
buttonCreateAppointment.setOnClickListener(new OnClickListenerCreateAppointment());
buttonProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Landing.this, Products.class));
}
});
}
public void readRecords() {
LinearLayout linearLayoutRecords = findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<ObjectAppointment> appointments = new TableControllerAppointments(this).read();
if (appointments.size() > 0) {
for (ObjectAppointment obj : appointments) {
String fullName = obj.fullName;
int contactNumber = obj.contactNumber;
String textViewContents = fullName + " - " + contactNumber;
TextView textViewAppointmentItem= new TextView(this);
textViewAppointmentItem.setPadding(0, 10, 0, 10);
textViewAppointmentItem.setText(textViewContents);
textViewAppointmentItem.setTag(Integer.toString(contactNumber));
linearLayoutRecords.addView(textViewAppointmentItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
public void countRecords(){
int recordCount = new TableControllerAppointments(this).count();
TextView textViewRecordCount = findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
}
Database Handler Class
package ie.app.barbershop;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS students";
db.execSQL(sql);
onCreate(db);
}
}
The -1 is being returned from getColumnIndex meaning that the column firstname
doesn't exist in the cursor in the following line.
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
You create the table using :-
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
Where the columns are id fullname and contactno.
--
Fix
To fix this change to use :-
String fullName = cursor.getString(cursor.getColumnIndex("fullname"));
Additional
Better still define column and tables names as constants and always refer to them.
e.g.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public static final String TABLE_NAME = "appointments";
public static final String COL_ID = "id";
public static final String COl_FULLNAME = "fullname";
public static final String COL_CONTACTNO = "contactno";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME +
"( " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_FULLNAME + " TEXT, " +
COL_CONTACTNO + " NUMBER ) ";
db.execSQL(sql);
}
.... and so on
and later as one example :-
String fullName = cursor.getString(cursor.getColumnIndex(DatabaseHandler.COL_FULLNAME));
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
I keep on getting this error saying that the table in my database doesn't exist but the table was declared.
So, I have this class to create appointments into a database, which is:
package com.example.calendar;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.calendar.Appointment;
import static com.example.calendar.Constants.KEY_DATE;
import static com.example.calendar.Constants.KEY_DETAILS;
import static com.example.calendar.Constants.KEY_ID;
import static com.example.calendar.Constants.KEY_TIME;
import static com.example.calendar.Constants.KEY_TITLE;
import static com.example.calendar.Constants.TABLE_APP;
public class CreateAppointment extends Activity implements OnClickListener{
EditText titleTextBox, timeTextBox, detailsTextBox;
int[] dateSelected = new int[3];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
titleTextBox = (EditText) findViewById(R.id.apptTitle);
timeTextBox = (EditText) findViewById(R.id.apptTime);
detailsTextBox = (EditText) findViewById(R.id.apptDetails);
View createButton = (Button) findViewById(R.id.apptSave);
String dateToPass = null;
Bundle getExtraFromMain = getIntent().getExtras();
if(getExtraFromMain != null){
dateSelected = getExtraFromMain.getIntArray(dateToPass);
}
createButton.setOnClickListener(this);
}
private Cursor cursor(){
DBHandler appointment = new DBHandler(this);
SQLiteDatabase db = appointment.getReadableDatabase();
String[] getValueFrom = {KEY_DATE, KEY_TITLE, KEY_TIME, KEY_DETAILS};
Cursor cursor = db.query(TABLE_APP, getValueFrom, null, null, null, null, KEY_DATE + " ASC");
return cursor;
}
private void save(){
String getTime = timeTextBox.getText().toString();
String getTitle = titleTextBox.getText().toString();
String getDetails = detailsTextBox.getText().toString();
DBHandler appointment = new DBHandler(this);
SQLiteDatabase db = appointment.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, getTitle);
values.put(KEY_TIME, getTime);
values.put(KEY_DETAILS, getDetails);
values.put(KEY_DATE, dateSelected[0] + "/" + dateSelected[1] + "/" + dateSelected[2]);
db.insertOrThrow(TABLE_APP, null, values);
appointment.close();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.apptSave:
save();
finish();
break;
}
}
}
And, of course, my handler:
package com.example.calendar;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static com.example.calendar.Constants.KEY_DATE;
import static com.example.calendar.Constants.KEY_DETAILS;
import static com.example.calendar.Constants.KEY_ID;
import static com.example.calendar.Constants.KEY_TIME;
import static com.example.calendar.Constants.KEY_TITLE;
import static com.example.calendar.Constants.TABLE_APP;
public class DBHandler extends SQLiteOpenHelper {
//Variables needed
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "appts.db";// database name
public DBHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override//create table
public void onCreate(SQLiteDatabase db){
String CREATE_APPOINTMENTS_TABLE = "CREATE TABLE " + TABLE_APP + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_DATE + " TEXT NOT NULL,"
+ KEY_TITLE + " TEXT NOT NULL, " + KEY_TIME + " TEXT NOT NULL, " + KEY_DETAILS + " TEXT NOT NULL" + ");";
db.execSQL(CREATE_APPOINTMENTS_TABLE);
}
#Override//when upgraded, trigger
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_APP);//delete table from older version
onCreate(db);//create new table
}
}
And additionally, the interface where the table name was declared:
package com.example.calendar;
import android.provider.BaseColumns;
public interface Constants extends BaseColumns{
public static final String TABLE_APP = "appointments";// table name
public static final String KEY_ID = "id";
public static final String KEY_DATE = "date";
public static final String KEY_TITLE = "title";
public static final String KEY_TIME = "time";
public static final String KEY_DETAILS = "details";
}
When I hit the button on the Activity, Logcat gives me this:
03-24 02:18:28.134: E/AndroidRuntime(800): android.database.sqlite.SQLiteException: no such table: appointments: , while compiling: INSERT INTO appointments(time,title,date,details) VALUES (?,?,?,?)
03-24 02:18:28.134: E/AndroidRuntime(800): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
03-24 02:18:28.134: E/AndroidRuntime(800): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
03-24 02:18:28.134: E/AndroidRuntime(800): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)
03-24 02:18:28.134: E/AndroidRuntime(800): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1718)
03-24 02:18:28.134: E/AndroidRuntime(800): at android.database.sqlite.SQLiteDatabase.insertOrThrow(SQLiteDatabase.java:1617)
03-24 02:18:28.134: E/AndroidRuntime(800): at com.example.calendar.CreateAppointment.save(CreateAppointment.java:69)
03-24 02:18:28.134: E/AndroidRuntime(800): at com.example.calendar.CreateAppointment.onClick(CreateAppointment.java:80)
Note: lines 69 and 80 are:
69:
db.insertOrThrow(TABLE_APP, null, values);
80:
save();//from switch statement
Can someone please help me??
Your code look fine, so changing the DATABASE_VERSION = 1 to DATABASE_VERSION = 2 may do the trick.
The reason because the onCreate() and onUpgrade() run only once! Therefore if you did any change within them after calling them, the change will not take affect. So changing the VERSION of the database or clearing your application data in your device/emulator could trigger to run the onCreate() and onUpgrade() again.
So whenever you change anything within the onCreate() and onUpgrade() increase the Database version.
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.