I have Created a database in Sqllite Android Application and I tried to add two tables in my Database, but I have problem to create that Database. First Table only Created. Can anyBody help me?
package com.android.cdtech;
import java.sql.SQLException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class saveData {
public static final String KEY_ROWID = "rowid"; public static final String KEY_DATE = "Date";public static final String KEY_NAME = "CustomerName";public static final String KEY_AMOUNT = "Amount";public static final String KEY_BANK = "Banks";
private static final String TAG = "DBAdapter";
public static final String KEY_BUSNAME="BusinessName";public static final String KEY_ADD="Address";public static final String KEY_CPERSON="ContactPerson";;
private static final String DATABASE_NAME = "EXPORTDETAILS";
private static final String DATABASE_TABLE = "Payment";
private static final String DATABASE_TABLE2 = "Customer";
private static final int DATABASE_VERSION = 1;
private static String DATABASE_CREATE =
"create table Payment (_id integer primary key autoincrement, "
+ "Date text not null,"+"CustomerName text not null,"+"Amount text not null,"+"Banks text not null);";
private static final String DATABASE_CREATECUS =
"create table Customer (_id integer primary key autoincrement, "
+ "BusinessName text not null,"+"Address text not null,"+"ContactPerson text not null,"+"PhoneNumber text not null,);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public saveData(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
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);
db.execSQL(DATABASE_CREATECUS);
}
#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 titles");
onCreate(db);
}
}
public saveData open()throws SQLException
{
db=DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insert(String Date,String CustomerName,String Amount,String Banks) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_DATE,Date);
cv.put(KEY_NAME,CustomerName);
cv.put(KEY_AMOUNT,Amount);
cv.put(KEY_BANK,Banks);
return db.insert(DATABASE_TABLE, null,cv);
}
public long insertForm(String BusinessName ,String Address ,String ContactPerson) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_BUSNAME,BusinessName);
cv.put(KEY_ADD,Address);
cv.put(KEY_CPERSON,ContactPerson);
}
public Cursor getlatlng()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
public Cursor order()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE2,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
}
Error Code =1 No Such table for Customer
use below two class
package Your 'packagename';
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 DATABASE_NAME = "BistroDB";
private static final int DATABASE_VERSION =1;
// Database creation sql statement
public static final String Table1= "create table table1name ("Your cloumns");";
public static final String Table2 = "create table table2name ("Your cloumns");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(table1);
database.execSQL(table2);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS table1");
database.execSQL("DROP TABLE IF EXISTS table2");
onCreate(database);
}
public boolean deleteDatabase(Context context) {
return context.deleteDatabase(DATABASE_NAME);
}
}
Use below class to insert values into table
package 'Your package name';
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DataBaseAdapter {
// Database fields
private Context context;
private SQLiteDatabase database;
private DBHelper dbHelper;
public DataBaseAdapter(Context context) {
this.context = context;
}
public DataBaseAdapter open() throws SQLException {
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public Cursor fetchAllTAble1data() {
return database.query("MenuData", new String[] { "id", "Title",
"Image", "Description" }, null, null, null, null, null);
}
public Cursor fetchAllTable2data() {
return database.query("RestaurantsData", new String[] {
"restaurant_id", "name", "phone", "email", "open_days",
"timing", "website", "loc_name", "street", "city", "longitude",
"latitude", "zip" }, null, null, null, null, null);
}
public void deleteTable(String tablename){
database.execSQL("drop table if exists "+tablename+';');
}
public void createIndividualTable(String query){
database.execSQL(query);
}
public void InsertTable1Data(TAble1 review) {
ContentValues values = new ContentValues();
values.put("Name", review.Name);
values.put("Email", review.Email);
values.put("Comment", review.Comment);
values.put("Rating", review.Rating);
database.insert("ReviewsData", null, values);
}
public void InsertTable2Data(TAble2 photos) {
ContentValues values = new ContentValues();
values.put("photo", photos.Photos);
database.insert("PhotosData", null, values);
}
public ContentValues createContentValues(String category, String summary,
String description) {
ContentValues values = new ContentValues();
return values;
}
}
Try removing the "," at the end of DATABASE_CREATECUS
Related
I'm a beginner with android studio, so I'm stumbling my way through building my first app. I've come up with and error when attempting to save my data to a database. Whenever I try to save any digits, the app crashes.
Database Java file:
package com.miahollins.basketballfinal;
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;
/**
* Created by pumpkin on 6/17/16.
*/
public class DataHandler {
public static final String GAMES = "games_played";
public static final String GAMES2 = "games_started";
public static final String GAMES3 = "points";
public static final String TABLE_NAME = "statstable";
public static final String DATA_BASE_NAME = "mydatabase.sqlite";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_CREATE = "create table statstable (games_played VARCHAR not null, games_started VARCHAR not null, points VARCHAR not null)";
DatabaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DatabaseHelper(ctx);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context ctx){
super(ctx, DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(TABLE_CREATE);
} catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS statstable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getWritableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String games_played, String games_started, String points){
ContentValues content = new ContentValues();
content.put(GAMES, games_played);
content.put(GAMES2, games_started);
content.put(GAMES3, points);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[]{GAMES, GAMES2, GAMES3},null, null, null, null, null);
}
}
In my logcat I get an error saying that columns cannot be found. Any help is appreciated!
I have an application in which I'm trying to add user info inside a table created using SQLlite. The problem is when I press the add button the application crashes. bellow I include all the code and logcat.
MainActivity.java
package com.example.asus.sqlliteproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDB;
EditText Name,LastName,Grades;
Button AddData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DataBaseHelper(this);
Name = (EditText)findViewById(R.id.name);
LastName = (EditText)findViewById(R.id.lastName);
Grades = (EditText)findViewById(R.id.Grades);
AddData = (Button)findViewById(R.id.addDataButton);
addData();
}
public void addData () {
AddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean inserted = myDB.insertData(Name.getText().toString(),
LastName.getText().toString(),
Grades.getText().toString());
if (inserted){
Toast.makeText(MainActivity.this,"Text Inserted!", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this,"Unsuccessful!", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DataBaseHelper.java
package com.example.asus.sqlliteproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Asus on 29.4.2016.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DataBaseName = "student.db";
public static final String DataTableName = "studentTable.db";
public static final String ColID = "ID";
public static final String ColName = "Name";
public static final String ColLastName = "LastName";
public static final String ColGrades = "Grade";
public DataBaseHelper(Context context) {
super(context, DataBaseName, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + DataTableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT)," +
"Name TEXT, LastName TEXT, Grade INTEGER");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists" + DataTableName);
onCreate(db);
}
public boolean insertData (String name, String LastName, String Grades) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColName,name);
contentValues.put(ColLastName,LastName);
contentValues.put(ColGrades,Grades);
long result = db.insert(DataTableName, null, contentValues);
if (result == -1) {
return false;
}else
return true;
}
}
logcat error (separated into two imgs) and activity_main view
You missed white space here "create table" should be "create table "
Don't forget about white spaces.
try this:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DataBaseName = "student.db";
public static final String DataTableName = "studentTable";
public static final String ColID = "ID";
public static final String ColName = "Name";
public static final String ColLastName = "LastName";
public static final String ColGrades = "Grade";
public DataBaseHelper(Context context) {
super(context, DataBaseName, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + DataTableName + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Name TEXT, LastName TEXT, Grade INTEGER);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists" + DataTableName);
onCreate(db);
}
public boolean insertData (String name, String LastName, String Grades) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColName,name);
contentValues.put(ColLastName,LastName);
contentValues.put(ColGrades,Grades);
long result = db.insert(DataTableName, null, contentValues);
if (result == -1) {
return false;
}else
return true;
}
}
Once I was getting similar error. I simply replaced 'ID' by '_id' and it worked like a charm.
I don't know why this error is appearing, can somebody help me please? to continue my project? thanks
//BancoDeDados class
package kabashima.materiaisdeconstrucaoconcept.bancodedados;
import android.content.ContentValue`import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import kabashima.materiaisdeconstrucaoconcept.Contact;
public class BancoDeDados extends SQLiteOpenHelper {
// private static final int DATABASE_VERSION = 1;
//private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NOME = "nome";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_SENHA = "senha";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts(id integer primary key not null ," +
"nome text not null, email text not null, senha text not null);";
public BancoDeDados(Context context){
//super(context, DATABASE_NAME, null, DATABASE_VERSION);
super(context, "contacts.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
db.execSQL( ScriptSQL.getCreateEstoqueProdutos());
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NOME, c.getNome());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_SENHA, c.getSenha());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String nome){
db = this.getReadableDatabase();
String query = "select nome, senha from " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b = "not found";
if(cursor.moveToFirst()){
do{
a = cursor.getString(0);
if(a.equals(nome))
{
b = cursor.getString(1);
break;
}
}while (cursor.moveToNext());
}
return b;
}
}
//AND THE SCRIPTSQL
package kabashima.materiaisdeconstrucaoconcept.bancodedados;
public static String getCreateEstoqueProdutos()
{
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append(" CREATE TABLE IF NOT EXISTS ESTOQUEPRODUTOS ( ");
sqlBuilder.append("_id INTEGER NOT NULL ");
sqlBuilder.append("PRIMARY KEY AUTOINCREMENT, ");
sqlBuilder.append("NOME VARCHAR (200), ");
sqlBuilder.append("MARCA VARCHAR (200), ");
sqlBuilder.append("LOJA VARCHAR (200), ");
sqlBuilder.append("ESTOQUE VARCHAR (10), ");
sqlBuilder.append("VALOR VARCHAR (30), ");
sqlBuilder.append(");");
return sqlBuilder.toString();
}
}
//RepositorioEstoque class
package kabashima.materiaisdeconstrucaoconcept.bancodedados.dominio;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.ArrayAdapter;
public class RepositorioEstoque {
private SQLiteDatabase conn;
public RepositorioEstoque(SQLiteDatabase conn) {
this.conn = conn;
}
public void TesteInserirProdutos() {
for (int i = 0; i < 10; i++) {
ContentValues values = new ContentValues();
values.put("NOME", "JR");
conn.insertOrThrow("ESTOQUEPRODUTOS", null, values);
}
}
public ArrayAdapter<String> buscaEstoque(Context context)
{
ArrayAdapter<String> adpEstoque = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
Cursor cursor = conn.query("ESTOQUEPRODUTOS",null,null,null,null,null,null);
if (cursor.getCount() > 0)
{
do {
cursor.moveToFirst();
String nome = cursor.getString(1);
adpEstoque.add(nome);
} while (cursor.moveToNext());
}
return adpEstoque;
}
}
the error says it on console : 2938- 2938/kabashima.materiaisdeconstrucaoconcept E/SQLiteLog﹕ (1) no such table: ESTOQUEPRODUTOS
I have two files which both utilise a specific symbol class "Car". I have chosen this as a recurring pattern throughout the project.
My error:
DBhelper.java:
package com.example.brad.myapplication;
/**
* Created by Brad on 21/07/2014.
*/
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.graphics.Bitmap;
import android.view.View;
import android.view.TextureView;
public class DBhelper {
public static final String CAR_ID = "id";
public static final String CAR_PHOTO = "photo";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "CarDB.db";
private static final int DATABASE_VERSION = 1;
private static final String CARS_TABLE = "Cars";
private static final String CREATE_CARS_TABLE = "create table "
+ CARS_TABLE + " (" + CAR_ID
+ " integer primary key autoincrement, " + CAR_PHOTO
+ " blob not null);";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CARS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CARS_TABLE);
onCreate(db);
}
}
public void Reset() {
mDbHelper.onUpgrade(this.mDb, 1, 1);
}
public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void insertCarDetails(**Car** car) {
ContentValues cv = new ContentValues();
cv.put(CAR_PHOTO, Utility.getBytes(car.getBitmap()));
mDb.insert(CARS_TABLE, null, cv);
}
public **Car** retriveCarDetails() throws SQLException {
Cursor cur = mDb.query(true, CARS_TABLE, new String[] { CAR_PHOTO}, null, null, null, null, null, null);
if (cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(CAR_PHOTO));
cur.close();
return new Car(Utility.getPhoto(blob));
}
cur.close();
return null;
}
}
InsertandRetriveBlobData:
package com.example.brad.myapplication;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Created by Brad on 20/07/2014.
*/
public class InsertandRetriveBlobData extends MyActivity {
private DBhelper DbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
DbHelper = new DBhelper(this);
**Car** car_One = new Car(BitmapFactory.decodeResource(
getResources(), R.drawable.photo), 1);
DbHelper.open();
DbHelper.insertCarDetails(car_One);
DbHelper.close();
car_One = null;
DbHelper.open();
car_One = DbHelper.retriveCarDetails();
DbHelper.close();
ImageView carphoto = (ImageView) findViewById(R.id.photo);
carphoto.setImageBitmap(car_One.getBitmap());
}
}
I have a feeling it is a slight bug as I am also having errors with any use of getBitmap() "Cannot resolve method getBitmap()" despite importing it's library.
Check whether your Car class is in myapplication directory along with the other two classes you mentioned here.
And then compile from myapplication directory.
Hy!
I'm trying to create an application that looks for gps data that was stored in SQlite database.
But I'm facing a problem:
I built an DbAdapter class that creates my database and now I'm trying from another class to get an cursor over my all data,using this function:
public Cursor fetchAllData() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
}
Now,I'm creating an instance of DbAdapter in my new class,but I get forceclose when I insert this line:Cursor c=db.fetchAllData();
The class that creates my database looks like this:
package test.android;
import java.util.ArrayList;
import java.util.List;
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;
public class CoordonateDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_LONGITUDE= "longitude";
public static final String KEY_LATITUDE = "latitude";
public static final String KEY_COUNTRY= "country";
public static final String KEY_TOWN= "town";
public static final String KEY_STREET = "street";
private static final String TAG = "CoordonateDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table car1 (_id integer primary key autoincrement, "
+ "longitude text not null, latitude text not null," +
"country text not null,town text not null,street text not null);";
private static final String DATABASE_NAME = "gps";
private static final String DATABASE_TABLE = "masini";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
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) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public CoordonateDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CoordonateDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long insertData(String longitude, String latitude, String country, String town, String street) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LONGITUDE, longitude);
initialValues.put(KEY_LATITUDE, latitude);
initialValues.put(KEY_COUNTRY, country);
initialValues.put(KEY_TOWN, town);
initialValues.put(KEY_STREET, street);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteData(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllData() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
}
public Cursor fetchData(long rowId) throws SQLException {
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[]
{KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String longitude, String latitude,String country, String town,String street) {
ContentValues args = new ContentValues();
args.put(KEY_LONGITUDE, longitude);
args.put(KEY_LATITUDE, latitude);
args.put(KEY_COUNTRY, country);
args.put(KEY_TOWN, town);
args.put(KEY_STREET, street);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.mDb.query(DATABASE_TABLE, new String[] { "longitude"},
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
}
And the class that retrieves the gps data is like this:
package test.android;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;
public class screen_database extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_database);
CoordonateDbAdapter db = new CoordonateDbAdapter(this);
db.open();
long id;
// id= db.insertData("-36.2", "125","Romania","Cluj","Zorilor");
// db.insertData("44", "55","Romania","Iasi","Alexandru Ioan Cuza");
// List<String> names = db.selectAll();
Cursor c=db.fetchAllData();
/* if (c.moveToFirst())
{
do {
// DisplayTitle(c);
} while (c.moveToNext());
}*/
// c.close();
}
/* public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"longitude: " + c.getString(0) + "\n" +
"latitude: " + c.getString(1) + "\n" +
"country: " + c.getString(2) + "\n" +
"town: " + c.getString(3),
Toast.LENGTH_LONG).show();
}*/
}
//}
You can see lots of lines that are comments because I get force close when I'm asking for a Cursor,so I tried to keep it as simple.
Do I need any permissions to work with cursors,becuase I looked on the internet and all the line code looks like mine?!
Another problem is that my application is quite big,and I'm accesing this classes from other classes....a long row of classes until I get to query from the Sqlite.
I would really apreciate if you would help me,it might be something simple but I can't figure it out what it is.Thank you!!!
first try to access directly by copying
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
instead of calling it by method.
If that works, check if curser is available in the method.
If it is, try to reduce the SQLQuery like
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE}, null, null, null, null, null);
and add more columns step by step.