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.
Related
I find some tutorials, to create databaseHelper class, which help me to fetch data from database, the data was fetch using List, but somehow i dont know how to populate that list into ArrayList for my gridview and list view, when i try, it says List cannot converted into ArrayList. How can i do that? here my code snippet
databaseHelper.java
public List<Seat> getAllSeats() {
List<Seat> seats = new ArrayList<Seat>();
String selectQuery = "SELECT * FROM " + TABLE_SEATS + "WHERE status=0";
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Seat seat = new Seat();
seat.set_id(c.getInt((c.getColumnIndex("id"))));
seat.set_table_no(c.getString(c.getColumnIndex("table_no")));
// adding to list
seats.add(seat);
} while (c.moveToNext());
}
return seats;
}
index.java
/* LIST SEAT */
final ArrayList<Seat> list_seat = db.getAllSeats();
final GridView gridview_seat = (GridView) findViewById(R.id.gridviewSeat);
gridview_seat.setAdapter(new SeatListAdapter(this, list_seat));
Just convert your list data into array list with following code...
List<Seat> list = db.getAllSeats();
ArrayList<Seat> list_seat = new ArrayList<Seat>(list.size());
list_seat .addAll(list);
ok I just followed an instruction that I should do this to retrieve sql data from database but it just cuts to there so far I have this inside my databasehelper class.
public void getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
}
while (cursor.moveToNext());
}
db.close();
}
So somehow this does is it get all the values of my tables 4th column which contains an int... how do I retrieve the value in my MainActivity and save it in an array of integers?
just add everything in a ArrayList and return the arraylist
simply call the method in your main activty
public ArrayList<Integer> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
ArrayList data= new ArrayList<>();
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
data.add(resource);
}
while (cursor.moveToNext());
}
db.close();
}
return data;
}
Well, as you have it, the variable resource is scoped only to the while loop. Even if it wasn't it would constantly get overwritten on each loop iteration.
Instead, you should declare a collection higher up and Add each value to it during your while loop. You could also redefine your function to return the collection if integers.
public List<int> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
List<int> myVals = new List<int>();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource, null); //null for conditions
if (cursor.moveToFirst())
{
do
{
myVals.Add(cursor.getInt(3));
}
while (cursor.moveToNext());
}
db.close();
return myVals;
}
Also, as a note... string concatenation of a SQL query is a recipe for disaster. Look up SQL Injection and best practices to avoid it before continuing further. It is worth the time to get into good habits early on.
EDIT / ADDENDUM
Unless you also limit your result set returned from your table query, you will be getting every record. The function you have here really has no practical use and would likely cause more problems than any benefits it may have. I would suggest, as an example of a more usable function that returns a specific IconResource based on the IconId:
public int getIconResource(int iconId)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "select IconResource from IconTable where IconId = ?";
PreparedStatement pstmnt = db.prepareStatement(getresource);
pstrmnt.setString(1, iconId);
ResultSet rset = db.executeQuery();
int iconResource;
if (rset.next())
iconResource = rset.getInt("IconResource");
db.close();
return iconResource;
}
Of course, the above is making assumptions of your table structure.
Using the above, in your code elsewhere, you would simply call this function with the IconId and use the output however needed:
int iconResource = getIconResource(5); // returns the IconResource for IconId = 5
The above prevents any possible SQL Injection attacks by using a parameterized query and avoiding the use of dynamic concatenated strings sent to your SQL server.
You may try out the following code:
public List<Integer> getIconResource(String tblName)
{
List<Integer> list = new ArrayList<Integer>();
list.clear();
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
list.add(resource);
}
while (cursor.moveToNext());
}
db.close();
return list;
}
Then call this method in MainActivity and store the List in another Integer type list.
databasehelper dbhelper;
List<Integer> newList = dbhelper.getIconResource("Your tablename");
fot(int i = 0 ; i< newList.size() ; i++){
int yourValue = newList(i);
}
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 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
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