force close at cursor line! - java

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.

Related

How to get database value into edit text in android

Here is my code
Databasehandler.java
package com.example.mybucky.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.prefs.Preferences;
/**
* Created by Satyajeet Sen on 20/12/2016.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Register.db" ;
private static final int DATABASE_VERSION = 1 ;
private static final String TABLE_REGISTER = "REGISTER";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
private static final String COL_USERNAME = "username";
private static final String COL_PASSWORD = "password";
private static final String COL_AGE = "age";
SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_REGISTER_TABLE = "CREATE TABLE " + TABLE_REGISTER + "("
+ COL_ID + " INTEGER PRIMARY KEY ," + COL_NAME + " TEXT ,"
+ COL_USERNAME + " TEXT ," + COL_PASSWORD + " TEXT ," + COL_AGE + " INTEGER "+")";
db.execSQL(CREATE_REGISTER_TABLE);
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
this.onCreate(db);
}
public void insertDetails(LoginRegisterBean l){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query ="SELECT * FROM "+TABLE_REGISTER;
Cursor cursor =db.rawQuery(query,null);
int count=cursor.getCount();
values.put(COL_ID,count);
// Contact Name
values.put(COL_NAME, l.getName());
values.put(COL_USERNAME, l.getUsername());
values.put(COL_PASSWORD, l.getPassword());
values.put(COL_AGE, l.getAge());
db.insert(TABLE_REGISTER,null,values);
db.close();
}
public String searchPass(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
b="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public String searchUser(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
a="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return a;
}
LoginRegisterBean getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_REGISTER, new String[] { COL_ID,
COL_USERNAME,COL_AGE }, COL_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
LoginRegisterBean retrievecontact = new LoginRegisterBean(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)));
// return contact
return retrievecontact;
}
}
UserAreaActivity.java 2edit texts one for age and other for username. Aim:-to display values of age nd username from database to edittext
package com.example.mybucky.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
import com.example.mybucky.myapplication.R;
import java.util.ArrayList;
import java.util.List;
public class UserAreaActivity extends AppCompatActivity {
DatabaseHandler helper = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final EditText etUsername = (EditText) findViewById(R.id.username);
final EditText etAge = (EditText) findViewById(R.id.age);
final TextView tvwelcome = (TextView) findViewById(R.id.tvwelcome);
public void retrievefromdb(LoginRegisterBean l){
List<LoginRegisterBean> lst =new ArrayList<LoginRegisterBean>();
for(int i=0;i<3;i++){
lst.add( helper.getContact(i));
}
}
}
}
I have a method returning a single contact in Databasehandler class but i dont need password to be displayed. Display fields only age and username in activity UserAreaActivity.
Welcome user!Your age is
age
---edit field------
username
---edit field-----

My error says that the table ESTOQUEPRODUTOS was not created, how can i creat?

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

SQLite NullPpointerException Error when trying to call a method

The aim is to retrieve the car park names from the car park tables columns 'CPNAME' and put those rows of names in another class' arraylist which a spinner will display.
The problem is apparently with my getCpNames() method, specifically on this line:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_CPNAME, null, null, null,
null);
The errors I get on LogCat:
Caused by: java.lang.NullPointerException
at com.example.parkangel.DbHelper.getCpnames(DbHelper.java:93)
at com.example.parkangel.BookTicket.<init>(BookTicket.java:19)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
My database class code:
package com.example.parkangel;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper
{
private static DbHelper dbHelper;
private Context ourContext;
private static DbHelper instance;
private static SQLiteDatabase ourDatabase;
private static final String DATABASE_NAME = "CPDB.db";
private static final String DATABASE_TABLE = "CPTable";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CPNAME = "cpname";
public static final String KEY_COST = "cost";
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
this.ourContext = context;
}
public static DbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new DbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CPNAME + " TEXT NOT NULL, " + KEY_COST + " TEXT NOT NULL);");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('1','Learning
Resource Center','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('2','Park and
Ride','1');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('3','de
Havilland Campus','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('4','Multi
Storey Building','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values
('5','Reception','2');");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized DbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen());
this.ourDatabase = getWritableDatabase();
return this;
}
public static String[] getCpnames()
{
String[] columns = new String[] {KEY_ID, KEY_CPNAME, KEY_COST};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_CPNAME,
null, null, null, null);
ArrayList<String> list = new ArrayList<String>();
if (c != null)
{
c.moveToFirst();
do
{
list.add(c.getString(0));
}
while (c.moveToNext());
}
if (ourDatabase == null) System.out.println ("is null");
return list.toArray(new String[]{});
}
}
This is the class and arraylist I am calling getCpnames() into:
package com.example.parkangel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class BookTicket extends Activity implements OnClickListener{
Spinner spinner, spinner2;
DbHelper dbhelper = DbHelper.getInstance(this);
String[] carParks = DbHelper.getCpnames();
I am beginner, so apologies for any amateur mistakes. Thank you in advance!
You never called DbHelper.open();
BTW, I also see a potential problem here
public synchronized DbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen());
this.ourDatabase = getWritableDatabase();
return this;
}
especially on this line
if(ourDatabase == null || !ourDatabase.isOpen());
The semicolon ";" at the end of line makes the if statement ineffective
The most likely explanation is that ourDatabase is null. You failed to call DBHelper.open() to set it.

How to create a two table in single Database in Android Application?

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

Android Development - Null Pointer Exception on Database Insert

OK, well I've been working on a simple app that allows users to save notes to contacts. It lists the contacts from the phone. User clicks on a contact and the notes entries that are related to the contact based on the contact ID are shown. The user can then add a new note by Menu>Add note. I can get all the way through the app but it wont save the data entered in the form to the database. When I try to save, I get a Null Pointer Exception. Nothing crashes, it just returns to the previous activity and doesn't do anything. I am kind of new to programming and have been teaching myself android for the past week and a half, so it could be something really simple. I have been digging around the web and frequently come to Stack Overflow to check for answers but cant seem to find anything on this one. Also, I'm not sure what code is needed so I'm just going to post the code for my form activity and my dbadapter. Thanks in advance for any help!
This is the activity used to enter the data:
package com.onyx.formapp23;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.onyx.formapp23.MyDbAdapter;
public class FormsNewNote extends Activity {
String mIntentString;
int contactId;
EditText contactIdEdit, titleEdit, bodyEdit;
long dateTimeValue;
Button submitBtn, discardBtn;
private MyDbAdapter db = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forms_newnote);
Bundle extras = getIntent().getExtras();
mIntentString = extras.getString("contactId");
db = new MyDbAdapter(this);
contactIdEdit = (EditText) findViewById(R.id.noteFormContactId);
contactIdEdit.setText(mIntentString);
contactId = Integer.parseInt(mIntentString);
titleEdit = (EditText) findViewById(R.id.noteFormTitle);
bodyEdit = (EditText) findViewById(R.id.noteFormBody);
dateTimeValue = java.lang.System.currentTimeMillis();
submitBtn = (Button) findViewById(R.id.noteFormSave);
discardBtn = (Button) findViewById(R.id.noteFormDiscard);
submitBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
try{
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
db.createNote(contactId, titleInsert, bodyInsert, dateTimeValue);
} catch (Exception e) {
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
e.printStackTrace();
Context context = getApplicationContext();
CharSequence text = "SQL Exception Thrown: " + e + "\nTitle: " + titleInsert + "\nBody: " + bodyInsert;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
finish();
}
});
}
}
This is my Db adapter class:
package com.onyx.formapp23;
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 MyDbAdapter {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_CONTACTID = "contactId";
public static final String KEY_ROWID = "_id";
public static final String KEY_DATETIME = "datetime";
private static final String TAG = "MyDbAdapter";
private static final String DATABASE_CREATE =
"create table contactNotes (_id integer primary key autoincrement, contactId integer, title text not null, body text not null, datetime long);";
private static final String DATABASE_NAME = "OnyxDatabase";
private static final String DATABASE_TABLE = "contactNotes";
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 MyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public MyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(int contactId, String title, String body, long datetime) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CONTACTID, contactId);
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
initialValues.put(KEY_DATETIME, datetime);
return mDb.insertOrThrow(DATABASE_TABLE, null, initialValues);
}
public void createNote2(int contactId, String title, String body) {
mDb.execSQL("insert into " + DATABASE_TABLE + " (" + KEY_CONTACTID + ", " + KEY_TITLE + ", " + KEY_BODY + ", " + KEY_DATETIME + ") values(" + contactId + ", " +
title + ", " + body + ", " + java.lang.System.currentTimeMillis() + ");");
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_CONTACTID,
KEY_BODY, KEY_DATETIME}, null, null, null, null, null);
}
public Cursor fetchNotesForContact(String contactId) {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CONTACTID, KEY_TITLE, KEY_BODY, KEY_DATETIME}, KEY_CONTACTID + " = " + contactId, null, null, null, new String (KEY_DATETIME +
" COLLATE LOCALIZED ASC"));
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String title, String body) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
And here is the Trace from the Eclipse Debug:
Thread [<1> main] (Suspended (entry into method createNote in MyDbAdapter))
MyDbAdapter.createNote(int, String, String, long) line: 58
FormsNewNote$1.onClick(View) line: 43
Button(View).performClick() line: 2447
View$PerformClick.run() line: 9025
ViewRoot(Handler).handleCallback(Message) line: 587
ViewRoot(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4628
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 870
ZygoteInit.main(String[]) line: 628
NativeStart.main(String[]) line: not available [native method]
Doesn't look like you are calling MyDbAdapter.open() anywhere so in createNote() mDb is null.

Categories

Resources