android-studio: using SQLite class correct - java

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

Related

Populating SQLite database table with foreign key

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

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

Is it the correct way to initialize SQLite in MainActivity?

Im working on android studio and i encountered a problem, I cant initialize my sqlite instance in my DataHandler class but I can initialize it in my MainActivity class.
Example:
MainActivity class:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//valid
private SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("Database", Context.MODE_PRIVATE , null); //...
in datahandler class:
public class DataHandler {
public static String[] names,dates;
//invalid: cannot resolve method
SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("HMDB", Context.MODE_PRIVATE , null);
so, i did this
in main activity:
public SQLiteDatabase getSqLiteDatabase() {
return sqLiteDatabase;
}
in datahandler:
MainActivity mainActivity;
SQLiteDatabase sqLiteDatabase = mainActivity.getSqLiteDatabase();
is this the correct way? is there any better method? sry if hard to understand
Is this the correct way?
Did it throws any errors when project is running ?
This is how I normally do in DatabaseHandler (just sharing)
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DATA.db";
public static final String TABLE_NAME = "TITLE";
public static final String COL0 = "ID";
public static final String COL1 = "TODO";
public static final String COL2 = "DETAIL";
public DatabaseHandler(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, TODO TEXT, DETAIL TEXT)";
db.execSQL(createTable); }
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop if database is exists" + TABLE_NAME);
onCreate(db);
}
}
In MainActivity, declare this line
DatabaseHandler db;
In onCreate method, initialize DatabaseHandler
db = new DatabaseHandler(this);
When you want to use SQLite database, make sure you have this line
SQLiteDatabase db = this.getWritableDatabase();
The best approach is to use Singleton Pattern as described here
https://github.com/codepath/android_guides/wiki/Local-Databases-with-SQLiteOpenHelper
public class PostsDatabaseHelper extends SQLiteOpenHelper {
private static PostsDatabaseHelper sInstance;
// ...
public static synchronized PostsDatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (sInstance == null) {
sInstance = new PostsDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
/**
* Constructor should be private to prevent direct instantiation.
* Make a call to the static method "getInstance()" instead.
*/
private PostsDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
And in your MainActivity use it like
// In any activity just pass the context and use the singleton method
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
// or
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(context);
// or
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(getActivity());
// Do something with data via Cursor and
helper.close();
This approach perfect suits to get access to the database from different places of you app like Service, Fragment and etc...

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)

Table is not found in SQLiteDatabase

I am facing this strange problem that I searched alot, but no use so far.
The following code I am using to retrieve SQLite database using a DBHelper that extends from openhelper class.
public class DBHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "cp.db";
public static final String DB_PATH = "/data/data/abdulla.com.test/databases/";
public static final String ID = "no";
public static final String NAME = "name";
public static final String FORMULA = "formula";
public static final String MW = "mw";
public static final String OMEGA = "omega";
public static final String TC = "tc";
public static final String PC = "pc";
SQLiteDatabase db;
Cursor cursor;
ArrayList<String> elementName;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists elements");
this.onCreate(db);
}
public List<Element> getAllElements() {
List<Element> elementList = new ArrayList<Element>();
// Select All Query
Cursor cursor = null;
String selectQuery = "SELECT * FROM elements";
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Element element = new Element();
element.setNo(Integer.parseInt(cursor.getString(0)));
element.setFormula(cursor.getString(1));
element.setName(cursor.getString(2));
// Adding contact to list
elementList.add(element);
} while (cursor.moveToNext());
}
// return contact list
return elementList;
}
}
This is capture from MainActivity class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper helper = new DBHelper(this);
List<Element> elementList = helper.getAllElements();
for(Element element : elementList){
String log = "no: "+element.getNo();
Log.d("No: ", log);
}
}
}
I am getting this error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{abdulla.com.test/abdulla.com.test.MainActivity}:
android.database.sqlite.SQLiteException: no such table: elements (code 1):
, while compiling: SELECT * FROM elements
I know that elements table is there
Any help?
Probably the issue is in your onUpgrade() method. If your database doesn't have version, application tries to upgrade it, and drops your table (db.execSQL("drop table if exists elements");).
Solution: set version to DB or change onUpgrade() method (delete DROP statement).

Categories

Resources