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.
I am new to android programming. I am having a little issue on how to retrieve a single record while using Inner joins. From research I know how to do it with one table e.g
public Shop getShop(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SHOPS, new String[] { KEY_ID,
KEY_NAME, KEY_SH_ADDR }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Shop contact = new Shop(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return shop
return contact;
}
But I am at a loss when I have to consider three different tables. I have been able to retrieve all records, currently my code to retreive a single record is below. I have been able to replace ? with a corresponding id and it works but I obviously do not want to have that static.
getTeam method
//Getting Single Team
public List < Team > getTeam() {
List < Team > teamList = new ArrayList < Team > ();
// Select All Query
String selectQuery = "SELECT teams.id, teams.team_name, teams.image, teams_vs_leagues.points, leagues.league_name " +
"FROM teams_vs_leagues " +
"INNER JOIN teams " +
"ON teams_vs_leagues.team_id = teams.id " +
"INNER JOIN leagues " +
"ON teams_vs_leagues.league_id = leagues.id " +
"WHERE teams.id = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Team team = new Team();
team.setId(Integer.parseInt(cursor.getString(0)));
team.setTeamName(cursor.getString(1));
team.setPath(cursor.getString(2));
team.setPoints(Integer.parseInt(cursor.getString(3)));
team.setLeagueName(cursor.getString(4));
// Adding team to list
teamList.add(team);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return team list
return teamList;
}
Team class
public class Team {
String team_name, path, league_name;
int id, league_id, points;
public Team(int keyId, String team_name, String path,
int points, String league_name) {
this.id = keyId;
this.team_name = team_name;
this.path = path;
this.points = points;
this.league_name = league_name;
}
public Team() {}
public Team(int keyId) {
this.id = keyId;
}
public int getId() {
return id;
}
public void setId(int keyId) {
this.id = keyId;
}
public int getLeagueId() {
return league_id;
}
public String getTeamName() {
return team_name;
}
public String getLeagueName() {
return league_name;
}
public void setLeagueName(String league_name) {
this.league_name = league_name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void setTeamName(String team_name) {
this.team_name = team_name;
}
public void setLeague_id(int league_id) {
this.league_id = league_id;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
Since you are using placeholder
"WHERE teams.id = ?";
in your query , you need to pass selection arguments in rawQuery() so that during the execution of your query , the placeholder will be replaced by the actual value.
Cursor cursor = db.rawQuery(selectQuery, new String[]{id});//"id" is the value which you want to pass in place of "?". You can hardcode it or you can pass it all the way to getTeam()
Check this .
I have jokes.db database. This database file imported from using this article., http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/. Now i have Jokes.db in to /data/data/a.b.c/database/Jokes.db. In this database , I have two table NepaliJokes and EnglishJokes. So Now I want to retrive this nepali and english jokes and display in to textview, But I have done following code but couldnot more idea behind How to retrieve data from database.
public class FunnyJokes extends Activity implements View.OnClickListener {
private SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
Button back;
super.onCreate(savedInstanceState);
setContentView(R.layout.displayjoks1);
back = (Button) findViewById(R.id.back_btn);
back.setOnClickListener(this);
DataBaseHelper helper = new DataBaseHelper(this);
database = helper.getWritableDatabase();
loadJokes();
}
private void loadJokes() {
//jok=new ArrayList<String>();
/*Cursor c = database.query("SELECT title,body" +
" FROM " + 'tableName'
+ " WHERE category=1;",
null);*/
Cursor c = database.query("NepaliJokes",
null, null, null, null, null, null);
c.moveToPosition(0);
TextView tv= (TextView) findViewById(R.id.textView1);
tv.append(c.getString(1));
c.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_btn:
FunnyJokes.this.finish();
break;
default:
break;
}
}
}
I also use the database file import from in DDMS->fileExploer. I import database file Pull mobile icon from left of file explorer section.
To read values from the table:
Create a cursor to read data from the database.
Write the following function.
public Cursor retrieveRecords(int category)
{
Cursor c = null;
c = db.rawQuery("select title,body from tablename where category=" +category, null);
return c;
}
Now get the values from the cursor.
public void getDataFromDatabase()
{
try
{
Cursor cursor = null;
db.OpenDatabase();
cursor = db.retrieveRecords();
if (cursor.getCount() != 0)
{
if (cursor.moveToFirst())
{
do
{
titleArrayList.add(cursor.getString(cursor.getColumnIndex("title")));
bodyArrayList.add(cursor.getString(cursor.getColumnIndex("body")));
} while (cursor.moveToNext());
}
db.closeDatabase();
}
cursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I an using the fallowing class for manage DataBase in my application.
public class PersonDbHelper {
public class Row_DocumentTable extends Object {
public int rwo_id;
public String dockey;
public String docid;
public String size;
public String status;
public String name;
public String product_discription;
public String type;
public String publisher;
public String version;
public String filepathurl;
public String basepage;
public String copypaste;
public String save;
public String print;
public String printablepage;
public String nonprintablepage;
public String search;
public String watermarkimageurl;
public String expiry;
public String versiondescription;
public String update_available;
public String localfilepath;
}
public class Row_CategoriesTable extends Object {
public String dockey;
public String category_id;
public String category_name;
}
private static final String DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.DOCUMENTDETAIL";
private static final String DROP_CATEGORIES_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.CATEGORIES";
private static final String DATABASE_CREATE_DOCUMENTDETAIL = "create table DOCUMENTDETAIL(row_id integer primary key autoincrement, dockey text , "
+ "docid text not null,"
+ "size text not null,"
+ "status text not null,"
+ "name text not null,"
+ "product_discription text not null,"
+ "type text not null,"
+ "publisher text not null,"
+ "version text not null,"
+ "filepathurl text not null,"
+ "basepage text not null,"
+ "copypaste text not null,"
+ "save text not null,"
+ "print text not null,"
+ "printablepage text not null,"
+ "nonprintablepage text not null,"
+ "search text ,"
+ "watermarkimageurl text not null,"
+ "expiry text not null,"
+ "versiondescription text not null,"
+ "update_available text not null,"
+ "localfilepath text not null"
+ ");";
private static final String DATABASE_CREATE_CATEGORIES = "create table CATEGORIES(_id integer primary key autoincrement, "
+ "dockey text ,"
+ "category_id text ,"
+ "category_name text"
+ ");";
private static final String DATABASE_NAME = "CONTENTRAVENDB";
private static final String DATABASE_TABLE1 = "CATEGORIES";
private static final String DATABASE_TABLE2 = "DOCUMENTDETAIL";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public PersonDbHelper(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
db.execSQL(DATABASE_CREATE_DOCUMENTDETAIL);
db.execSQL(DATABASE_CREATE_CATEGORIES);
}
public void dropAllTable(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
// db.execSQL(DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE);
// db.execSQL(DROP_CATEGORIES_TABLE_FROM_DATABASE);
db.delete(DATABASE_TABLE1, null, null);
db.delete(DATABASE_TABLE2, null, null);
close();
}
public PersonDbHelper(Context ctx, String abc) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
}
public PersonDbHelper() {
}
public void close() {
db.close();
}
public void createRow_InDocumentDetailTable(String dockey, String docid,
String size, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available,
String localfilepath) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("docid", docid);
initialValues.put("size", size);
initialValues.put("status", status);
initialValues.put("name", name);
initialValues.put("product_discription", product_discription);
initialValues.put("type", type);
initialValues.put("publisher", publisher);
initialValues.put("version", version);
initialValues.put("filepathurl", filepathurl);
initialValues.put("basepage", basepage);
initialValues.put("copypaste", copypaste);
initialValues.put("save", save);
initialValues.put("print", print);
initialValues.put("printablepage", printablepage);
initialValues.put("nonprintablepage", nonprintablepage);
initialValues.put("search", search);
initialValues.put("watermarkimageurl", watermarkimageurl);
initialValues.put("expiry", expiry);
initialValues.put("versiondescription", versiondescription);
initialValues.put("update_available", update_available);
initialValues.put("localfilepath", localfilepath);
db.insert(DATABASE_TABLE2, null, initialValues);
}
public void createRow_InCategorieTable(String dockey, String category_id,
String category_name) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("category_id", category_id);
initialValues.put("category_name", category_name);
db.insert(DATABASE_TABLE1, null, initialValues);
}
public void deleteRow_FromDocumentDetailTable(long rowId) {
db.delete(DATABASE_TABLE2, "_id=" + rowId, null);
}
public List<Row_DocumentTable> fetchAllRows_FromDocumentDetailTable() {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL";
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "row_id","dockey","docid","size", "status", "name",
// "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry",
// "versiondescription","update_available","localfilepath"
// }, null, null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_DocumentTable> fetchAllRows_Of_Single_Type(String argtype) {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL where type='" + argtype
+ "'";
Cursor c = db.rawQuery(sql, null);
// Cursor c=db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"
// }, "type=PDF", null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_CategoriesTable> fetchAllRows_FromCategorieTable(
String argsql) {
ArrayList<Row_CategoriesTable> ret = new ArrayList<Row_CategoriesTable>();
try {
String sql = argsql;
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(true,DATABASE_TABLE1, new String[] {
// "dockey","category_id","category_name"
// }, null,null,null, null, null,null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_CategoriesTable row = new Row_CategoriesTable();
row.dockey = c.getString(0);
row.category_id = c.getString(0);
row.category_name = c.getString(0);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public Row_DocumentTable fetchRow_FromDocumentDetailTableByDocKey(
String dockey) {
Row_DocumentTable row = new Row_DocumentTable();
String sql = "select * from DOCUMENTDETAIL where dockey='" + dockey
+ "'";
try {
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"},
// "dockey=" + dockey, null, null,
// null,null,"name desc");
if (c.getCount() > 0) {
c.moveToFirst();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
return row;
} else {
row.docid = null;
row.dockey = row.name = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
return row;
}
public void updateRow_InDocumentDetailTableByDocKey(String dockey,
String docid, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available) {
ContentValues args = new ContentValues();
args.put("dockey", dockey);
args.put("docid", docid);
args.put("status", status);
args.put("name", name);
args.put("product_discription", product_discription);
args.put("type", type);
args.put("publisher", publisher);
args.put("version", version);
args.put("filepathurl", filepathurl);
args.put("basepage", basepage);
args.put("copypaste", copypaste);
args.put("save", save);
args.put("print", print);
args.put("printablepage", printablepage);
args.put("nonprintablepage", nonprintablepage);
args.put("search", search);
args.put("watermarkimageurl", watermarkimageurl);
args.put("expiry", expiry);
args.put("versiondescription", versiondescription);
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public Cursor GetAllRows() {
try {
return db.query(DATABASE_TABLE2, new String[] { "dockey", "docid",
"status", "name", "product_discription", "type",
"publisher", "version", "filepathurl", "basepage",
"copypaste", "save", "print", "printablepage",
"nonprintablepage", "search", "watermarkimageurl",
"expiry", "versiondescription" }, null, null, null, null,
null);
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
return null;
}
}
public void updateRow_InDocumentDetailTableByDocKey_UpdateAvl(Context ctx,
String dockey, String update_available) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public void updateRow_InDocumentDetailTableByDocKey_LocalFilePath(
Context ctx, String dockey, String argLocalFilePath) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("localfilepath", argLocalFilePath);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
}
I have two table and apply all the query insert update delete and createtable select using the code it is working fine.
I hope this is help.
First of all don't use tv.append instead use setText because if u use append then ur next joke will be append to the previous one and textView show the jokes as you click the button
Actually the answere is long enough so
I have written a ansere in my blog please see the link the code will do exactly what you are lokking for but i just made one table you can add more table similarly.
You can visit HERE