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

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.

Related

App is getting crashed when I'm trying to delete Data from database and refreshing ListView

I'm learning android programming and trying to delete data from database using a button in custom ListView but, unfortunately, my App is getting crashed when I hit Yes On Alert DialogBox.
FenceActivity
public class FenceActivity extends AppCompatActivity {
List<Fence> fenceList;
SQLiteDatabase sqLiteDatabase;
ListView listViewFences;
FenceAdapter fenceAdapter;
DataBaseHelper dataBaseHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.savedfences);
listViewFences = findViewById(R.id.fencesListView);
fenceList = new ArrayList<>();
showFencesFromDatabase();
}
public void showFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
public void reloadFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
fenceList.clear();
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
}
ShowFencesFromDatabase method I'm using to get Data from the database.
FenceAdapter
public class FenceAdapter extends ArrayAdapter<Fence> {
Context context;
int listLayoutRes;
List<Fence> fenceList;
DataBaseHelper dataBaseHelper;
FenceActivity fenceActivity;
public FenceAdapter(Context context, int listLayoutRes, List<Fence> fenceList) {
super(context, listLayoutRes, fenceList);
this.context = context;
this.listLayoutRes = listLayoutRes;
this.fenceList = fenceList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_layout_fences, null);
}
final Fence fence = fenceList.get(position);
TextView textViewSno = convertView.findViewById(R.id.textViewSnoLabel);
TextView textViewLat = convertView.findViewById(R.id.textViewLatitudeValue);
TextView textViewLon = convertView.findViewById(R.id.textViewLongitudeValue);
TextView textViewRadi = convertView.findViewById(R.id.textViewRadiusValue);
textViewSno.setText(Integer.toString(fence.getSno()));
textViewLat.setText(String.valueOf(fence.getLat()));
textViewLon.setText(String.valueOf(fence.getLon()));
textViewRadi.setText(Integer.toString(fence.getRadius()));
Button buttonDel = convertView.findViewById(R.id.buttonDeleteFence);
buttonDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper = new DataBaseHelper(context);
fenceActivity = (FenceActivity)context;
dataBaseHelper.deleteDataById(fence);
fenceActivity.reloadFencesFromDatabase();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
return convertView;
}
DatabaseHelper Class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
public static final String DB_NAME = "FenceDatabase";
private static final String TABLE_NAME = "FenceData";
private static final String col1 = "Sno";
private static final String col2 = "Latitude";
private static final String col3 = "Longitude";
private static final String col4 = "Radius";
Context context;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + col1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + col2 + " REAL , " + col3 + " REAL , " + col4 + " INTEGER)";
sqLiteDatabase.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean addData(Double lat, Double lon, int radi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, lat);
contentValues.put(col3, lon);
contentValues.put(col4, radi);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
return true;
}
public Cursor getAllData() {
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
return cursor;
}
public void deleteDataById(Fence fence) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String sql = "DELETE FROM FenceData WHERE Sno = ?";
sqLiteDatabase.execSQL(sql, new Integer[]{fence.getSno()});
}
}
Fence class
public class Fence {
int radius,sno;
double lat,lon;
public Fence( int sno,double lat, double lon,int radius) {
this.radius = radius;
this.sno = sno;
this.lat = lat;
this.lon = lon;
}
public int getRadius() {
return radius;
}
public int getSno() {
return sno;
}
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
}
Errors
2019-06-30 19:06:08.658 22783-22875/com.abhishakkrmalviya.fencetest E/LB: fail to open file: No such file or directory
2019-06-30 19:06:11.473 22783-22783/com.abhishakkrmalviya.fencetest E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted
What steps should I take to make App work properly, I mean to delete data from the database?
Initialise dataBaseHelper = new DataBaseHelper(context); before invoking dataBaseHelper.deleteDataById();
The problem is within FenceAdapter.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper.deleteDataById();
fenceActivity.showFencesFromDatabase();
}
});
The problem is that dataBaseHelper is not initialized before its usege.
It can be solve by adding a line dataBaseHelper = new DataBaseHelper(context); at the end of adapter's constructor.

Android studio no such column SQL database

I do not understand why my note taking application keeps crashing. I click on a button to insert a note that shows in a listView using a SQLite database.
The error given is:
(1) no such column: TITLE
FATAL EXCEPTION: main
Unable to resume activity: android.database.sqlite.SQLiteException: no such column: TITLE (code 1 SQLITE_ERROR): , while compiling: SELECT ID, TITLE FROM note_table
located here in mainactivity.java:
cursor = database.query(table_name, columns, where, where_args, group_by, having, order_by);
Database:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "ITEM2";
public static final String DATE_COLUMN = "DATE";
SQLiteDatabase db = this.getWritableDatabase();
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" TITLE TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table notes_table");
onCreate(db);
}
Mainactivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayList<String> notes_list;
private ArrayAdapter adapter;
private DBOpenHelper helper;
private SQLiteDatabase database;
private TextView noNotesView;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Edit_notes.class);
startActivity(intent);
}
});
noNotesView = findViewById(R.id.empty_notes);
listView = (ListView) findViewById(R.id.listView);
notes_list = new ArrayList<>();
helper = new DBOpenHelper(this);
database = helper.getWritableDatabase();
}
private void ViewData(){
String table_name = "note_table";
String[] columns = {"ID", "TITLE"};
String where = null;
String where_args[] = null;
String group_by = null;
String having = null;
String order_by = null;
cursor = database.query(table_name, columns, where, where_args, group_by, having, order_by); // the error is here
String total_text = "total number of rows: " + cursor.getCount() + "\n";
cursor.moveToLast();
notes_list = new ArrayList<>();
adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,notes_list);
for(int i = 0; i < cursor.getCount(); i++) {
// total_text += c.getInt(0) + " " + c.getString(1) + "\n";
notes_list.add(cursor.getString(1));
listView.setAdapter(adapter);
cursor.moveToPrevious();
}
// noNotesView.setText(total_text);
}
private void hide_or_show() {
if (cursor.getCount() == 0) {
noNotesView.setVisibility(View.VISIBLE);
} else {
noNotesView.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.delete_all) {
Delete_all();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume()
{
super.onResume();
ViewData();
hide_or_show();
}
public void Delete_all() {
database.execSQL("delete from " + "note_table");
adapter.clear();
}
I don't understand why I get this error message since my column name is right. I have tried deleting and recompiling my application without success.
Your problem is with your database class's constructor:
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
Specifically the 1 in the final argument of super(). That's your database version, and is key to introducing changes to your database structure. You mentioned in your comments that TITLE was previously called ITEM1, on your device it is still called ITEM1 as your app is unaware that the database structure has changed.
You can fix this by introducing a version constant in your class like so:
private static final int DB_VERSION = 2;
And using this variable in your constructor:
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
Whenever you make any structural changes to your database, increment DB_VERSION and this will cause SQLiteOpenHelper to call its onUpgrade() method.

Delete A Row In customAdapter extends BaseAdapter using SQLite - Android

I am trying to get a row in my SQLite database to delete on button click. I was successful in getting a row to delete in the ListView, but every time when I try delete from sqlite app crashes.
dba.removeData(position);
mModel.remove(position);
notifyDataSetChanged();
That just delete the item in ListView and not the row in the database.
public class CustomAdapter extends BaseAdapter {
private int custom_adapter;
private Context context;
private ArrayList<Model> mModel;
DatabaseHelper dba = new DatabaseHelper(this.context);
public CustomAdapter(Context context, int custom_adapter, ArrayList<Model> mModel) {
this.context = context;
this.mModel = mModel;
this.custom_adapter = custom_adapter;
}
#Override
public int getCount() {
return mModel.size();
}
#Override
public Object getItem(int position) {
return mModel.get(position);
}
#Override
public long getItemId(int position) {
return mModel.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = View.inflate(context, R.layout.custom_adapter, null);
final TextView ID = (TextView) v.findViewById(R.id.textViewID);
TextView przejechane = (TextView) v.findViewById(R.id.textViewPrzejechane);
TextView spalone = (TextView) v.findViewById(R.id.textViewSpalanie);
TextView zuzytePaliwo = (TextView) v.findViewById(R.id.textViewUzytepaliwo);
final TextView dataView = (TextView) v.findViewById(R.id.textViewData);
final Button btnDelete = (Button) v.findViewById(R.id.btnDelete);
final ListView listView = (ListView) v.findViewById(R.id.listview);
ID.setText(String.valueOf( mModel.get(position).getId()));
przejechane.setText(String.valueOf( mModel.get(position).getAmount_km()));
spalone.setText(String.valueOf( mModel.get(position).getAvg()));
zuzytePaliwo.setText(String.valueOf( mModel.get(position).getAmount_fuel()));
dataView.setText(String.valueOf( mModel.get(position).getData()));
btnDelete.setTag(position);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dba.removeData(position);
mModel.remove(position);
notifyDataSetChanged();
}
});
return v;
}
here is my DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private SQLiteDatabase mDatabase;
public static final String DATABASE_NAME = "AvgFuel.db";
public static final String TABLE_NAME = "avgFuel_table";
public static final String ID = "ID";
public static final String AMOUNT_FUEL = "AMOUNT_FUEL";
public static final String AMOUNT_KM = "AMOUNT_KM";
public static final String AVG = "AVG";
public static final String DATA = "DATA";
private static final String SELECT_PEOPLE = "SELECT * FROM " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AMOUNT_FUEL + " REAL, " + AMOUNT_KM + " REAL, " + AVG + " REAL, " + DATA + " TEXT" + ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String amount_fuel, String amount_km, double avg){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AMOUNT_FUEL,amount_fuel);
contentValues.put(AMOUNT_KM,amount_km);
contentValues.put(AVG,avg);
contentValues.put(DATA,getNow());
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public void removeData(int id){
SQLiteDatabase db = this.getReadableDatabase();
db.delete(TABLE_NAME, ID + "=" + id , null);
db.close();
}
public ArrayList<Model> getModels() {
ArrayList<Model> model = new ArrayList<Model>();
mDatabase = this.getReadableDatabase();
Cursor cursor = mDatabase.rawQuery(SELECT_PEOPLE, null);
cursor.moveToNext();
for (int i = 0; i <cursor.getCount() ; i++) {
model.add(new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)));
cursor.moveToNext();
}
cursor.close();
mDatabase.close();
return model;
}
public Model getModel(int id){
mDatabase = this.getReadableDatabase();
String s = "SELECT * FROM" + TABLE_NAME + "WHERE " + ID + "=" + id;
Cursor cursor = mDatabase.rawQuery(s,null);
cursor.moveToFirst();
Model model = new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
cursor.close () ;
mDatabase.close () ;
return model ;
}
private String getNow(){
// set the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
I think the problem is dba creation. Here you just use this adapter context. This should be the context what you get from Activity.
DatabaseHelper dba = new DatabaseHelper(this.context);
Try to use this
public CustomAdapter(Context context, int custom_adapter, ArrayList<Model> mModel) {
this.context = context;
this.mModel = mModel;
this.custom_adapter = custom_adapter;
dba = new DatabaseHelper(context);
}
To get the actual position of recyclerView you can use getAdapterPosition(). Like this
dba.removeData(mModel.get(getAdapterPosition()).getId());
Hope this will help.
Try to change this ..mModel.get(position).getId()
dba.removeData(mModel.get(position).getId());

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.

cannot bind data from sqlliteData-base to simplecursoradaptor

I don´t know how to connect the data my array String [] station = {"København", "Grenaa", "Hanstholm"}; in my MyListActivity to the simpleCursorAdaptor
I have made a SQLitedatabase, a Helperclass and anActivityclass - but I get the error " java.lang.IllegalArgumentException: column 'København' does not exist". I have additional code - but this code should be sufficient I think.
Any help would really be appreciated.
public class MyListActivity extends ListActivity {
String [] station = {"København", "Grenaa", "Hanstholm"};
Cursor stations;
SQLiteDatabase db;
SimpleCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter dbaAdapter = new DBAdapter(this);
dbaAdapter.open();
Cursor stations = dbaAdapter.getStations();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,stations,station,new int [] {
android.R.id.text1
});
setListAdapter(cursorAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor) l.getItemAtPosition(position);
String value = station[(int)id];
Intent intent = new Intent();
intent.putExtra(TravelActivity.SELECTED_STATION_NAME, cursor.getString(cursor.getColumnIndexOrThrow("station")));
this.setResult(RESULT_OK,intent);
cursor.close();
finish();
}
#Override
protected void onDestroy() {
db.close();
}
}
public class MyHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "database";
String DESTINATION = "DESTINATION";
int version = 1;
public MyHelper(Context context) {
super(context, "travel.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String TRAVELS = ( "create table travels (_id integer primary key autoincrement, start text, slut text)");
String STATIONS = ( "create table stations (_id integer primary key autoincrement, start text)" );
db.execSQL(TRAVELS);
db.execSQL(STATIONS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS ");
onCreate(db);
}
}
public class DBAdapter {
MyHelper myHelper;
SQLiteDatabase db;
String TABLE_STATIONS = "stations";
String TABLE_TRAVELS = "travels";
String START = "start";
String SLUT = "slut";
String ID_COL = "_id";
Context context;
public static final int NUMBER_TRAVELS = 1;
public DBAdapter(Context context) {
this.context = context;
myHelper = new MyHelper(context);
}
public void open() {
db = myHelper.getWritableDatabase();
}
public void close() {
myHelper.close();
}
public Cursor getTravels() {
Cursor cursor = db.query(TABLE_TRAVELS,new String[]{ID_COL,START,SLUT},null,null,null,null,START);
return cursor;
}
public void saveTravels(String start, String slut) {
ContentValues values = new ContentValues();
values.put(START,start);
values.put(SLUT,slut);
db.insert(TABLE_TRAVELS,null,values);
}
public Cursor getStations() {
Cursor cursor = db.query(TABLE_STATIONS,new String[]{ID_COL,START},null,null,null,null,START);
return cursor;
}
public void saveStations(String start) {
ContentValues values = new ContentValues();
values.put(START,start);
db.insert(TABLE_TRAVELS,null,values);
}
}
The error is generated by your SimpleCursorAdapter constructor :
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,stations,station,new int [] {
android.R.id.text1
});
The 4td parameter is the column names, so a String array with START and/or SLUT values in your case.

Categories

Resources