Android Studio - Error while creating Table - Logcat - java

DatabaseHelperClass.java
This is the database helper class for creating the database in android. But it is not working as I see in the android logcat. It is unable to point location column in database. Please advise if I made any mistake in the below mention classes.
public class DatabaseHelperClass extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "metrolines.db";
public DatabaseHelperClass(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
/* CREATE CLASS */
db.execSQL(Station.CREATE_TABLE);
Log.d("Create Table", "Passed this step");
Insert_Station(new Station("Uttam Nagar East","West Delhi"));
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* DROP TABLE IF EXIST */
db.execSQL("DROP TABLE IF EXISTS " + Station.TABLE_NAME);
/* CREATE TABLES AGAIN */
onCreate(db);
}
public void Insert_Station(Station station) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Station.STATION_NAME, station.getD_Station());
contentValues.put(Station.STATION_LOCATION, station.getD_Location());
db.insert(Station.TABLE_NAME, null, contentValues);
db.close();
}
public List<Station> getStationList() {
List<Station> stationList = new ArrayList<Station>();
//StationList
String SELECT_QUERY = "SELECT * FROM " + Station.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.moveToFirst()) {
do {
Station station = new Station();
station.setD_Station(cursor.getString(1));
station.setD_Location(cursor.getString(2));
stationList.add(station);
} while (cursor.moveToNext());
}
return stationList;
}}
Station.java
public class Station {
public static final String TABLE_NAME = "STATION_TABLE";
public static final String STATION_NAME = "Station_name" ;
public static final String STATION_LOCATION = "Location_name" ;
private String D_Station;
private String D_Location;
//create table SQL Query
public static final String CREATE_TABLE =
"CREATE TABLE STATION_TABLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, Station_name TEXT, Location_name TEXT)";
public Station(){
}
public Station(String d_Station, String d_Location) {
D_Station = d_Station;
D_Location = d_Location;
}
public String getD_Station() {
return D_Station;
}
public void setD_Station(String d_Station) {
D_Station = d_Station;
}
public String getD_Location() {
return D_Location;
}
public void setD_Location(String d_Location) {
D_Location = d_Location;
}
}
MainActiviy.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelperClass db = new DatabaseHelperClass(this);
Log.d("Insert", "Inserting");
db.Insert_Station(new Station("Uttam Nagar East", "West Delhi"));
db.Insert_Station(new Station("Dwarka Sec 9", "West Delhi"));
db.Insert_Station(new Station("Rajiv Chowk", "Central Delhi"));
db.Insert_Station(new Station("Hauz Khas", "South Delhi"));
Logcat
2020-03-20 09:51:54.330 29987-29987/com.gauravbhagat.meg D/Insert: Inserting
2020-03-20 09:51:54.389 29987-29987/com.gauravbhagat.meg E/SQLiteLog: (1) table STATION_TABLE has no column named Location_name
2020-03-20 09:51:54.436 29987-29987/com.gauravbhagat.meg E/SQLiteDatabase: Error inserting Location_name=West Delhi Station_name=Uttam Nagar East
android.database.sqlite.SQLiteException: table STATION_TABLE has no column named Location_name (code 1 SQLITE_ERROR[1]): , while compiling: INSERT INTO STATION_TABLE(Location_name,Station_name) VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1229)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:703)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:2019)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1890)
at com.gauravbhagat.meg.SQliteDataBase.DatabaseHelperClass.Insert_Station(DatabaseHelperClass.java:48)
at com.gauravbhagat.meg.MainActivity.onCreate(MainActivity.java:64)
at android.app.Activity.performCreate(Activity.java:7340)
at android.app.Activity.performCreate(Activity.java:7331)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3106)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3269)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1960)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7094)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

Related

How to update sqlite record?

I coded this for my school project. It crashes when I call update method. error is given below :
E/SQLiteLog: (1) table userInfo has no column named userInfo E/SqDb:
Err ins ...
android.database.sqlite.SQLiteException: table userInfo has no column named userInfo (code 1): , while compiling: INSERT INTO
userInfo(password,userInfo) VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:921)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:532)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1570)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1427)
at com.example.prabuddhaabisheka.mock.DBHelper.addInfo(DBHelper.java:46)
at com.example.prabuddhaabisheka.mock.Home$2.onClick(Home.java:59)
at android.view.View.performClick(View.java:5232)
at android.view.View$PerformClick.run(View.java:21289)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
public class EditProfile extends AppCompatActivity {
Button search, edit, delete;
EditText name, password, dob;
RadioButton male,female;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
search = findViewById(R.id.buttonSerach);
edit = findViewById(R.id.buttonEdit);
delete = findViewById(R.id.Delete);
name = findViewById(R.id.editTextName);
password = findViewById(R.id.editTextPassword);
dob = findViewById(R.id.editTextDOB);
male = (RadioButton) findViewById(R.id.radioButtonMale);
female = findViewById(R.id.radioButtonFemale);
}
public void search(View view){
DBHelper dbHelper = new DBHelper(this);
String givenName = name.getText().toString();
ArrayList<userInfo> user ;
user = dbHelper.readAllInfo();
if(!user.isEmpty()) {
for (userInfo u : user) {
if (givenName.equals(u.name)) {
password.setText(u.password);
dob.setText(u.dob);
if ("Male".equals(u.gender)) {
male.setChecked(true);
female.setChecked(false);
} else {
male.setChecked(false);
female.setChecked(true);
}
}
}
}
}
public void update(View view){
DBHelper dbHelper = new DBHelper(this);
String givenName = name.getText().toString();
int id = 0;
ArrayList<userInfo> user;
user = dbHelper.readAllInfo();
if(!user.isEmpty()) {
for (userInfo u : user) {
if (givenName.equals(u.name)) {
id = u.id;
}
}
}
String givenDob = dob.getText().toString();
String givenPassword = name.getText().toString();
String gender;
if (male.isChecked()){
gender = "Male";
}
else{
gender = "Female";
}
boolean updated = dbHelper.updateInfo(id,givenName,givenPassword,givenDob,gender);
if (updated) {
Toast toast = Toast.makeText(this, "Updated", Toast.LENGTH_SHORT);
toast.show();
}
else{
Toast toast = Toast.makeText(this, "Update failed !", Toast.LENGTH_SHORT);
toast.show();
}
}
}
DBHelper class is also given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, UserProfile.Users.DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE "+ UserProfile.Users.TABLE_NAME +" ("+
UserProfile.Users._ID + "INTEGER PRIMARY KEY," +
UserProfile.Users.TABLE_COLUMN_USERNAME + "TEXT,"+
UserProfile.Users.TABLE_COLUMN_PASSWORD + "TEXT," +
UserProfile.Users.TABLE_COLUMN_DOB + "TEXT,"+
UserProfile.Users.TABLE_COLUMN_GENDER + "TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addInfo( ContentValues values ){
SQLiteDatabase db = getWritableDatabase();
long added = db.insert(UserProfile.Users.TABLE_NAME,null,value);
return (added != 0);
}
public boolean updateInfo(int id, String name, String password, String dob, String gender ){
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.Users.TABLE_COLUMN_USERNAME,name);
values.put(UserProfile.Users.TABLE_COLUMN_PASSWORD,password);
values.put(UserProfile.Users.TABLE_COLUMN_DOB,dob);
values.put(UserProfile.Users.TABLE_COLUMN_GENDER,gender);
String where = UserProfile.Users._ID + " =";
String[] arg = {Integer.toString(id)};
int row = db.update(UserProfile.Users.TABLE_NAME, values, where, arg);
return (row !=0 );
}
public ArrayList readAllInfo(){
SQLiteDatabase db = getReadableDatabase();
String[] columns = {
UserProfile.Users._ID,
UserProfile.Users.TABLE_COLUMN_USERNAME,
UserProfile.Users.TABLE_COLUMN_PASSWORD,
UserProfile.Users.TABLE_COLUMN_GENDER,
UserProfile.Users.TABLE_COLUMN_DOB
};
Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,columns,null,null,null
,null,null);
ArrayList<userInfo> users = new ArrayList<>();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_USERNAME));
String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_DOB));
String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_GENDER));
String password = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_PASSWORD));
userInfo user = new userInfo(id,name,password,dob,gender);
users.add(user);
}
cursor.close();
return users;
}
public ArrayList readAllInfo(int id){
SQLiteDatabase db = getReadableDatabase();
String[] columns = {
UserProfile.Users._ID,
UserProfile.Users.TABLE_COLUMN_USERNAME,
UserProfile.Users.TABLE_COLUMN_PASSWORD,
UserProfile.Users.TABLE_COLUMN_GENDER,
UserProfile.Users.TABLE_COLUMN_DOB
};
String where = UserProfile.Users._ID + " =?";
String[] arg = {Integer.toString(id)};
Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,columns,where,arg,null
,null,null);
ArrayList<userInfo> users = new ArrayList<>();
while (cursor.moveToNext()){
//int ID = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_USERNAME));
String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_DOB));
String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_GENDER));
String password = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_PASSWORD));
userInfo user = new userInfo(id,name,password,dob,gender);
users.add(user);
}
cursor.close();
return users;
}
public void deleteUser(int ID){
SQLiteDatabase db = getReadableDatabase();
String where = UserProfile.Users._ID + " =?";
String[] arg = {Integer.toString(ID)};
int count = db.delete(UserProfile.Users.TABLE_NAME,where,arg);
}
}
The error is clear:
...
.sqlite.SQLiteException: table userInfo has no column named userInfo (code 1):
, while compiling: INSERT INTO userInfo(password,userInfo) VALUES (?,?) at
...
When you are invoking the method
public boolean addInfo( ContentValues values )
You are passing as a content value, a value named with the same name as the table. You have to check two things:
Where you are using UserProfile.Users.TABLE_NAME (that I suppose it has the value userInfo
Check what you are passing to content values used by addInfo method.
Hope it helps.
If you are trying to add new row to the table after it has been created, try to remove the table and create it again.
to remove
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
after this, you can recreate the table again
You have to increase your version of database after then do changes in On-upgrade method of sqlite.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
db.execSQL("DROP TABLE IF EXISTS " +......);
db.execSQL("CREATE TABLE IF NOT EXISTS " +......);
insertColumnIfNotAvailableinTable(SQLiteDatabase db, String tableName, String columnName, String columnType);
}
}

Strange error with SQLite extending SQLiteOpenHelper

I've created a class which extends SQLiteOpenHelper class and trying to create a DB and insert a dummy record when my Android app launches.
However I get an error 'table gallery has no column named title'.
No error being thrown for the other columns and they're all created in the same way.
The error:
12-19 14:24:30.401 4801-4807/? E/art: Failed sending reply to debugger: Broken pipe
12-19 14:24:30.808 4801-4801/? E/SQLiteLog: (1) table gallery has no column named title
12-19 14:24:30.810 4801-4801/? E/SQLiteDatabase: Error inserting title=First pic artist=James Liscombe rank=3 year=1992
android.database.sqlite.SQLiteException: table gallery has no column named title (code 1): , while compiling: INSERT INTO gallery(title,artist,rank,year) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
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:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.jamesliscombe.cet325assignment.DBHandler.addPicture(DBHandler.java:59)
at com.example.jamesliscombe.cet325assignment.Home.onCreate(Home.java:35)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The class I've created which extends SQLiteOpenHelper:
public class DBHandler extends SQLiteOpenHelper {
//DB Info
private static final int DB_VERSION = 2;
private static final String DB_NAME = "louvre";
private static final String TABLE_NAME = "gallery";
//Table column names
private static final String KEY_ID = "id";
private static final String KEY_RANK = "rank";
private static final String KEY_ARTIST = "artist";
private static final String KEY_TITLE = "title";
private static final String KEY_YEAR = "year";
public DBHandler(Context context) {
super(context, DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_GALLERY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + "INTEGER PRIMARY KEY," + KEY_RANK + "INTEGER,"
+ KEY_ARTIST + "TEXT," + KEY_TITLE + "TEXT," + KEY_YEAR + "TEXT" + ")";
db.execSQL(CREATE_GALLERY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//Create table again
onCreate(db);
}
//Adding a new gallery record
public void addPicture(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RANK, picture.getRank());
values.put(KEY_ARTIST, picture.getArtist());
values.put(KEY_TITLE, picture.getTitle());
values.put(KEY_YEAR, picture.getYear());
//Insert row
db.insert(TABLE_NAME, null, values);
//Close db connection
db.close();
}
//Reading a single record
public Picture getPicture(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] {
KEY_ID,KEY_RANK,KEY_ARTIST,KEY_TITLE,KEY_YEAR
},KEY_ID + "=?", new String[] {
String.valueOf(id) }, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Picture contact = new Picture(Integer.parseInt(cursor.getString(0)),Integer.parseInt(cursor.getString(1)),cursor.getString(2),cursor.getString(3), cursor.getString(4));
return contact;
}
//Reading all records
public List<Picture> getAllPictures() {
List<Picture> galleryList = new ArrayList<Picture>();
//Select all query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Loop through all rows and add to galleryList.
if(cursor.moveToFirst()) {
do {
Picture picture = new Picture();
picture.setId(Integer.parseInt(cursor.getString(0)));
picture.setRank(Integer.parseInt(cursor.getString(1)));
picture.setArtist(cursor.getString(2));
picture.setTitle(cursor.getString(3));
picture.setYear(cursor.getString(4));
galleryList.add(picture);
} while (cursor.moveToNext());
}
return galleryList;
}
//Get total number of records
public int getGallerySize() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
//Update gallery items
public int updateGallery(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RANK, picture.getRank());
values.put(KEY_ARTIST, picture.getArtist());
values.put(KEY_TITLE, picture.getTitle());
values.put(KEY_YEAR, picture.getYear());
return db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(picture.getId())});
}
//Delete a gallery record
public void deletePicture(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[] {String.valueOf(picture.getId())});
db.close();
}
}
Where I'm using the class and inserting a dummy record:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Create our DB
DBHandler db = new DBHandler(this);
//Insert some test data into our db
db.addPicture(new Picture(1,3,"James","First pic","1992"));
You already have a database installed in your device that does not contain title column so when your try to add the dummy data with the value for Title column, you get the error.
This can be fixed by deleting the old already created database and then running your application again so that new database is created.
To delete the existing database, go to Android Device Monitor -> data -> data and then search for your app's package name. Click on your app's package name and then delete the database folder inside it and then run your app again.

Android. SQLite Exception: no such column _ingredients [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 5 years ago.
Im having some troubles trying to get the info stored in my database and showing it in a ListView.
When I start the application it crashes.
My MainActivity:
private ListViewAdapter adapter;
private ArrayList<ListItem> itemList;
private ListView list;
private DatabaseAdapter receptDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setupButton();
setupListView();
setupDatabase();
addObject();
}
private void setupDatabase() {
receptDB = new DatabaseAdapter(this);
receptDB.open();
refreshListView();
}
private void setupButton() {
Button addItemButton = (Button) findViewById(R.id.addItemButton);
addItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked();
}
});
}
private void buttonClicked() {
//get EditText
Intent newItemIntent = new Intent(List_Page.this, Add_Object.class);
startActivity(newItemIntent);
finish();
}
private void setupListView() {
itemList = new ArrayList<ListItem>();
adapter = new ListViewAdapter(List_Page.this, itemList);
list = (ListView) findViewById(R.id.listItem);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return true;
}
});
View header = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_list_item, null);
list.addHeaderView(header);
list.setAdapter(adapter);
}
private void addObject(){
Intent intent = getIntent();
if (intent.hasExtra(Constants.KEY_RECEPT_NAME)) {
String name = intent.getExtras().getString(Constants.KEY_RECEPT_NAME);
String kategory = intent.getExtras().getString(Constants.KEY_KATEGORY);
String ingredients = intent.getExtras().getString(Constants.KEY_INGREDIENTS);
String directions = intent.getExtras().getString(Constants.KEY_DIRECTIONS);
Bitmap image = (Bitmap) intent.getParcelableExtra(Constants.KEY_IMAGE);
//byte[] imageBytes = getBytes(image);
ListItem newObject = new ListItem(name,kategory,ingredients,directions, image);
//itemList.add(newObject);
receptDB.insertReceptItem(newObject);
refreshListView();
}
}
private void refreshListView() {
Cursor cursor = receptDB.getAllRows();
String[] fromFieldNames = new String[] {DatabaseAdapter.KEY_NAME, DatabaseAdapter.KEY_KATEGORY};
int[] toViewIDs = new int[] {R.id.receptName, R.id.kategory};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.activity_list_item, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listItem);
myList.setAdapter(myCursorAdapter);
}
#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;
}
#Override
protected void onDestroy() {
super.onDestroy();
receptDB.close();
}
Database:
public class DatabaseAdapter {
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "receptlist.db";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_TABLE = "receptlistitems";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KATEGORY = "kategory";
public static final String KEY_INGREDIENTS = "ingredients";
public static final String KEY_DIRECTIONS = "directions";
//bitmap?
public static final int COLUMN_NAME_INDEX = 1;
public static final int COLUMN_KATEGORY_INDEX = 2;
public static final int COLUMN_INGREDIENTS_INDEX = 3;
public static final int COLUMN_DIRECTIONS_INDEX = 4;
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_KATEGORY, KEY_INGREDIENTS, KEY_DIRECTIONS};
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null, " + KEY_KATEGORY
+ " text, " + KEY_INGREDIENTS
+ " text not null, " + KEY_DIRECTIONS
+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DatabaseAdapter(Context context) {
this.context = context;
DBHelper = new DatabaseHelper(context);
}
public DatabaseAdapter open(){
db = DBHelper.getWritableDatabase();
return this;
}
public void close(){
DBHelper.close();
}
//Neue Liste von Daten in Datenbank
public long insertReceptItem(ListItem item) {
ContentValues itemValues = new ContentValues();
itemValues.put(KEY_NAME, item.getName());
itemValues.put(KEY_KATEGORY,item.getKategory());
itemValues.put(KEY_INGREDIENTS, item.getIngredients());
itemValues.put(KEY_DIRECTIONS, item.getDirection());
//Speichern in die Datenbank
return db.insert(DATABASE_TABLE, null, itemValues);
}
//Löschen eines Items durch den primary Key
public boolean deleteItem(long itemID){
String where = KEY_ID + "=" + itemID;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ID);
if (c.moveToFirst()) {
do {
deleteItem(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
//Zurückgeben aller Daten in der Datenbank
public Cursor getAllRows(){
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null,null,null,null,null);
if (c != null) c.moveToFirst();
return c;
}
//Auf bestimmte Reihe zugreifen
public Cursor getRow(long rowId){
String where = KEY_ID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null,null,null,null,null);
if (c != null) c.moveToFirst();
return c;
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Logcat:
08-12 16:41:11.161 20386-20386/de.ur.mi.android.excercises.starter E/SQLiteLog: (1) no such column: ingredients
08-12 16:41:11.163 20386-20386/de.ur.mi.android.excercises.starter D/AndroidRuntime: Shutting down VM
08-12 16:41:11.164 20386-20386/de.ur.mi.android.excercises.starter E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.ur.mi.android.excercises.starter, PID: 20386
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ur.mi.android.excercises.starter/de.ur.mi.android.excercises.starter.List_Page}: android.database.sqlite.SQLiteException: no such column: ingredients (code 1): , while compiling: SELECT DISTINCT _id, name, kategory, ingredients, directions FROM receptlistitems
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.database.sqlite.SQLiteException: no such column: ingredients (code 1): , while compiling: SELECT DISTINCT _id, name, kategory, ingredients, directions FROM receptlistitems
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:895)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:506)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1165)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1036)
at de.ur.mi.android.excercises.starter.DatabaseAdapter.getAllRows(DatabaseAdapter.java:96)
at de.ur.mi.android.excercises.starter.List_Page.refreshListView(List_Page.java:109)
at de.ur.mi.android.excercises.starter.List_Page.setupDatabase(List_Page.java:51)
at de.ur.mi.android.excercises.starter.List_Page.onCreate(List_Page.java:42)
at android.app.Activity.performCreate(Activity.java:6720)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:241) 
at android.app.ActivityThread.main(ActivityThread.java:6274) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Thanks in advance!
If you change anything in the database schema (like adding a column), you have to increase the Database version in SQLiteOpenHelper. If you increase the value of the version you will get a callback to onUpgrade and you have to handle that database change there.
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION); // increased version
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Either add the column, or drop and create the table again.
}
}
Or the simple solution is to uninstall and reinstall the app.

Cant insert values in my sqlite database

i am very new to databases so i was looking at some guides online and started to try making my own database. For some reason my add method isnt working and i cant figure out why
This is my database class
public class DBHandler extends SQLiteOpenHelper{
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "DictionaryInfo";
// Contacts table name
private static final String TABLE_WORDS = "Words";
// Shops Table Columns names
private static final String KEY_ID ="id";
private static final String KEY_WORD = "word";
private static final String KEY_MEANING = "meaning";
private static final String CREATE_WORDS_TABLE = "CREATE TABLE " + TABLE_WORDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_WORD + " TEXT," + KEY_MEANING + " TEXT " + ")";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_WORDS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORDS);
onCreate(db);
}
public void addWord(Word word){
SQLiteDatabase db = this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID,word.getId());
values.put(KEY_WORD,word.getWord());
values.put(KEY_MEANING,word.getMeaning());
db.insert(TABLE_WORDS,null,values);
db.close();
}
public Word getWord(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WORDS,null,KEY_ID + " = ?",new String[]{String.valueOf(id)},null,null,null);
if (cursor != null)
cursor.moveToFirst();
Word word = new Word(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2));
return word;
}
}
This is my "word" class
public class Word {
int _id;
String word;
String meaning;
public Word(int id,String word, String meaning)
{
this._id = id;
this.word = word;
this.meaning = meaning;
}
public int getId() {
return this._id;
}
public void setId(int id) {
this._id = id;
}
public String getMeaning() {
return this.meaning;
}
public void setMeaning(String meaning) {
this.meaning = meaning;
}
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
}
This is my mainActivity
public class MainActivity extends AppCompatActivity {
TextView tv1;
TextView tv2;
TextView tv3;
TextView tv4;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
tv2 = (TextView)findViewById(R.id.tv2);
tv3 = (TextView)findViewById(R.id.tv3);
tv4 = (TextView)findViewById(R.id.tv4);
btn1 = (Button)findViewById(R.id.btn1);
DBHandler db = new DBHandler(this);
db.addWord(new Word(1,"abc","def"));
Word word = db.getWord(1);
tv1.setText(word.getWord());
tv2.setText(word.getMeaning());
}
}
I tried pulling out the values out of the database and insert them into a textview to check if its working but by the logcat i can obviously see that its caused somewhere in the insert process.
My logcat
com.example.android.psydictionary E/SQLiteLog: (1555) abort at 10 in [INSERT INTO Words(meaning,word,id) VALUES (?,?,?)]: UNIQUE constraint failed: Words.id
11-19 12:34:44.875 17853-17853/com.example.android.psydictionary E/SQLiteDatabase: Error inserting meaning=def word=abc id=1
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: Words.id (code 1555)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:784)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.android.psydictionary.DBHandler.addWord(DBHandler.java:51)
at com.example.android.psydictionary.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
UNIQUE constraint failed says what the problem is. You have a UNIQUE constraint on a column (meaning,words,id) and try to INSERT the same value twice in that column.
It is most likely the id that fails. Maybe you can just leave it and it gets calculated during insert. Otherwise, check your testdata.

android-studio: using SQLite class correct

I'm trying to use a SQLite Class in Android Studio outside the class. My error is:
Error:(42, 51) error: incompatible types: bluetooth cannot be converted to Context
"Bluetooth" is my calling class, I wan't receive some strings and write them to a SQLite DB.
How can I use the class correctly?
I try this: Sqlite database can not be create , but no luck. I don't understand the problem. :-/
Thanks for any help.
Here's my code:
DatabaseHelper.java:
public class DatabaseHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "aprs";
private final Context context;
private SQLiteDatabase database;
private DBHelper helper;
private class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_POS_TABLE = "CREATE TABLE pos ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"call TEXT, " +
"time TEXT )";
// create books table
db.execSQL(CREATE_POS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older books table if existed
db.execSQL("DROP TABLE IF EXISTS books");
// create fresh books table
this.onCreate(db);
}
}
public DatabaseHelper(Context c) {
context = c;
}
public DatabaseHelper openDB(){
helper = new DBHelper(context);
database = helper.getWritableDatabase();
return this;
}
public void addPos(String call, String time) {
ContentValues values = new ContentValues();
values.put("call", call);
values.put("time", time);
database.insert("pos",null, values);
Log.e("DB", "written");
database.close();
}
public void getAllPos() {
// 1. build the query
String query = "SELECT * FROM pos;";
// 2. get reference to writable DB
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Log.d("db", cursor.toString());
} while (cursor.moveToNext());
}
}
}
And this is bluetooth.java, my calling class:
public class bluetooth extends Thread {
<snip>
public void convertString() {
DatabaseHelper entry = new DatabaseHelper(this);
entry.addPos("text","test");
}
<snap>
}

Categories

Resources