Hi I am creating an sqlite helper file for my android project. I have found a couple of tutorials on doing this but i am having an issue with retrieving values from the sqlite database. I get the following error message:"Can not resolve constructor"
Event getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_EVENTS, new String[] { KEY_ID, KEY_EVENTNAME, KEY_EVENTTIME,
KEY_EVENTDATE, KEY_EVENTLOCATION, KEY_EVENTADDRESS1, KEY_EVENTADDRESS2, KEY_EVENTCITY, KEY_EVENTSTATE, KEY_EVENTZIP, KEY_EVENTTYPE },
KEY_ID + "=?", new String[] {String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Event event = new Event(Integer.parseInt(cursor.getString(0)), cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),
cursor.getString(5), cursor.getString(6),cursor.getString(7), cursor.getString(8), cursor.getString(9),
cursor.getString(10), cursor.getString(11));
//return event
return event;
}
The error is in the statement that starts with Event event = new Event....
I am not sure do if i need a cursor.getString(n) for each table column?
Any help would be great.
Thanks.
adding event file
//empty contructor
public Event(){
}
public Event(int id, String _eventName, String _eventTime, String _eventDate, String _eventLocation, String _eventAddress1, String _eventAddress2, String _eventCity, String _eventState, int _eventZip, String _eventType) {
this._id = id;
this._eventName = _eventName;
this._eventTime = _eventTime;
this._eventDate = _eventDate;
this._eventLocation = _eventLocation;
this._eventAddress1 = _eventAddress1;
this._eventAddress2 = _eventAddress2;
this._eventCity = _eventCity;
this._eventState = _eventState;
this._eventZip = _eventZip;
this._eventType = _eventType;
}
public Event(String _eventName, String _eventTime, String _eventDate, String _eventLocation, String _eventAddress1, String _eventAddress2, String _eventCity, String _eventState, int _eventZip, String _eventType) {
this._eventName = _eventName;
this._eventTime = _eventTime;
this._eventDate = _eventDate;
this._eventLocation = _eventLocation;
this._eventAddress1 = _eventAddress1;
this._eventAddress2 = _eventAddress2;
this._eventCity = _eventCity;
this._eventState = _eventState;
this._eventZip = _eventZip;
this._eventType = _eventType;
}
Thanks #Selvin and #Pier That was part of the issue I had too many parameters and the other part was I didn't realize that you need cursor.getInt() instead cursor.getString for integers.
Thanks again
Related
I have the following function in android studio, which is supposed to return a sqlite cursor.
The problem comes in the selectionArgs argument. Whenever I am passing more than one value to it, it returns a cursor with 0 records.
public Cursor getCursor(String strListWhere, String strTable, String strCols) {
String strColsToReturn = mySqliteHandler.getWhereColNamesFromJsonString(strListWhere);
String strArgs = mySqliteHandler.getWhereColArgsFromJsonString(strListWhere);
Log.d(TAG, "qqqq9: " + strArgs);
String strTableName = strTable;
String[] strColumnsToReturn = { strCols };
String strSelectWhere = strColsToReturn ;
String[] strSelectArgs = { strArgs };
Cursor csrResult = sqLiteDatabase.query(true, strTableName, strColumnsToReturn, strSelectWhere, strSelectArgs, null, null, null, null);
Log.d(TAG, "qqqq9: " + csrResult.getCount());
return csrResult;
}
The value in strColsToReturn is animal_class = ? and province_name = ?
The value in strArgs is Bird, KwaZulu-Natal
So I want it to be animal_class = 'Bird' and province_name = 'KwaZulu-natal'
When I only pass one value it works, for example
The value in strColsToReturn is animal_class = ?
The value in strArgs is Bird
Can anyone assist?
EDIT: the following code works:
public Cursor getCursor(String strListWhere, String strTable, String strCols) {
String strColsToReturn = mySqliteHandler.getWhereColNamesFromJsonString(strListWhere);
List<String> arrWhere = new ArrayList<String>();
arrWhere = mySqliteHandler.getWhereArray(strListWhere);
String[] finalValue = new String[ arrWhere.size() ];
arrWhere.toArray( finalValue );
String strTableName = strTable;
String[] strColumnsToReturn = { strCols };
String strSelectWhere = strColsToReturn ;
Cursor csrResult = sqLiteDatabase.query(true, strTableName, strColumnsToReturn, strSelectWhere, finalValue, null, null, null, null);
return csrResult;
}
The value for strColumnsToReturn should be an array with the names of the columns that you want returned, like:
new String[] {column1, column2, column3}
where column1, column2, column3 are strings.
The value for strSelectWhere should be the string:
"animal_class = ? and province_name = ?"
and the value of strSelectArgs should be a string array with the parameters that you pass to each of the ? placeholders of strSelectWhere:
new String {"Bird", "KwaZulu-Natal"}
You can find more here
When I try to insert my data in my sqlite table, The inserted data is not inserting but the primary key is increasing and row count also increasing. Dont know what the exact problem is. Please some one help what the issue is. I will add my code here. Pls some one help me
here I am adding to database
mylistDataBaseModel = new MyListDataBaseModel();
mylistDataBaseModel.setItemId(0);
mylistDataBaseModel.setItemName("");
mylistDataBaseModel.setItemPrice(0.0);
mylistDataBaseModel.setItemGst(0.0);
mylistDataBaseModel.setCategoryId(0);
mylistDataBaseModel.setItemCategoryName("");
mylistDataBaseModel.setItemPicture("");
mylistDataBaseModel.setItemcount(0);
mylistDataBaseModel.setListName(createList.getText().toString().trim());
mylistDataBaseModel.setListItemcount(0);
mylistDataBaseModel.setItemisAdded(0);
// Log.d("==============", "====" + createList.getText().toString().trim());
sqLiteDatabase = sqlLiteController.getWritableDatabase();
SqliteController.addMyListNameToDataBase(sqLiteDatabase, mylistDataBaseModel);
sqlLiteController.close();
and opearation in database is
public static void addMyListNameToDataBase(SQLiteDatabase sqLiteDatabase, MyListDataBaseModel model) {
ContentValues contentValues = new ContentValues();
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN__ITEM_ID, model.getItemId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_NAME, model.getItemName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PRICE, model.getItemPrice());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_GST, model.getItemGst());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM__CATEGORY_ID, model.getCategoryId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_CATEGORY_DESCRIPTION, model.getItemCategoryName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PICTURE, model.getItemPicture());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_COUNT_ID, model.getItemcount());
Log.d("==============", "====" + model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_NAME, model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_COUNT, model.getListItemcount());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_IS_ADDED, model.getItemisAdded());
sqLiteDatabase.insert(SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null, contentValues);
System.out.println("Cart Summary one row has been inserted");
UserNotification.notify(Constants.NOTIFICATION_MY_LIST_ITEM_ADDED, null);
}
this is my get data from table method
public static ArrayList<MyListDataBaseModel> getMyListData(SQLiteDatabase db) {
ArrayList<MyListDataBaseModel> allMyLists = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from " + SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int localId = cursor.getInt(0);
Log.d("list","====localId====="+localId);
int itemId = cursor.getInt(1);
Log.d("list","====itemId====="+itemId);
String itemName = cursor.getString(2);
Log.d("list","====itemName====="+itemName);
Double itemPrice = cursor.getDouble(3);
Log.d("list","====itemPrice====="+itemPrice);
Double itemGst = cursor.getDouble(4);
Log.d("list","====itemGst====="+itemGst);
int categoryId = cursor.getInt(5);
Log.d("list","====categoryId====="+categoryId);
String catName = cursor.getString(6);
Log.d("list","====catName====="+catName);
String itemPicture = cursor.getString(7);
Log.d("list","====itemPicture====="+itemPicture);
int itemsCount = cursor.getInt(8);
Log.d("list","====itemsCount====="+itemsCount);
String listName = cursor.getString(9);
Log.d("list","====listName====="+listName);
int listItemCount = cursor.getInt(10);
Log.d("list","====listItemCount====="+listItemCount);
int itemIsAdded = cursor.getInt(11);
Log.d("list","====itemIsAdded====="+itemIsAdded);
allMyLists.add(new MyListDataBaseModel(localId, itemId, itemName, itemPrice,
itemGst, categoryId, catName, itemPicture, itemsCount, listName, listItemCount, itemIsAdded));
} while (cursor.moveToNext());
}
}
cursor.close();
return allMyLists;
}
I did a mistake that I got the data with some other column id instead of respected column id . That's my mistake
I cannot understand this problem. I have tried to get the solution from other stackoverflow questions but failed to get the solution. I was not getting this error before. However, now I don't know what's wrong with the code stated below. Please help me with this. I'm stuck with this problem.
public void getAlbumsLists() {
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final String _id = MediaStore.Audio.Albums._ID;
final String album = MediaStore.Audio.Media.ALBUM;
final String album_name = MediaStore.Audio.AlbumColumns.ALBUM;
final String artist = MediaStore.Audio.AlbumColumns.ARTIST;
final String tracks = MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS;
// final String data=MediaStore.Audio.Albums.ALBUM_ID; // NO
// final String id1=MediaStore.Audio.Albums.ALBUM_ID;
final String tit = MediaStore.Audio.Albums.ALBUM; //NO
final String nam = MediaStore.Audio.Albums.ALBUM_KEY; // NO
final String typ = MediaStore.Audio.Media.MIME_TYPE; // NO
final String art = MediaStore.Audio.Albums.ALBUM_ART; //<<<< CAN GET
final String artstkey = MediaStore.Audio.Artists.ARTIST_KEY; //<<<< CAN GET
final String frstyr = MediaStore.Audio.AlbumColumns.FIRST_YEAR; //<<<< CAN GET
final String lstyr = MediaStore.Audio.AlbumColumns.LAST_YEAR; //<<<< CAN GET
final String artstid = "artist_id"; //<<<< CAN GET
final String[] columns = {"*"};
Cursor cursor = getActivity().getContentResolver().query(uri, columns, null, null, null);
// Lists the columns in the cursor
for (String s : cursor.getColumnNames()) {
Log.d("COLUMNS", "Column = " + s);
}
while (cursor.moveToNext()) {
String id = (cursor.getString(cursor.getColumnIndex(_id)));
String name = cursor.getString(cursor.getColumnIndex(album_name));
String artist2 = cursor.getString(cursor.getColumnIndex(artist));
String nr = cursor.getString(cursor.getColumnIndex(tracks));
String x = (cursor.getString(cursor.getColumnIndex(album)));
//String data1=cursor.getString(cursor.getColumnIndexOrThrow(data)); //<<<< NOT A COLUMN
// String id2=cursor.getString(cursor.getColumnIndex(data));
//String title=cursor.getString(cursor.getColumnIndex(tit)); //<<<< NOT A COLUMN
//String name1=cursor.getString(cursor.getColumnIndex(nam)); //<<<< NOT A COLUMN
//String type=cursor.getString(cursor.getColumnIndex(typ)); //<<<< NOT A COLUMN
// AVAIALABLE COLUMNS
String artwork = cursor.getString(cursor.getColumnIndex(art)); //<<<< ADDED
String artistkey = cursor.getString(cursor.getColumnIndex(artstkey)); //<<<< ADDED
String artistid = cursor.getString(cursor.getColumnIndex(artstid)); //<<<< ADDED
String minyear = cursor.getString(cursor.getColumnIndex(frstyr));
String maxyear = cursor.getString(cursor.getColumnIndex(lstyr));
s = new albumInfo(id, name, artist2, nr, artwork, x); // EXCLUDED
albumList.add(s);
cursor.close();
recyclerView1.setAdapter(albumAdapter); // EXCLUDED
}
}
Move cursor.close(); outside the while loop.
Edited..
First time after the while loop iterates the cursor is closed so you need to put it outside while.
I can suggest three improvement scenarios.
You need to move the cursor to first before accessing it for fetching data from the cursor.
You need to close the cursor when nothing is returned or the cursor is null.
Move the cursor close outside of your while loop.
So I would like to recommend you to rewrite the code like following.
// After you have fetched the data from cursor
if(cursor == null) return;
if(cursor.size() == 0) {
cursor.close();
return;
}
for (String s : cursor.getColumnNames()) {
Log.d("COLUMNS", "Column = " + s);
}
// Move the cursor to the first position.
cursor.moveToFirst();
do {
String id = (cursor.getString(cursor.getColumnIndex(_id)));
String name = cursor.getString(cursor.getColumnIndex(album_name));
String artist2 = cursor.getString(cursor.getColumnIndex(artist));
String nr = cursor.getString(cursor.getColumnIndex(tracks));
String x = (cursor.getString(cursor.getColumnIndex(album)));
// ... Other code
} while (cursor.moveToNext());
recyclerView1.setAdapter(albumAdapter); // EXCLUDED
// Move the cursor outside of while loop
cursor.close();
I want to read bookname field in database, but it does not work in this class.
How can I use this class?
public Person readPerson(String bookkname) {
Person person = null;
String[] columns = new String[]{"id" ,"bookname"};
String selection = "bookname=?";
String[] selectionArgs = new String[]{ bookkname};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getWritableDatabase();
Cursor cursor = database.query("tbl_persons", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if(cursor != null && cursor.moveToFirst()) {
int idIndex = 0;
int payIndex = 1;
int lastunitIndex = 2;
int lastlessenIndex = 3;
int booknameIndex = 4;
int maxfreeunitIndex = 5;
long personId = cursor.getLong(idIndex);
String personpay = cursor.getString(payIndex);
String personlastunit = cursor.getString(lastunitIndex);
String personlastlessen = cursor.getString(lastlessenIndex);
String personbookname = cursor.getString(booknameIndex);
String personmaxfreeunit = cursor.getString(maxfreeunitIndex);
person = new Person();
person.setId(personId);
person.setpay(personpay);
person.setlastunit(personlastunit);
person.setlastlessen(personlastlessen);
person.setbookname(personbookname);
person.setmaxfreeunit(personmaxfreeunit);
}
} catch (Exception ex) {
Log.d("Database", "Exception:" + ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return person;
}
I try call readperson class like inner but cant give data from data base or give to me packagename
Please tell to me way of calling this class ?
PersonDatabaseAdapter databaseAdapteer = new PersonDatabaseAdapter(Main2Activity.this);
Person persoon = new Person();
databaseAdapteer = new PersonDatabaseAdapter(this);
username = databaseAdapteer.readPerson(pass.toString());
I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.