I try to call a method and write to my database from another activity in android but my app crashes because it cannot write. My activity does not have On Create because it does not need it. Therefore I have this code:
DB db = new DB(ServSearcher.this); which I want to give me acess to my Database and then I use my method below like:
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
db.addContact(new Contact(var, getTime()));
Here is my logcat error:
java.lang.NullPointerException
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:268)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.android.SecondActivity.DB.getAllContacts(DB.java:88)
at com.android.SecondActivity.ServSearcher$5.onAvailable(ServSearcher.java:189)
I think it is obvious that my app cannot write to database so this line is wrong DB db = new DB(ServSearcher.this); or at least does not gives me access, any ideas?
edit after V_J comment:
Here is my method on DB
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTime(cursor.getInt(0));
contact.setName(cursor.getString(1));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
I think you can solve your problem with the singleton pattern, I leave a link below to your explanation.
https://en.wikipedia.org/wiki/Singleton_pattern
Related
I'm not able to disply the content of my sqllite table. Instead of displaying the values its displaying address of it....help me with the same...
public List<databaseHandler> getAllContacts() {
List<databaseHandler> contactList = new ArrayList<databaseHandler>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// return cursor;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
databaseHandler handler = new databaseHandler();
handler.setId(Integer.parseInt(cursor.getString(0)));
handler.setName(cursor.getString(1));
//contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(handler);
} while (cursor.moveToNext());
}
//
// // return contact list
return contactList;
}
Looks like you're returning a list of databaseHandler objects and displaying them somehow. "Address of it" hints at the display mechanism using the default toString() implementation that outputs the object's class name and hashCode().
To fix that, override toString() in your databaseHandler class to return a string representation you want to get displayed.
here i get only single value and save it in spinner but i want to retrieve two column value in one spinner
public List<String> getAllLabels1(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT DISTINCT WeatherPrediction.CropID as CropID, Crop.Name as Name FROM Crop INNER JOIN " +
"WeatherPrediction ON Crop.CropID = WeatherPrediction.CropID order by Name";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
I created and populated a SQLite database with the Firefox SQLite Manager. I copied the .sqlite file into the assets folder of my Android project.
My aim is to use this records to populate a spinner. When I query the database, the cursor displays the columns but no records.
My DatabaseHandler class extends SQLiteOpenHelper and contains methods for onCreate, onUpgrade and getAllOffices.
public List<String> getAllOffices(){
List<String> offices = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT OfficeId as _id, OfficeName FROM " + TABLE_OFFICE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
offices.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning offices
return offices;
}
Any ideas on why the records are not returned would be appreciated.
Try this:
public List<String> getAllOffices(){
List<String> offices = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT OfficeId as _id, OfficeName FROM " + TABLE_OFFICE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
offices.add(cursor.getString(cursor.getColumnIndex("_id")));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning offices
return offices;
}
Basically it will just ensure that you are using the correct column index. Otherwise if you are using eclipse then try the cellobject plugin to browse the database and make sure your table is populated as expected:
http://marketplace.eclipse.org/content/cellobject-sqlite-xml-browser#.UWOU5RaBD3g
Please try this and may be useful for you.
public List<String> getAllOffices(){
List<String> offices = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_OFFICE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.println("CURSOR SIZE:"+cursor.getCount())
// looping through all rows and adding to list
if(cursor.getCount()!=0){
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getString(c.getColumnIndex("as per your db column name"));
} while (cursor.moveToNext());
}
}
// closing connection
cursor.close();
db.close();
// returning offices
return offices;
}
First of all you have to just see console output if you are getting right then add into your office bean
when I try to request informations from my sqlite database I get this error:
07-19 02:17:10.835: E/AndroidRuntime(689): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.bodprod.dkr/de.bodprod.dkr.MediNotmediList}: java.lang.IllegalArgumentException: You must supply an SQL string
My Database Request:
public ArrayList<HashMap<String,Object>> getAllNotmedis(){
ArrayList<HashMap<String,Object>> notmediList = new ArrayList<HashMap<String,Object>>();
String selectQuery = "SELECT medi_id, medi_wirk, medi_handel FROM dkr_medi_liste ORDER BY medi_wirk";
Log.d("ALLNOTMEDIS",selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
HashMap<String , Object> notmedi_item;
if (cursor.moveToFirst()) {
do {
notmedi_item = new HashMap<String, Object>();
notmedi_item.put("sql_id", Integer.parseInt(cursor.getString(0)));
notmedi_item.put("wirk", cursor.getString(1));
notmedi_item.put("handel", unescape(cursor.getString(2)));
notmediList.add(notmedi_item);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return notmediList;
}
This line make the error:
SQLiteDatabase db = this.getWritableDatabase();
Why I become this error? The database exist and is filled up with data...
The error was in the onCreate section.
I tried to insert a blank line with db.execSQL.
I get the error on this line becaause SQLiteDatabase db = this.getWritableDatabase(); calls the onCreate method.
You should create Database Adapter that will serve as the connection between your app and your database
java.lang.IllegalArgumentException: You must supply an SQL string
Above exception occurs if you pass an invalid Sql Query statement in the rawQuery Method. There must be a problem in below statement:
= "SELECT medi_id, medi_wirk, medi_handel FROM dkr_medi_liste ORDER BY medi_wirk";
I have created a database. And opened it :
public SQLiteDatabase open() {
String path = "/data/data/com.develop.assetcapture/databases/Asset_Directory";
db = SQLiteDatabase.openOrCreateDatabase(path, null);
return db;
}
I'm writing a user registration and what to enable them to reset their passwords.
I have no problem inserting new records or querying the database. However on my resetPassword(username,password) method I get an error message:
android.database.sqlite.DatabaseObjectNotClosedException:
Application did not close the cursor or database object that was opened here
Please help, I've been stuck on this for too long now.
When you query the database you usually receive a Cursor object. Here is an example:
public Cursor querySomething() {
final String whereClause = ...
final String[] params = ...
final Cursor c = this.getReadableDatabase().query(
Table.TABLE_NAME,
Table.allColumnNames(),
whereClause,
params, // parameters for where clause
null, // group
null, // having
null); // order
return c;
}
Using the cursor c you access the rows in the answer. When you have finished processing the answer you have to close the cursor object:
c.close();