I have certain data in sqlite and want to fetch the data into an array of string, I am getting the first column successfully but cant able to fetch the next column data. Here is my code.
SQLiteDatabase db = contactsdbHelper.getWritableDatabase();
//db.openDatabase(path, factory, flags)
int columnIndex = 1; // Whichever column your float is in
Cursor cursor1= getData();
String[] values=new String[cursor.getCount()+1];
try{
if(cursor1.moveToFirst())
{
for(int i=0;i<cursor1.getCount();i++ )
{
values[i]=cursor1.getString(columnIndex);
//Log.i("HI", "piyush");
Log.i("StartTime"+i, values[i]);
cursor1.moveToNext();
}
}
}
catch(ArrayIndexOutOfBoundsException e){
Log.i("Exception Generated", e.toString());
}
String[] values1=new String[cursor.getCount()+1];
try{
if(cursor1.moveToNext())
{
for(int i=0;i<cursor1.getCount();i++ )
{
values1[i]=cursor1.getString(columnIndex+1);
Log.i("EndTime"+i, values[i]);
cursor1.moveToNext();
}
}
}
catch(ArrayIndexOutOfBoundsException e){
Log.i("Exception Generated", e.toString());
}
Why not fill both arrays at once?
SQLiteDatabase db = contactsdbHelper.getWritableDatabase();
//db.openDatabase(path, factory, flags)
int columnIndex = 1; // Whichever column your float is in
Cursor cursor1= getData();
String[] values=new String[cursor.getCount()+1];
String[] values1=new String[cursor.getCount()+1];
try{
if(cursor1.moveToFirst())
{
for(int i=0;i<cursor1.getCount();i++ )
{
values[i]=cursor1.getString(columnIndex);
values1[i]=cursor1.getString(columnIndex+1);
Log.i("StartTime"+i, values[i]);
cursor1.moveToNext();
}
}
}
catch(ArrayIndexOutOfBoundsException e){
Log.i("Exception Generated", e.toString());
}
But that whole thing looks kinda rubbish ... what are you trying to achieve?
You will need to call moveToFirst() on the Cursor again before you can start reading the second column.
Specifically the second if should be:
if (cursor1.moveToFirst())
Edit - usually data is in a database for a reason: you don't want to fetch it all into memory in one big array most of the time.
Could you be looking for a CursorAdapter and ListView combination to display the data in a list?
Try reading the column values by their column name.
Cursor cursor = ...
if(cursor.moveToFirst()) {
do {
values[i] = cursor.getString(cursor.getColumnIndex("columnName"));
values1[i] = cursor.getString(cursor.getColumnIndex("otherColumnName"));
} while(cursor.moveToNext());
}
where "columnName" and "otherColumnName" are the names of the columns of your table which you want to fill into the arrays.
Cursor cur = db.query(TABLENAME, null, null, null, null, null, null);
cur.moveToFirst();
int a[] = new int[100];
for (int i = 0; i < cur.getCount(); i++)
{
a[i] = cur.getInt(0);
cur.moveToNext();
}
Here is my code to return all the data in the table in list. But, it is not working.
I have called this method from CheckData class which in turn is called by main class via intent.
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
int x = 0;
if (cursor.moveToFirst())
{
do
{
String[] b1 = new String[]
{
cursor.getString(1),
cursor.getString(2)
};
list.add(b1);
x = x + 1;
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
cursor.close();
return list;
}
My database contains 3 columns - id(integer primary key), symbol(text) and company_name(text). My database name is AppDB and table name is scrip.
Related
I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
public String[] getAllDescription() {
db = this.getReadableDatabase();
cursor = db.query(NOTIFICATIONTABLE, new String[]{"notification_id", "notification_title",
"notification_description", "notification_isread", "date"}, null, null, null,
null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
result[i] = cursor.getString(cursor.getColumnIndex("notification_description"));
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
db.close();
}
return result;
}
this is my code currently i am getting from 0 to n data in staring array i want to get in reverse array data from n to 0 so that i can Print please suggest me how i will get data
Try this method :
public ArrayList<String> getAllDescription()
{
ArrayList<String> array_list = new ArrayListString>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * " + " FROM " + NOTIFICATIONTABLE+ " DESC;", null);
res.moveToFirst();
while (res.isAfterLast() == false)
{
array_list.add(hashmap);
res.moveToNext();
}
return array_list;
}
Or If you want to reverse arrayList then you can also do it By just a single line of code .
Collections.reverse("yourArrayList");
Hope it will help you.
i am getting from 0 to n data in staring array i want to get in
reverse array data from n to 0
Why not using ASC or DESC in db query to get result in sequence as want according to notification_description column.
do it as:
cursor = db.query(NOTIFICATIONTABLE,
new String[]{"notification_id",
"notification_title",
"notification_description",
"notification_isread",
"date"}, null, null, null,
null, "notification_description DESC");
You can insert the data from end of theString[]...
public String[] getAllDescription() {
db = this.getReadableDatabase();
cursor = db.query(NOTIFICATIONTABLE, new String[]{"notification_id", "notification_title",
"notification_description", "notification_isread", "date"}, null, null, null,
null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
///////////////////////
result[(cursor.getCount()-1)-i] = cursor.getString(cursor.getColumnIndex("notification_description"));
///////////////////////
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
db.close();
}
return result;
}
public String[] getNewsLink(String prodcuttye) {
Cursor cursor = mDb.query(SQLITE_TABLE, new String[] { "productname" }, "ProdctType='"
+ prodcuttye + "'", null, null, null, null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
result[i] = cursor.getString(cursor.getColumnIndex("productname"));
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
mDb.close();
}
return result;
}
This function for fetch data in String array i am trying to excute this Query am getting data when i am call the in Sqlite browser[ select productname from MyShopingTable where ProdctType= 'Basmati Rice'] But when i try to run this Query in function i am getting cursor count 0 so i am unable to get data please tell me where am doing wrong please suggest me
Try changing your query like following :
Cursor c = mDb.query("SELECT * FROM MyShopingTable where ProdctType = ?",new String[]{prodcuttye})
See if that works in your case...
Please help me with following, I have a database which contain strings ( e.g. fotonames ).
And I want to read entire fotonames column into an arraylist.
How can I do this?
public Cursor getfotoname() throws SQLException
{
String getRT = "SELECT fotonames from "+ TABLE_NAME+";";
Cursor mCur = sqldb.rawQuery(getRT, null);
return mCur;
}
Now when you call
Cursor mCursor=null;
mCursor= DatabaseObject.getfotoname();
ArrayList<WhateverTypeYouWant> mArrayList = new ArrayList<WhateverTypeYouWant>();
for(mCursor.moveToFirst(); mCursor.moveToNext(); mCursor.isAfterLast()) {
// The Cursor is now set to the right position
mArrayList.add(mCursor.getWhateverTypeYouWant(WHATEVER_COLUMN_INDEX_YOU_WANT));
}
Have a look at this tutorial will help you
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/
this is where you can lear how to fetch all values from one column
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/3/#getrowasarray
or otherway is
fire query like this
public Cursor columnValues() throws SQLException{
// TODO Auto-generated method stub
Cursor mCursor = db.query(Course_Info_Table,
new String[] {Column1 , column2 },
null,null, null, null, null);
//Cursor mCursor = mDb.rawQuery("Select",null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
and receive it like
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list12 = new ArrayList<String>();
cursor = dbm.columnValueofCourse();
cursor.moveToFirst();
startManagingCursor(cursor);
for (int i = 0; i < cursor.getCount(); i++) {
String reciv = cursor.getString(cursor
.getColumnIndex("column1"));
String reciv3 = cursor.getString(cursor
.getColumnIndex("column2"));
list1.add(reciv);
list2.add(reciv3);
cursor.moveToNext();
}
The code to returns all the data in the table in list.But this isn't working.
I've called this method from CheckData class which is called by main class
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(1),
cursor.getString(2) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
My database contains 3 columns - id(integer primary key), symbol(text) and company_name(text).
My Data Base name is AppDB and table name is scrip.
Here are the good tutorial to LEARN use of Android-SQLite.
so,I also advise you the same As I answered here