I am creating an android application that will be using a SQLite database. I have created a separate class called DBAdapter that holds all the methods relating to the database.
My issue comes when I try to access these methods from the main activity. I am still learning but I would normally instantiate the DBAdapter class and then I would be able to reference the methods. However the approach I am taking isnt working. Below is the single line of how I am trying to instantiate the class and under that is the rest of the class.
The error I am getting is cannot resolve method 'open()'
Instantiate Line and method
DBAdapter db = new DBAdapter(this);
db.open();
Main Class
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ContentFrameLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final Context context = this;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBAdapter db = new DBAdapter(this);
db.open();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_box);
dialog.setTitle("Add new Location!");
dialog.show();
final EditText NameEdit = (EditText) findViewById(R.id.NameInput);
final EditText LatEdit = (EditText) findViewById(R.id.LatInput);
final EditText LongEdit = (EditText) findViewById(R.id.LongInput);
final EditText PhoneEdit = (EditText) findViewById(R.id.PhoneInput);
final Button OkButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
final Button CancelButton = (Button) dialog.findViewById(R.id.dialogButtonCancel);
OkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String RealName = NameEdit.getText().toString();
String Lat = LatEdit.getText().toString();
Float realLat = Float.parseFloat(Lat);
String Long = LongEdit.getText().toString();
Float realLong = Float.parseFloat(Long);
String Phone = PhoneEdit.getText().toString();
Double realPhone = Double.parseDouble(Phone);
//Use above to create a new Geofence
}
});
CancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
}
DBAdpater Class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Rory on 09/09/2016.
*/
public class DBAdapter {
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
//Database Version & name
private static final String DATABASE_NAME = "OpenSesame";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "DBMain";
private static final String GEOTABLE = "geoTable";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_LAT = "lat";
private static final String KEY_LONG = "long";
private static final String KEY_RADIUS = "radius";
private static final String KEY_PHONE = "phone";
private static final String CREATE_GEO_TABLE = "CREATE TABLE "
+ GEOTABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTO INCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_LAT + " FLOAT,"
+ KEY_LONG + " FLOAT,"
+ KEY_RADIUS + " INTEGER,"
+ KEY_PHONE + " INTEGER" + ")";
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Method for updating the database
* #param db
* #param newVersion
* #param oldVersion
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public DatabaseHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public Cursor DeleteGeo(String name) {
return db.rawQuery("delete from geoTable where name = " + name, null);
}
public long AddGeo(String name, float lat, float lon, double phone, int radius) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_LAT, lat);
initialValues.put(KEY_LONG, lon);
initialValues.put(KEY_PHONE, phone);
initialValues.put(KEY_RADIUS, radius);
return db.insert(GEOTABLE, null, initialValues);
}
public Cursor GetAllGeos() {
return db.rawQuery("select * from geoTable order by name ASC", null);
}
}
}
Your DBAdapter class does not have the open() method. It is the private inner class DatabaseHelper that has that method. You have two options to expose open() to be able to call it the way you are expecting.
Option 1: add an open() method to DBAdapter that calls DatabaseHelper's open() method
public void open() {
DBHelper.open();
}
Option 2: remove DatabaseHelper entirely, and have DBAdapter extends SQLiteOpenHelper instead
public class DBAdapter extends SQLiteOpenHelper {
...
public DBAdapter(Context ctx) {
this.context = ctx;
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// add all the code from inside DatabaseHelper below
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
// you will have to change this method to work
public DBAdapter open() throws SQLException
{
db = getWritableDatabase();
return this;
}
...
}
Related
Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Try removing space from your column name's
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..
Below is my database that I have already created and it works fine, it can save the data to the database,I am really new to this android project and need guidance on how to display all data that was saved inside the listview.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BmiDatabase {
private data helper;
private SQLiteDatabase help;
private Context context;
public BmiDatabase(Context context){
helper = new data(context);
help = helper.getWritableDatabase();
this.context=context;
}
public long insertData(String bmi, String status, String weight){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(data.NAME, bmi);
contentValues.put(data._STATUS, status);
contentValues.put(data.WEIGHT, weight);
long id = db.insert(data.DATABASE_TABLE, null, contentValues);
db.close();
return id;
}
public String getAllData(){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {data.UID, data.NAME, data._STATUS, data.WEIGHT};
Cursor cursor = db.query(data.DATABASE_TABLE, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext())
{
// int index1 = cursor.getColumnIndex(data.UID);
// int cid = cursor.getInt(index1);
int cid = cursor.getInt(0);
String bmi = cursor.getString(1);
String status = cursor.getString(2);
String weight = cursor.getString(3);
buffer.append(cid +" "+bmi+" kg "+status+" "+weight+ "\n");
}
return buffer.toString();
}
public static class data extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME = "bmidatabase";
private static final String DATABASE_TABLE = "bmitable";
private static final int DB_VERSION = 7;
public static final String UID = "_id";
public static final String NAME = "Bmi";
public static final String _STATUS = "Status";
public static final String WEIGHT = "Weight";
private static final String DROP_TABLE= "DROP TABLE IF EXISTS "+DATABASE_TABLE;
private static final String CREATE_TABLE = "CREATE TABLE "+DATABASE_TABLE+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +
" "+NAME+" VARCHAR(255)," +
" "+_STATUS+" VARCHAR(255)," +
""+WEIGHT+" VARCHAR(255));";
public data(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
this.context=context;
}
public void getAllData(){
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
Message.message(context,"Database Created");
}
catch (SQLException e){
Message.message(context, "Failed" +e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
Message.message(context, "DATABASE DELETED");
db.execSQL(DROP_TABLE);
onCreate(db);
}
catch(SQLException e){
Message.message(context, "SQL FAILED");
}
}
}
}
Below is the code for my mainactivity, it shows that I can display it using a toast, but I have no idea how to call the method to populate the list view with those data.
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//private static DataHelper DataHelper;
//DataHelper helper = new DataHelper(this);
private static BmiDatabase data;
private EditText weightinputid;
private EditText heightinputid;
private Button buttonBMI, save, detail;
private TextView BMIStatus;
private TextView BMIfinal;
private double weight =0.0;
private double height =0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupDB();
// setDB();
initializeApp();
}
private void initializeApp(){
weightinputid = (EditText) findViewById(R.id.weightid);
heightinputid = (EditText) findViewById(R.id.heightid);
buttonBMI = (Button) findViewById(R.id.buttonBMI);
BMIfinal= (TextView) findViewById(R.id.BMIfinal);
BMIStatus = (TextView) findViewById(R.id.BMIstatus);
save = (Button) findViewById(R.id.button);
detail = (Button)findViewById(R.id.button1);
data = new BmiDatabase(this);
}
public void calculateBMI (View v){
String status;
weight= Double.parseDouble(weightinputid.getText().toString());
height= Double.parseDouble(heightinputid.getText().toString());
double bmi = weight/(height/100*height/100);
String result = String.format("%.2f", bmi);
Log.d("MainActivity", result);
BMIfinal.setText(result, TextView.BufferType.NORMAL);
if(bmi < 16){
status = "Seriously Underweight";
}
else if(bmi >=16.0 && bmi < 18.0){
status = "Underweight";
}
else if(bmi >=18.0 && bmi <24.0){
status = "Normal";
}
else{
status = "Obese";
}
BMIStatus.setText(status);
}
public void save(View v){
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
String weight = weightinputid.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0)
{
Message.message(this, "");
}
else
{
Message.message(this, "");
}
}
public void detail(View v){
String d = data.getAllData();
Message.message(this, d);
}
}
I am a php developer learning my way around android development.
I have a dbhelper helper class which has the below coding.
package com.example.bootstart;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
private static final String LOGTAG = "THEDBHELPER";
private static final String DATABASE_NAME = "geolocation.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_LOCATIONS = "locations";
private static final String COLUMN_ID = "id";
private static final String COLUMN_welawa = "welawa";
private static final String COLUMN_lati = "latitude";
private static final String COLUMN_longi = "longitude";
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_LOCATIONS + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_welawa + " TEXT, " + COLUMN_lati
+ " TEXT, " + COLUMN_longi + " TEXT)";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.i(LOGTAG, "TABLE HAS BEEN CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
onCreate(db);
}
public void insert_records(String lati, String longi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
sqLiteDatabase.execSQL("INSERT INTO " +
TABLE_LOCATIONS +
"(welawa,latitude,longitude) Values (" + ts + ","+ lati +"," + longi + ");");
Log.i(LOGTAG, "Data Entered");
}
}
However, when I try to access the insert_records function from another class by using
dbhelper = new DBHelper(this); //I can't even get the insert_records function in the suggestions in the drop here OR DBHelper dbh= new DBHelper(this); dbh.insert_records("12.2323", "25.22222"); lovely eclipse throws the error message The constructor DBHelper(new Runnable(){}) is undefined.
I simply have no idea on how to access my function.
I have
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
defined at the top of the class I am trying to access from.
Below is the class im trying to access the dbhelper function from.
package com.example.bootstart;
import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class GPSService extends Service {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
GPSTracker gps;
private int mInterval = 10000;
private Handler mHandler;
#Override
public void onCreate()
{
Log.v("StartServiceAtBoot", "StartAtBootService Created");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
//Service Will Start until stopped
mHandler = new Handler();
Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
mStatusChecker.run();
return START_STICKY;
}
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"Service Stopped",Toast.LENGTH_LONG).show();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
gps = new GPSTracker(GPSService.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
//new AsyncSendData().execute("http://www.accuretta.lk/nv/maps/track_post"); Sending Info Code Is Working Fine
DBHelper dbh= new DBHelper(this);
dbh.insert_records("12.2323", "25.22222");
dbh.insert_records("55.2222", "11.256");
}
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
}
I haven't seen any runnables created in any of the tutorials.
Your help is greatly appreciated.
You are passing the wrong parameter type to the DBHelper constructor. You have to do like this
DBHelper dbh= new DBHelper(getApplicationContext());
inside your void run() method of the mStatusChecker Runnable instance. if you look into the error message, you can understand that compiler is not able to find an appropriate constructor for DBHelper class with parameter type Runnable. that's why this error is thrown by eclipse.
Hope you understand now.
I was researching on how to add tables in an sqlite database for more information but I can't have a grip on how it was truly done.
I have this code:
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "SCORING";
public static final String MYDATABASE_TABLE = "SCORING_TABLE";
public static final String MYDATABASE_TABLE1 = "Assessment";
public static final int MYDATABASE_VERSION = 3;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
//create table SCORING (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_CONTENT1 + " text not null, "
+ KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + "text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String content1, String content2, String content3){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT1, content1);
contentValues.put(KEY_CONTENT2, content2);
contentValues.put(KEY_CONTENT3, content3);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2, KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE SCORING_TABLE ADD COLUMN Content4 TEXT");
}
}
}
}
and for the second one I'm having a hard time inputting data to the second table
package com.example.database;
import com.example.database.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidSQLite extends Activity {
EditText inputContent2;
TextView textView1, textView2;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
inputContent2 = (EditText)findViewById(R.id.content2);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2, R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int a=Integer.parseInt(textView1.getText().toString());
int b=a+2;
String s1 = String.valueOf(b);
textView1.setText(s1);
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
String data1 = textView1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = textView2.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
}
I personally found using ContentProviders to be a clearer and easier to maintain way to manage multiple tables.
There is a nice article here that explains ContentProviders and other ways of dealing with android database/
http://www.vogella.com/articles/AndroidSQLite/article.html#tutorialusecp