cannot bind data from sqlliteData-base to simplecursoradaptor - java

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.

Related

cannot populate my activity (DrinkActivity) from SQLite database

I don't know what am I missing that I cannot populate my DrinkActivity from my Database!
here is my SQLiteOpenHelper class :
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "starbuzz"; // the name of our database
private static final int DB_VERSION = 2; // the version of the database
StarbuzzDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateMyDatabase(db, 0, DB_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
private static void insertDrink(SQLiteDatabase db, String name, String description,
int resourceId) {
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 1) {
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte);
insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam",
R.drawable.cappuccino);
insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter);
}
if (oldVersion < 2) {
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;");
}
}
}
and the other activity (DrinkCategoryActivity) which leads to DrinkActivity is here :
public class DrinkCategoryActivity extends AppCompatActivity {
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
ListView listDrinks = findViewById(R.id.list_drinks);
try {
db = starbuzzDatabaseHelper.getReadableDatabase();
cursor = db.query("DRINK",
new String[]{"_id", "NAME"},
null, null, null, null, null);
SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"NAME"},
new int[]{android.R.id.text1},
0);
listDrinks.setAdapter(listAdapter);
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> listDrinks,
View itemView,
int position,
long id) {
//Pass the drink the user clicks on to DrinkActivity
Intent intent = new Intent(DrinkCategoryActivity.this,
DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINK_ID, (int) id);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
cursor.close();
db.close();
}
}
and finally here is DrinkActivity :
public class DrinkActivity extends Activity {
public static final String EXTRA_DRINK_ID = "drinkId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
int drinkId = Objects.requireNonNull(getIntent().getExtras()).getInt("EXTRA_DRINK_ID");
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query ("DRINK",
new String[] {"NAME", "DESCRIPTION", "IMAGE_RESOURCE_ID"},
"_id = ?",
new String[] {Integer.toString(drinkId)},
null, null,null);
if (cursor.moveToFirst()) {
//Get the drink details from the cursor
String nameText = cursor.getString(0);
String descriptionText = cursor.getString(1);
int photoId = cursor.getInt(2);
//Populate the drink name
TextView name = findViewById(R.id.name1);
name.setText(nameText);
//Populate the drink description
TextView description = findViewById(R.id.description1);
description.setText(descriptionText);
//Populate the drink image
ImageView photo = findViewById(R.id.photo1);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
}
cursor.close();
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Database unavailable", Toast.LENGTH_LONG).show();
}
}
}
First off the DATABASE_NAME should be name.db, you are missing the extention of the file.
Reference: https://developer.android.com/training/data-storage/sqlite
Another important thing is how to retrieve data from the intent, you should not use:
getIntent().getExtras()).getInt("EXTRA_DRINK_ID")
Instead, once you have the intent, you can directly extract the data in this way:
Intent intent = getIntent();
int extraId = intent.getExtraInt(DrinkActivity.EXTRA_DRINK_ID);

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.

Delete Both row of list items on recyclerView and SQLite database

I am a beginner at programming, I want to make a delete button on every items list on recyclerView. I got some references from stack overflow, and its work for the deleted item only at the activity (layout), but when i run the activity again the The selected item showed again.
I found some related articles on stackoverflow and make the method to delete from the SQLite. But my app crushed "unfortunetly app has stopped" every time I call the delete function.
I hope someone can help me to figure it out.
here is my databasehelper class
public class DatabaseHelperClass extends SQLiteOpenHelper {
Log cat Database
public static String log = "DatabaseHelper";
//Databse version
public static final int DATABASE_VERSION = 1;
//Database name
public static final String DATABSE_NAME = "dbPig";
//Tables Name
public static final String TABLE_PIGINFO = "tb_pigInfo";
//Common and PigInfo Column Names
public static final String KEY_ID = "id";
public static final String KEY_NAMA = "nama";
public static final String KEY_TANGGAL_PENDAFTARAN = "tanggal_pendaftaran";
//table create statement
//table pig Info
public static final String CREATE_TABLE_PIGINFO = "CREATE TABLE "
+ TABLE_PIGINFO + "(" + KEY_ID + " INTEGER," + KEY_NAMA
+ " TEXT," + KEY_TANGGAL_PENDAFTARAN
+ " TEXT" + ")";
public DatabaseHelperClass(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//creating requaired table
db.execSQL(CREATE_TABLE_PIGINFO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PIGINFO);
// create new tables
onCreate(db);
}
public void insertdata(String nama, String tanggal_pendaftaran) {
System.out.print("Tersimpan" + TABLE_PIGINFO);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAMA, nama);
contentValues.put(KEY_TANGGAL_PENDAFTARAN, tanggal_pendaftaran);
db.insert(TABLE_PIGINFO, null, contentValues);
}
public List<PigInfoTable> getdata() {
List<PigInfoTable> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_PIGINFO + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
PigInfoTable pigInfoTable = null;
while (cursor.moveToNext()) {
pigInfoTable = new PigInfoTable();
String nama = cursor.getString(cursor.getColumnIndexOrThrow("nama"));
String tanggal_pendaftaran = cursor.getString(cursor.getColumnIndexOrThrow("tanggal_pendaftaran"));
pigInfoTable.setNama(nama);
pigInfoTable.setTanggal_pendaftaran(tanggal_pendaftaran);
stringBuffer.append(pigInfoTable);
data.add(0, pigInfoTable);
}
for (PigInfoTable mo : data) {
Log.i("Hellomo", "" + mo.getNama());
}
return data;
}
public void delete(int position) {
SQLiteDatabase db = this.getWritableDatabase();
String table = TABLE_PIGINFO;
String whereClause = KEY_ID;
String [] whereArgs = new String[] {String.valueOf(position)};
db.delete (table, whereClause, whereArgs);
}
and here my adapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.Myholder> {
DatabaseHelperClass databaseHelper;
List <PigInfoTable> pigInfoTablesArrayList;
public RecycleAdapter(List <PigInfoTable> pigInfoTablesArrayList) {
this.pigInfoTablesArrayList = pigInfoTablesArrayList;
}
class Myholder extends RecyclerView.ViewHolder{
private TextView nama, tanggal_pendaftaran;
private Button delete;
public Myholder(View itemView) {
super(itemView);
nama = (TextView) itemView.findViewById(R.id.nama1);
tanggal_pendaftaran = (TextView) itemView.findViewById(R.id.tanggal1);
delete = (Button) itemView.findViewById(R.id.delete);
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itempigview,null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, final int position) {
PigInfoTable pigInfoTable= pigInfoTablesArrayList.get(position);
holder.nama.setText(pigInfoTable.getNama());
holder.tanggal_pendaftaran.setText(pigInfoTable.getTanggal_pendaftaran());
holder.itemView.setClickable(true);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return pigInfoTablesArrayList.size();
}
I am trying some other solution but the same error occurred which's
null object references on
Position
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
at com.example.newbreedy.RecycleAdapter$1.onClick(RecycleAdapter.java:66)
thank you
com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
because you have not initialized the reference of
DatabaseHelperClass databaseHelper;
So Add.
databaseHelper =new DatabaseHelperClass (context);
in your recycler adapter
In your code you are sending adapter position so in place of position send KEY_ID.
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyDataSetChanged();
First you have to initialize your DatabaseHelperClass in your adapter like this,
databaseHelper =new DatabaseHelperClass (context);
Than you need to call the delete function and inform the adapter about the removed item like this,
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());

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.

Error database not open

Hey I'm trying to insert data in the SQLite database, but everytime I try to insert the logcat shows the error. THe error ir shown on a service that gets the calllog data and insert in the DB.
Error:
02-15 17:07:51.658: ERROR/AndroidRuntime(25392): java.lang.IllegalStateException: database not open
And the error is in this line of the Service class:
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
Here is the service:
public class TheService extends Service {
private static final String TAG = "TheService";
private static final String LOG_TAG = "TheService";
private Handler handler = new Handler();
private SQLiteDatabase db;
class TheContentObserver extends ContentObserver {
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
db = DataHandlerDB.createDB(this);
registerContentObservers();
}
#Override
public void onDestroy(){
db.close();
}
#Override
public void onStart(Intent intent, int startid) {
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
int callTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = (null == cursor.getString(contactNameId) ? ""
: cursor.getString(contactNameId));
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
String callType = cursor.getString(callTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
values.put("type", callType);
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
cursor.close();
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new TheContentObserver(handler));
}
}
And here is the DataHandlerDB Class:
public class DataHandlerDB {
private static final String DATABASE_NAME = "mydb.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "table1";
protected static final String TABLE_NAME_2 = "table2";
protected String TAG = "DataHandlerDB";
//create the DB
public static SQLiteDatabase createDB(Context ctx) {
OpenHelper helper = new OpenHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
helper.onOpen(db);
db.close();
return db;
}
public static class OpenHelper extends SQLiteOpenHelper {
private final Context mContext;
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String[] sql = mContext.getString(R.string.ApplicationDatabase_OnCreate).split("\n");
db.beginTransaction();
try{
execMultipleSQL(db, sql);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e("Error creating tables and debug data", e.toString());
throw e;
} finally {
db.endTransaction();
}
}
private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
for(String s : sql){
if(s.trim().length() > 0){
db.execSQL(s);
}
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*Log.w("Application Database",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);*/
}
#Override
public void onOpen(SQLiteDatabase db){
super.onOpen(db);
}
}
}
Don't you want this code
if (!db.isOpen()) {
getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
to be:
if (!db.isOpen()) {
db = getApplicationContext().openOrCreateDatabase(
"/data/data/com.my_app/databases/mydb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
?
Also, in the function
public TheContentObserver(Handler h) {
super(h);
OpenHelper helper = new OpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
}
helper and db are local variables, not class members. This means that the database that you open here is not used for anything, anywhere.

Categories

Resources