Populating SQLite database table with foreign key - java

I'm currently attempting to populate my SQLite database using Android studio. So far I can populate the book table but am unsure to why I cannot populate my chapter table. If I go to view my chapter table I get no output.
As far as I am aware it is due to the foreign key used in this table.
In my onCreate method have I done something incorrectly with the foreign key?
Below is my code.
Helper class
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "formularyApp.db";
public static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
//when called creates query
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String sqlBook = "CREATE TABLE book(id INTEGER PRIMARY KEY AUTOINCREMENT, bookName VARCHAR, bookAuthor VARCHAR);";
String sqlChapter = "CREATE TABLE chapter(id INTEGER PRIMARY KEY AUTOINCREMENT, chapterName VARCHAR, book_id INTEGER, FOREIGN KEY(book_id) REFERENCES book(id))";
sqLiteDatabase.execSQL(sqlBook);
sqLiteDatabase.execSQL(sqlChapter);
}
public boolean addChapter(String chapterName, Integer book_id){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("chapterName", chapterName);
contentValues.put("bookID", book_id);
db.insert("chapter", null, contentValues);
db.close();
return true;
}
public boolean addBook(String bookName, String bookAuthor){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("bookName", bookName);
contentValues.put("bookAuthor", bookAuthor);
db.insert("book", null, contentValues);
db.close();
return true;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sqlBook = "DROP TABLE IF EXISTS book";
String sqlChapter = "DROP TABLE IF EXISTS chapter";
sqLiteDatabase.execSQL(sqlBook);
sqLiteDatabase.execSQL(sqlChapter);
onCreate(sqLiteDatabase);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
DatabaseHelper db;
/** Called when the activity is created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
db.addBook("Tester Book 5", "Test author");
db.addChapter("The basics", 5);
Toast.makeText(this, "updated", Toast.LENGTH_SHORT).show();
viewPager = findViewById(R.id.viewPager);
IntroAdapter adapter = new IntroAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}

In your addChapter method you have a typo:
contentValues.put("bookID", book_id);
should be
contentValues.put("book_id", book_id);
You are using a wrong column name

Related

Why do I fail to save data in my application?

I am a student and started working on android studio recently. I don't know about it much. I am working on an application where I save the item name and its amount in the database and display toast message if data we entered is saved or not. problem is whenever I click on the save button my application crashes.
following is my DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Items.db";
public static final String TABLE_NAME = "item_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "ITEM";
public static final String COL_3 = "AMOUNT";
public DatabaseHelper(#Nullable 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," + "ITEM TEXT, AMOUNT TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,item);
contentValues.put(COL_3,item);
long result = db.insert(TABLE_NAME,null, contentValues);
if(result == -1){
return false;
}else {
return true;
}
}
}
following is my MainActivity class:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editItem, editAmount;
Button buttonSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editItem = (EditText)findViewById(R.id.item_field);
editAmount = (EditText)findViewById(R.id.amount_field);
buttonSave = (Button)findViewById(R.id.button_save);
AddData();
}
public void AddData(){
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editItem.getText().toString();
String amount = editAmount.getText().toString();
boolean insertData = myDb.addData(item, amount);
if(insertData == true){
Toast.makeText(MainActivity.this,"Amount is saved with Item detail", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this, "Error occurred : Detailed are not saved", Toast.LENGTH_LONG).show();
}
}
});
}
}
I will appreciate your help.
Thank you
It might be crashing because it's not creating the table:
String createTable = "CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + "ITEM TEXT, AMOUNT TEXT)";
A space is missing between table and its name:
String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEM TEXT, AMOUNT TEXT)";
You should also close the database after you get the data in db.insert but this only creates a warning:
long result = db.insert(TABLE_NAME,null, contentValues);
db.close();

TextView not populating data from sqlite

I am trying to create a bill template by populating data stored in SQLite. I know there is a way to do this using ListView as well. The app crashes when I run this Activity.
public class Ticket_generator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_table);
Context context;
context=this;
TableHelper datahelper= new TableHelper(context);
datahelper.insertData("Home foods","Veg Resturant","New Municipal Blog","abc compound","mumbai 400007","01/07/17","COUNTER","BILL NO.-123","Perticulars","Quantity","Rate","gst","06.56AM");
Cursor cr;
cr=datahelper.getInformation();
TextView tv;
tv=(TextView)findViewById(R.id._s1t1);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5, 5, 5, 5);
tv.setText(cr.getString(1));
}
}
This is the TableHelper.java
public class TableHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Ticketdb";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_TICKET = "tblticketdata";
public static final String CREATE_TABLE_TICKET = "CREATE TABLE IF NOT EXISTS " + TABLE_TICKET + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, s1t1 TEXT NULL,s1t2 TEXT NULL,s1t3 TEXT NULL,s1t4 TEXT NULL,s1t5 TEXT NULL,s2t1 TEXT NULL,s2t2 TEXT NULL,s2t3 TEXT NULL, s3t1 TEXT NULL,s3t2 TEXT NULL,s3t3 TEXT NULL,ft1 TEXT NULL,ft2 TEXT NULL)";
public static final String DELETE_TABLE_SERVICES = "DROP TABLE IF EXISTS " + TABLE_TICKET;
public TableHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TICKET);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DELETE_TABLE_SERVICES);
//Create tables again
onCreate(db);
}
public void insertData(String s1t1, String _s1t2, String _s1t3, String _s1t4, String _s1t5, String _s2t1, String _s2t2,
String _s2t3, String _s3t1, String _s3t2, String _s3t3, String _ft1, String _ft2) {
// Open the database for writing
SQLiteDatabase db = this.getWritableDatabase();
// Start the transaction.
db.beginTransaction();
ContentValues values;
try {
values = new ContentValues();
values.put("s1t1", s1t1);
values.put("s1t2", _s1t2);
values.put("s1t3", _s1t3);
values.put("s1t4", _s1t4);
values.put("s1t5", _s1t5);
values.put("s2t1", _s2t1);
values.put("s2t2", _s2t3);
values.put("s2t3", _s2t3);
values.put("s3t1", _s3t1);
values.put("s3t2", _s3t2);
values.put("s3t3", _s3t3);
values.put("ft1", _ft1);
values.put("ft2", _ft2);
// Insert Row
long i = db.insert(TABLE_TICKET, null, values);
Log.i("Insert", i + "");
// Insert into database successfully.
db.setTransactionSuccessful();
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}
public Cursor getInformation() {
SQLiteDatabase sq = this.getReadableDatabase();
String[] columns = {"s1t1", "s1t2", "s1t3", "s1t4", "s1t5", "s2t1", "s2t2", "s2t3", "s3t1", "s3t2", "s3t3", "ft1", "ft2"};
Cursor cr = sq.query(TABLE_TICKET, columns, null, null, null, null, null);
return cr;
}
}
You need to move your cursor for the first position, like this example:
public String getFirstResult(){
String firstResult;
TableHelper datahelper = new TableHelper(context);
Cursor cursor = datahelper.getInformation();
cursor.moveToFirst();
firstResult = cursor.getString(0);
return firstResult;
}

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>
}

Trying to make Android database for the first time using SQLite, my app keeps crashing [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
Ive been trying to create a simplistic database on Android that has a table that gets three values,one for id, one for event desc. and the other for time which is on string format. problem is that it crashes for no reason and i cant find why. here is MainActivity:
public class MainActivity extends ListActivity {
private static final int MENU_EDIT = Menu.FIRST+1;
private static final int MENU_REMOVE = Menu.FIRST+2;
ArrayList <String> Events = new ArrayList<String>();
ArrayList <Integer> ids = new ArrayList<Integer>();
ListView lview = (ListView)findViewById(R.id.listview);
DBHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// registerForContextMenu(getListView());
db = new DBHandler(this);
// db.addInfo(new Day_Info("stef", "123"));
loadList();
}
private void loadList() {
try{
Events.clear();
ids.clear();
for(Day_Info e:db.getAllInfo()){
Events.add(e.getEvents()+", "+e.getTime());
ids.add(e.getId());
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2,Events);
lview.setAdapter(adapter);
}
catch(Exception e){
Toast.makeText(this, "Problem Loading List", Toast.LENGTH_LONG).show();
}
}
AND HERE is my database class:
class DBHandler extends SQLiteOpenHelper {
private static final String TABLE_NAME = "INFO";
private static final String DATABASE_NAME = "Schedule";
private static final String EVENT_DB ="event";
private static final String TIME_DB = "time";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
//Log.d("Database", "Database created");
}
#Override
public void onCreate(SQLiteDatabase db) {
String TABLE_CREATION = "CREATE TABLE "+ TABLE_NAME +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, EVENT TEXT not null,TIME TEXT not null)";
db.execSQL(TABLE_CREATION);
Log.d("Database", "Tables created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
void addInfo(Day_Info info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(EVENT_DB, info.getEvents());
cv.put(TIME_DB, info.getTime());
db.insert(TABLE_NAME, null, cv);
db.close();
}
public ArrayList<Day_Info> getAllInfo(){
ArrayList<Day_Info> List = new ArrayList<Day_Info>();
String selectQuery = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Day_Info info= new Day_Info();
info.setId(Integer.parseInt(cursor.getString(0)));
info.setEvents(cursor.getString(1));
info.setTime(cursor.getString(2));
List.add(info);
}while(cursor.moveToNext());
cursor.close();
}
return List;
}
}
Your coloumn at position 0 is an integer type
`_id INTEGER PRIMARY KEY AUTOINCREMENT`
But you are trying to fetch it as string
info.setId(Integer.parseInt(cursor.getString(0)));
instead use
info.setId(cursor.getInt(0));
Without logcat, i think this is the error you are facing. if you show your logs i will help more to determine the issue
you also declare _id as integer on need to convert cursor position (0) into integer put cursor.getInt(0)

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