I am trying to get the unique column name and show it as a list adapter.
public String[] getAllUsers() {
String[] contactList = new String[100];
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS, new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE }, null, null, KEY_NAME, null, null, null);
int i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contactList[i] = cursor.getString(1);
i++;
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
The above is method in my database class.
And from mainActivity I call this method
private void updateUserList() {
// TODO Auto-generated method stub
String[] contactList = new String[100];
contactList = db.getAllUsers();
Log.d("User List",contactList[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, contactList);
setListAdapter(adapter);
}
The list is getting updated ,but list is getting repeated as a whole
I don't know if I fully understood your question.
If you want to get columns KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE from all rows in database without KEY_NAME repetitions use this query:
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE },
null, null, null, null, null, null);
In your methods do not use Array instead use ArrayList<String>
public ArrayList<String> getAllUsers() {
ArrayList<String> contactList = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE },
null, null, null, null, null, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contactList.add(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
And updateUserList():
private void updateUserList() {
// TODO Auto-generated method stub
ArrayList<String> contactList;
contactList = db.getAllUsers();
Log.d("User List", contactList.get(0));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, contactList);
setListAdapter(adapter);
}
As you only use the column KEY_NAME from cursor the query can be simplified to return only that column.
Cursor cursor = db.query(true,TABLE_TRANS,
new String[] {KEY_NAME}, null, null, null, null, null, null);
The problem was with initializing the String array as 100. I wrote a method to get the total number of counts and it works fine.
public int getUsersCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(true,TABLE_TRANS, new String[] { KEY_ID ,KEY_NAME, KEY_CASH,KEY_DESC,KEY_DATE }, null, null, KEY_NAME, null, null, null);
//cursor.close();
// return count
return cursor.getCount();}
Related
This is my cursor in database handler class for displaying single coloumn in a list view
public String getAllStringValues() {
ArrayList<String> yourStringValues = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(true, TABLE_PATIENT_GENERAL,
new String[] { KEY_PATIENT_NAME }, null, null, null, null,
null, null);
if (result.moveToFirst()) {
do {
yourStringValues.add(result.getString(result
.getColumnIndex(KEY_PATIENT_NAME)));
} while (result.moveToNext());
} else {
return null;
}
return KEY_PATIENT_NAME;
}
as I m fresher in android please tell me the exact flow and code thanks.
I understand the requery() mechanic, but i do not understand the implementation:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getAllCategorie();
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_NOME // Contract class constant containing the word column name
};
int[] mWordListItems = { R.id.categoria_label };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
}
public void onClick(View view) {
categorie categoria = null;
switch (view.getId()) {
case R.id.add:
categoria = datasource.createCategoria("pluto") ;
break;
case R.id.categoria_label:
break;
}
}
after the categoria = datasource.createCategoria("pluto"); i have to define another:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getApplicationContext(), // The application's Context object
R.layout.single_list_item, // A layout in XML for one row in the ListView
values, // The result from the query
categorieColumns, // A string array of column names in the cursor
mWordListItems, // An integer array of view IDs in the row layout
0); // Flags (usually none are needed)
setListAdapter(adapter);
PollDataSource:
public class pollDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allCategorieColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_PREF, MySQLiteHelper.COLUMN_NOME };
private String[] allSondaggiColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_CATID, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID, MySQLiteHelper.COLUMN_RISPOSTA,
MySQLiteHelper.COLUMN_SELEZIONATA };
public pollDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
public void deleteCategoria(categorie categoria) {
long id = categoria.getId();
System.out.println("Categoria cancellata, id: " + id);
database.delete(MySQLiteHelper.TABLE_CATEGORIE, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public sondaggi createSondaggio(String domanda, int catid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
long insertId = database.insert(MySQLiteHelper.TABLE_SONDAGGI, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
sondaggi newSondaggio = cursorToSondaggi(cursor);
cursor.close();
return newSondaggio;
}
public void deleteSondaggio(sondaggi sondaggio) {
long id = sondaggio.getId();
System.out.println("Sondaggio cancellato, id: " + id);
database.delete(MySQLiteHelper.TABLE_SONDAGGI, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public Cursor getAllCategorie() {
List<categorie> categorie = new ArrayList<categorie>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
categorie categoria = cursorToCategorie(cursor);
categorie.add(categoria);
cursor.moveToNext();
}
// Make sure to close the cursor
// cursor.close();
return cursor;
}
private categorie cursorToCategorie(Cursor cursor) {
categorie categorie = new categorie();
categorie.setId(cursor.getLong(0));
categorie.setPreferita(cursor.getLong(1));
categorie.setNome(cursor.getString(2));
return categorie;
}
private sondaggi cursorToSondaggi(Cursor cursor) {
sondaggi sondaggi = new sondaggi();
sondaggi.setId(cursor.getLong(0));
sondaggi.setDomanda(cursor.getString(1));
sondaggi.setCatid(cursor.getLong(2));
return sondaggi;
}
}
with the same inputs?? so basically I will have the same exact code in two different places of the same class... May I define a... "procedure" or a class? I'm sorry if I'm too naive, I'm a real noob at this :D
the requery cursor method is deprecated. but you're right you have to reload the cursor and then make sure that your new cursor is being presented to your ListView. for a quick 'n dirty solution, I suggest you make your adapter a field. and then use the following method:
private void requery() {
Cursor values = datasource.getAllCategorie();
adapter.changeCursor(values);
}
What it does is remake a cursor. then by calling changeCursor you swap the old cursor for the new one and the old one is closed automatically. at the very least, you save yourself from making a new adapter. The more sophicated approach with all the trim and fixes i suppose would be to implement a CursorLoader which would perform the process automatically when the database content has been changed.
I have an activity and want to get data from my sqlite database. It works, but my activity only retrieves the last row and not the whole column. What can i do to get the whole column?
This is the code in my database:
public String getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
}
c.close();
return name;
}
This is the code in my activities to contact the database:
Database getdata = new Database(this);
getdata.open();
String data = getdata.getName();
getdata.close();
use cursor.moveToFirst() method example given below
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
list.add(cursor.getString(6));
} while (cursor.moveToNext());
}
See, As I said, Without seeing code I m helpless.. And after seeing your code..
You are returning only single String from that function getName() instead it return String[].
Note: this is only pseudo code.. Actual may be different..
public String[] getName() {
int i=0;
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
String name[] = new String[c.getCount()];
c.moveToFirst();
while(!c.isAfterLast()) {
name[i] = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
i++;
}
c.close();
return name;
}
And this one,
Database getdata = new Database(this);
getdata.open();
String data[] = getdata.getName();
getdata.close();
Update your code...
public String[] getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
int i=0;
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
String[] names = new String[c.getCount()];
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
names[i]=name;
c.moveToNext();
i++;
}
c.close();
return names;
}
Database getdata = new Database(this);
getdata.open();
String[] data = getdata.getName();
getdata.close();
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();
}
i want to get the value from the cursor without the SimpleCursorAdapter part.here is the code
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
and the activity side code
cursor = mySQLiteAdapter.queueAll();
from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
i am getting the pkg value correct.but i want to get the values directly from the cursor while removing SimpleCursorAdapter part the code doesn't work.
any help would be appreciated :)
You can get values without declaring adapters. Adapters are need if you want to show the data in the list widgets. So your can be the following:
cursor = mySQLiteAdapter.queueAll();
if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
}
First you must count how many rows are in your table. Then assign that count to variable and it use to create an array. For array size you can use that count variable. Then create a for loop and use that count variable for rounds. After create your query and assign values to your arrays. 100% worked!.
int sqlcount;
Cursor mFetch;
SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
mCount.moveToFirst();
sqlcount = mCount.getInt(0);
mCount.close();
String cname[] = new String[sqlcount];
String cemail[] = new String[sqlcount];
for(int i=0;i<sqlcount;i++) {
mFetch= mydb.rawQuery("select name,email from customer", null);
mFetch.moveToPosition(i);
cname[i] = mFetch.getString(0);
cemail[i] = mFetch.getString(1);
}
mFetch.close();
Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();