Android SQLite Colunm not found error [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Im trying to store data from some editTexts on a local android database and then eventually show it on a listview, but right now Im getting an error that says a column doesnt exist, I was following a tutorial on android hive so some of the variable names might look weird, but everything should be accurate.
StackTrace
2038-12038/com.example.adrian.legioncheck_in E/SQLiteLog﹕ (1) table contacts has no column named Longitude
08-25 12:12:19.121 12038-12038/com.example.adrian.legioncheck_in E/SQLiteDatabase﹕ Error inserting Latitude=-85 Longitude=50 POnumber=255902
android.database.sqlite.SQLiteException: table contacts has no column named Longitude (code 1): , while compiling: INSERT INTO contacts(Latitude,Longitude,POnumber) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1523)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1395)
at com.example.adrian.legioncheck_in.DatabaseHandler.addContact(DatabaseHandler.java:67)
at com.example.adrian.legioncheck_in.MapsActivity.SaveAction(MapsActivity.java:67)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3850)
at android.view.View.performClick(View.java:4470)
at android.view.View$PerformClick.run(View.java:18593)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Database Handle.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "POnumber";
private static final String KEY_PH_NO = "Latitude";
private static final String KEY_LONG = "Longitude";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#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" + KEY_LONG + " TEXT" +")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
/* line 67 */ void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_LONG }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setPO(cursor.getString(1));
contact.setLat(cursor.getString(2));
contact.setLong(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
contact.java
public class Contact {
//private variables
int _id;
String _PO;
String _lat;
String _longi;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String PO, String _lat, String _longi){
this._id = id;
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// constructor
public Contact(String PO, String _lat, String _longi){
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getPO(){
return this._PO;
}
// setting name
public void setPO(String PO){
this._PO = PO;
}
// getting phone number
public String getLat(){
return this._lat;
}
// setting phone number
public void setLat(String lat){
this._lat = lat;
}
public String getLong()
{
return this._longi;
}
public void setLong(String longi)
{
this._longi = longi;
}
}
Button that saves data to database:
public void SaveAction(View view)
{
EditText po = (EditText)findViewById(R.id.POnumber);
String PO = po.getText().toString();
EditText textlat = (EditText)findViewById(R.id.textLat);
String LAT = textlat.getText().toString();
EditText textlong = (EditText)findViewById(R.id.textLong);
String LONG = textlong.getText().toString();
DatabaseHandler db = new DatabaseHandler(MapsActivity.this);
db.addContact(new Contact(PO,LAT,LONG));
// Reading all Data
Log.d("Reading: ", "Reading all inputs..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,PO number: " + cn.getPO() + " ,Latitude: " + cn.getLat() + " ,Longitude: " + cn.getLong();
// Writing Data to log
Log.d("Name: ", log);
}
}

KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")"
Add the missing , before KEY_LONG:
KEY_PH_NO + " TEXT," + KEY_LONG + " TEXT" +")"
Uninstall your app so the onCreate() is run again. See
When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more about that.

Related

ID won't save in long format in database Sqlite

I'm making an Android Note Taking app, which save a note and display it in list of notes. if you touch each note it show a title and details of it in another layout. i can save note and i can show them in list but my problem is when i try to use intent to show that specific note's title and details.
what is do is use intent.putExtra("ID",...) and get that intent and show the note's detail and title with use of its ID. but i get "android.database.CursorIndexOutOfBoundsException" error and app crash.
this is part of my Note class:
public class Note {
private String Title, Content, Date, Time;
private long ID;
Note(){}
Note(String Title,String Content,String Date,String Time){
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
Note(long ID,String Title,String Content,String Date,String Time) {
this.ID = ID;
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
this is my NoteDataBase:
public class NoteDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
//column name for database tables
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
public NoteDataBase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//create table
String query = "CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ID + " INT PRIMARY KEY," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion >= newVersion) {
return;
} else {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long addNote(Note note) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
long ID = db.insert(DATABASE_TABLE,"null",c);
//c.put(KEY_ID,ID);
Log.d("Inserted", "addNote: note with id number " + KEY_ID + " has been inserted");
return ID;
}
public Note getNote(long ID){
//Select * from DatabaseTable where id = 1
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor != null)
cursor.moveToFirst();
return new Note(cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4));
}
public List<Note> getNotes() {
SQLiteDatabase db = getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
// Select * from databaseTable
String query = "SELECT * FROM "+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setContent(cursor.getString(2));
note.setDate(cursor.getString(3));
note.setTime(cursor.getString(4));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
}
this is my DetailActivity :
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Intent intent = getIntent();
Long id = intent.getLongExtra("ID",0);
NoteDataBase db = new NoteDataBase(this);
Note note = db.getNote(id);
Toast.makeText(this, "Title is "+ note.getTitle(), Toast.LENGTH_SHORT).show();
my error is in lines of both my Intent in DetailActivity and getNote method of NoteDataBase.
By defining the column id of your table as:
INT PRIMARY KEY
it is not defined as AUTOINCREMENT, so in every row that you add to the table, the column id is null, because you don't provide any value for it.
The value that is returned by the method addNote(), when you insert a new row, is the value of the column rowid and not the column id.
You must define the column as:
INTEGER PRIMARY KEY
You can also add AUTOINCREMENT in the above definition, if you don't want any deleted ids to be reused.
After you make this change you must uninstall the app from the device, so that the db is deleted and rerun to recreate the db and the table.
Also in the method getNote(), first check with moveToFirst() if the query returned any row:
public Note getNote(long ID){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor.moveToFirst())
return new Note(
cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4)
);
else return null;
}

Android sqlite:could not execute method onclick

I'm trying to login using the database by using the id of the specific members.
But the app crashes with log error.
Following various other similar errors, I included "c1.movetoFirst();" and "c2.movetoFirst();". But still its not working.
The logcat error is:
FATAL EXCEPTION: main
Process: no.nordicsemi.android.nrftoolbox, PID: 13196
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5276)
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:911)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Caused by: java.lang.reflect.InvocationTargetException
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:432)
at android.database.AbstractWindowedCursor.checkPosition
at android.database.AbstractWindowedCursor.getInt
at no.nordicsemi.android.nrftoolbox.LoginActivity.login
The LoginActivity is :
public class LoginActivity extends AppCompatActivity {
TextView email;
TextView pass;
private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (TextView) findViewById(R.id.editText_mail);
pass = (TextView) findViewById(R.id.editText_pass);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
}
public void register(View v) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Register_Page.class);
startActivity(goToSecond);
}
public void login(View v) {
Cursor c1 = mydb.getEmail(email);
c1.moveToFirst();
Cursor c2 = mydb.getpass(pass);
c2.moveToFirst();
int id1=c1.getInt(0);
int id2=c2.getInt(0);
if (id1>0 & id2>0) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Profile.class);
startActivity(goToSecond);
} else
message(getApplicationContext(), "not valid user");
}
}
The myDbHelper is:
public class myDbAdapter extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_PASS = "password";
public static final String CONTACTS_COLUMN_DOB = "dateofbirth";
public static final String CONTACTS_COLUMN_GENDER = "gender";
public static final String CONTACTS_COLUMN_PHONE="phone";
public static final String CONTACTS_COLUMN_CITY="city";
public static final String CONTACTS_COLUMN_WALLET="wallet";
private HashMap hp;
public myDbAdapter(Context context) {
super(context, DATABASE_NAME , null, 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + CONTACTS_TABLE_NAME + "(" + CONTACTS_COLUMN_ID + " INTEGER PRIMARY KEY," + CONTACTS_COLUMN_NAME + " TEXT," + CONTACTS_COLUMN_EMAIL + " TEXT," + CONTACTS_COLUMN_PASS +" TEXT," + CONTACTS_COLUMN_DOB + " TEXT," + CONTACTS_COLUMN_GENDER + " TEXT," + CONTACTS_COLUMN_PHONE + " INTEGER," + CONTACTS_COLUMN_CITY + " TEXT,"+CONTACTS_COLUMN_WALLET + " INTEGER DEFAULT 0);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String email, String pass, String dob, String gender, String phone, String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
contentValues.put("dateofbirth", dob);
contentValues.put("gender", gender);
contentValues.put("phone", phone);
contentValues.put("city", city);
db.insert("contacts", null, contentValues);
return true;
}
//Cursor csr = no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.getAllRowsFromTable(db,"contacts",true‌​,null)
//no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.LogCursorData(csr);
public int updateWallet(String amount,Integer id)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("wallet",amount);
return(db.update("contacts",contentValues,"id = ? ",new String[] { Integer.toString(id)}));
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public Cursor getEmail(TextView email)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where email='"+email.getText().toString()+"'",null);
return cursor;
}
public Cursor getpass(TextView pass)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where password='"+pass.getText().toString()+"'",null);
return cursor;
}
}
Where is the error? And how can it be recitified?
You better check whether cursor has next before invoking movetoFirst as in
Cursor c1 = mydb.getEmail(email);
if(c1.getcount() > 0)
c1.moveToFirst();
and make sure, email id is already in database and check for case sensitive.

Android SQLite Table Creation Error

I have my code to create SQLite database, the code create database but does not create any table. I went through some of the similar errors that others had before, I couldn't find any error. Could anyone help me.
Here is my code
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "swahilComm.db";
public static final String COUNTRY_TABLE = "countries";
public static final String COUNTRY_ID = "id";
public static final String COUNTRY_NAME = "country";
public static final String PROVINCE_TABLE = "province";
public static final String PROVINCE_ID = "id";
public static final String PROVINCE_NAME = "province";
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operation", "Database Created...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROVINCE);
db.execSQL(CREATE_COUNTRY_TABLE);
Log.d("Database Operation", "Tables Created...");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone
db.execSQL("DROP TABLE IF EXISTS " + PROVINCE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + COUNTRY_TABLE);
// Create tables again
onCreate(db);
}
//Delete all data in the table
public void DeleteCountry() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COUNTRY_TABLE, null, null);
db.close(); // Closing database connection
}
//Delete all data in the Province table
public void DeleteProvice() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PROVINCE_TABLE, null, null);
db.close(); // Closing database connection
}
//Insert country records
public int insertCountry(Country country) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_ID, country.getId());
values.put(COUNTRY_NAME, country.getCountry());
// Inserting Row
long country_Id = db.insert(COUNTRY_TABLE, null, values);
db.close(); // Closing database connection
return (int) country_Id;
}
//Insert province records
public int insertProvince(Province province) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PROVINCE_ID, province.getId());
values.put(PROVINCE_NAME, province.getProvince());
// Inserting Row
long province_Id = db.insert(PROVINCE_NAME, null, values);
db.close(); // Closing database connection
return (int) province_Id;
}
//Retrieve all records and populate into List<Country>
//This method allow you to retrieve more fields/information into List.
public List<Country> getAllCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<Country> countryList = new ArrayList<Country>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(cursor.getString(cursor.getColumnIndex(COUNTRY_ID)));
country.setCountry(cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
countryList.add(country);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<Province>
//This method allow you to retrieve more fields/information into List.
public List<Province> getAll() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<Province> provinceList = new ArrayList<Province>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getString(cursor.getColumnIndex(PROVINCE_ID)));
province.setProvince(cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
provinceList.add(province);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
//Retrieve all records and populate into List<String>
public List<String> getAllStringCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<String> countryList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
countryList.add(i,cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<String>
public List<String> getAll_Simple() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<String> provinceList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
provinceList.add(i,cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
}
This is the the Activity Class
public class Register extends AppCompatActivity {
DBHelper repo = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
countries = getResources().getStringArray(R.array.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, countries);
autoCompleteTextView.setAdapter(adapter);
insertDummyData();
loadProvince_Simple();
}
// This class insert data
private void insertDummyData(){
repo.DeleteProvice();
int i = 1;
String[] provinces = {"Prince Edward Island", "Quebec", "Saskatchewan", "Yukon","Northwest Territories", "Ontario", "Nunavut", "Nova Scotia", "Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador"};
for(int j=0; j < provinces.length; j++) {
Province province = new Province();
province.setId(Integer.toString(i));
province.setProvince(provinces[j]);
repo.insertProvince(province);
i++;
}
}
//This is the arrayadapter binding method as you can see
private void loadProvince_Simple(){
ArrayAdapter<String> spinnerAdapter;
DBHelper db = new DBHelper(getApplicationContext());
List<String> provinces = db.getAll_Simple();
spinnerAdapter = new ArrayAdapter<String>(Register.this,
android.R.layout.simple_spinner_item, provinces);
prov_spinner.setAdapter(spinnerAdapter);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
Read my comments below:
// TRY TO REMOVE THE SPACE BETWEEN "TEXT" TO THE "(" IN THE LAST LINE OF BOTH STRINGS
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
// YOU WROTE "INTEGET"
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";

Database issue with SQLite

I have been working with a few different database examples.
Every example i am using to try to learn about SQLite databases i am
getting the exact same error. I have already tried to research this and cannot
find my exact error anywhere.
Thanks for any help below is the code and the error i am getting
DatabaseHandler db = new DatabaseHandler(this);
I am getting unreachable code.
in my Database Handler.java file i do have the public class Database Handler (one word).
Thanks again.
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
this is my Database Handler
package com.example.databasetutorial;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#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);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Thanks for your help
Unreachable code error tells you that that particular line can never be executed because there exists no control flow path to the code from the rest of the program. So the error is that the location where you are writing this statement is never reachable and that piece code would never be executed. This can be because of logical problems such as if you have statements written after the return statement inside a function, then none of those would be executed because the function would always return the value before those statements gets executed.
Hope this makes you understand the reason of the error.
Show more code if you want to more help.
Update
As I said in your MainActivity inside onCreateOptionsMenu function, put the return true; statement at the end of just before closing the parenthesis after Lod.d.. line. You are returning from the function before hand.

How to insert data in SQLite db in Android?

I'm implementing SQLite db in my android application i want retrieve data from JSON and store in into SQLite db .I saw one of the example of using SQLite but I'm using different column name wchi is store into SQLite db .
But when i run the app I'm getting Error like =
((1) table contacts has no column named cost ,
Error inserting phone_number=9533333333 cost=46456 name=Karthik ,
android.database.sqlite.SQLiteException: table contacts has no column named cost (code 1): , while compiling: INSERT INTO contacts(phone_number,cost,name) VALUES (?,?,?))
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_COST = "cost";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_COST + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_COST, contact._cost); // Contact Phone
values.put(KEY_PH_NO, contact._mobile); //Contact phone no
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_COST, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.set_id(Integer.parseInt(cursor.getString(0)));
contact.set_name(cursor.getString(1));
contact.set_cost(cursor.getString(2));
contact.set_mobile(cursor.getString(3));
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.get_name());
values.put(KEY_COST, contact.get_cost());
values.put(KEY_PH_NO, contact.get_mobile());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.get_id()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.get_id()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Change this line
private static final int DATABASE_VERSION = 1;
to this
private static final int DATABASE_VERSION = 2;
And check your work again.
Try clear your app data then rerun the app, you may have had a different column before and run the app once (meaning the create table would not be called again).

Categories

Resources