In my app i have two different tables with different rows.
I trying to show the two tables on listView with the cursorAdapter.
But cursorAdapter gets query only one table to show.
how can i set the two tables two one cursorAdapter?
here is my code:
MainActivity:
hand = new DbHandler(getActivity());
Cursor c = hand.getDayCursor(workName);
adapterC = new CustomCursorAdapter(getActivity(), c, 0);
lv.setAdapter(adapterC);
From DbHandler:
public Cursor getSettingCursor(String workName) {
Cursor c = null;
try {
open();
c = myDb.query(TABLE_DAY, null, "workName=?", new String[]{workName}, null, null, null, null);
c.getInt(0);
c.getString(1);
c.getFloat(2);
c.getFloat(3);
c.getInt(4);
c.getInt(5);
c.getInt(6);
c.getInt(7);
c.getInt(8);
c.getFloat(9);
c.getFloat(10);
c.getFloat(11);
c.getInt(12);
c.getInt(13);
c.getFloat(14);
c.getFloat(15);
c.getFloat(16);
c.getInt(17);
c.getInt(18);
c.getFloat(19);
c.getFloat(20);
c.getFloat(21);
} catch (Exception e) {
// TODO: handle exception
}finally{
close();
}
return c;
}
public Cursor getDayCursor(String workName) {
Cursor c = null;
try {
open();
c = myDb.query(TABLE_DAY, null, "workName=?", new String[]{workName}, null, null, null, null);
c.getInt(0);
c.getString(1);
c.getFloat(2);
c.getFloat(3);
c.getInt(4);
c.getInt(5);
c.getInt(6);
c.getInt(7);
c.getInt(8);
c.getFloat(9);
c.getFloat(10);
c.getFloat(11);
c.getInt(12);
c.getInt(13);
c.getFloat(14);
c.getFloat(15);
c.getFloat(16);
c.getInt(17);
c.getInt(18);
c.getFloat(19);
c.getFloat(20);
c.getFloat(21);
} catch (Exception e) {
// TODO: handle exception
}finally{
close();
}
return c;
}
cursorAdapter:
#Override
public void bindView(View view, Context context, Cursor cursor) {
int dateDay = cursor.getInt(cursor.getColumnIndex(DbHandler.DATE_DAY));
int dateMonth = cursor.getInt(cursor.getColumnIndex(DbHandler.DATE_MONTH));
int dateYear = cursor.getInt(cursor.getColumnIndex(DbHandler.DATE_YEAR)); .....
}
and one more question, in the Dbhandler ,do i have to put "c.getInt(0);...c.getString(1);.."?
Thank's helpers..
Related
I am trying to populate a RecyclerView with the data in each column.
I want to retrieve all of the values under a column and return it as a List dynamically.
What is the best way to go about this?
Attached is a sample image of the data:
There is a list of tables I am showing in the app, then the user should be able to click on a table name and see a RecyclerView of all of the values under each column with swipeable tabs.
For the image above, the user should see a recyclerview of CreateDate, then swipe over and see a recyclerview of CreatedByTablet, etc.
The problem I am encountering is how to return all of the values in a column, dynamically. I am not that familiar with SQL so how would I go about accomplishing this? And how would the method know to return a List<String> or a List<Integer>?
Here is some code I wrote to attempt this:
// Get all table names
public List<String> getAllTableNames() {
List<String> tableNames = new ArrayList<>();
try {
String query = "SELECT name FROM sqlite_master WHERE type='table'";
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
// Iterate
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
tableNames.add(cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return tableNames;
}
// Get all names of columns inside a table
public List<String> getAllColumnNames(String tableName) {
List<String> names = new ArrayList<>();
try {
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null, null);
String[] columnNames = cursor.getColumnNames();
names = Arrays.asList(columnNames);
} catch (Exception e) {
e.printStackTrace();
}
return names;
}
public int getColumnType(String tableName, String columnName) {
String[] args = { columnName };
try {
int type;
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, args);
Log.d(TAG, "Column Index: " + String.valueOf(cursor.getColumnIndex(columnName)));
type = cursor.getType(cursor.getColumnIndex(columnName));
return type;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public List getAllRows(String tableName, String columnName, int type) {
Log.d(TAG, "Getting all rows");
switch (type) {
case 1:
List<Integer> integerList = createIntegerList(tableName, columnName);
return integerList;
case 3:
List<String> stringList = createStringList(tableName, columnName);
return stringList;
}
return null;
}
private List<Integer> createIntegerList(String tableName, String columnName) {
List<Integer> integerList = new ArrayList<>();
try {
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
int number = cursor.getInt(cursor.getColumnIndex(columnName));
integerList.add(number);
cursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return integerList;
}
private List<String> createStringList(String tableName, String columnName) {
List<String> integerList = new ArrayList<>();
try {
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(columnName));
integerList.add(name);
cursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return integerList;
}
How can I return a list of integer or string (depending of column data type) of all the values in a column inside a table in Sqlite android?
how to solved that error how to get the array list Result sets of queries are returned in Cursor objects. There are some common methods that you will use with cursors
public class DBAdapter {
Context c;
CluecatalogOpenHelper helper;
SQLiteDatabase db;
int flag=0;
public DBAdapter(Context ctx) {
super();
this.c = ctx;
helper=new CluecatalogOpenHelper(ctx);
}
public void openDB(){
db=helper.getWritableDatabase();
}
public void closeDB(){
db.close();
}
public void addRow(String name, byte[] data1) {
openDB();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("object",data1);
db.insert("topsearch", null, values);
closeDB();
}
public void deleteRow(String name)
{
try {
db.execSQL("delete from topsearch where name = (?)",new String[]{""+name});
} catch (SQLException e) {
e.printStackTrace();
}
}
public Cursor showData(){
try{
Cursor c = db.query("topsearch", new String[]{"name","object"}, null, null,null, null,null);
return c;
}catch(Exception e) {
e.printStackTrace();
return null;
}}}
how to solved that error
I'm not sure exactly what you're asking, but if you're asking how do you pull out the results out of a Cursor object and into a List you would do it like this:
List list = new ArrayList();
Cursor c = db.query("topsearch", new String[]{"name","object"}, null, null,null, null,null);
while(c.moveToNext())
{
//populate your return object from the cursor here
//i'm just making this part up
Obj obj = new Obj();
obj.setName(c.getString(0)); //0 being the column index
list.add(obj);
}
return list;
Goodyear to everyone.
well, this is the question, i would like to understand the logic of the listview, and how to retrieve informations on the item clicked in it.
i have done and customized a bunch of tutorials to do this app, and now i'm trying to figure out what i'm doing in this ugly and dirty code.
i have a activity where it lists a series of questions, after you select a category, selecting a question, brings you to the next activity, where some answers are listed and the user could select one. I would like to list ONLY those questions that the user has to answer, instead of all, so i've added a new column to the categories table called "fatta" - "done" in english that i would like to change to 1 when the user clicks the answer of that question.
so the idea was to pass the id of the question, so in the activity where i list al the answers, i could update both the answers and the questions tables, to set to 1 the "done field".
but something goes wrong. here's the code:
The Activity:
public class sondaggioActivity extends ListActivity{
private static final String strdomanda = null;
private pollDataSource datasource;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindomanda);
long domanda = getIntent().getExtras().getLong("domanda");
TextView text = (TextView) findViewById(R.id.domanda);
String strdomanda = Long.toString(domanda);
// text.setText(strcategory);
datasource = new pollDataSource(this);
datasource.open();
Cursor values = datasource.getTestoRisposte(strdomanda);
// data? if (values.moveToFirst())
// System.out.println(values.getString(values.getColumnIndex("sondid")));
String[] categorieColumns =
{
MySQLiteHelper.COLUMN_RISPOSTA // 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);
//values.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
datasource.setRispostaSelezionata(Long.toString(id));
datasource.setDomandaFatta(strdomanda);
datasource.close();
finish();
}
}
as you can see here at the end there is the onListItemClick where i use the strdomanda that i have defined at the top as private static final String strdomanda = null; the datasource is like this:
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_WEBID,MySQLiteHelper.COLUMN_FATTA, MySQLiteHelper.COLUMN_DOMANDA };
private String[] allRisposteColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_SONDID,MySQLiteHelper.COLUMN_WEBID, 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, int webid) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DOMANDA, domanda);
values.put(MySQLiteHelper.COLUMN_CATID, catid);
values.put(MySQLiteHelper.COLUMN_WEBID, webid);
values.put(MySQLiteHelper.COLUMN_FATTA, "0");
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;
}
public Cursor getDomanda(String id) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_ID + "=?",
new String[] { id }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
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));
sondaggi.setwebid(cursor.getLong(3));
return sondaggi;
}
public Cursor getAllDomandeCategoria(String catid) {
List<sondaggi> domande = new ArrayList<sondaggi>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SONDAGGI,
allSondaggiColumns,
MySQLiteHelper.COLUMN_CATID + "=?",
new String[] { catid }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
sondaggi sondaggio = cursorToSondaggi(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
public Cursor getTestoRisposte(String strdomanda) {
List<testo_risposte> domande = new ArrayList<testo_risposte>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_TESTORISPOSTE,
allRisposteColumns,
MySQLiteHelper.COLUMN_SONDID + "=?",
new String[] { strdomanda }, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
testo_risposte sondaggio = cursorToTestoRisposte(cursor);
domande.add(sondaggio);
cursor.moveToNext();
}
return cursor;
}
private testo_risposte cursorToTestoRisposte(Cursor cursor) {
testo_risposte testo_risposte = new testo_risposte();
testo_risposte.setId(cursor.getLong(0));
testo_risposte.setCatid(cursor.getLong(1));
testo_risposte.setWebid(cursor.getLong(4));
testo_risposte.Setselezionata(cursor.getLong(2));
testo_risposte.setDomanda(cursor.getString(3));
return testo_risposte;
}
public void setRispostaSelezionata(String id) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_SELEZIONATA, "1");
database.update(MySQLiteHelper.TABLE_TESTORISPOSTE,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { id });
}
public void setDomandaFatta(String strdomanda) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_FATTA, "1");
database.update(MySQLiteHelper.TABLE_SONDAGGI,values,MySQLiteHelper.COLUMN_ID + "=?", new String[] { strdomanda });
}
}
but as i run the activity, only the first updadate gone good, the other one, the one with which i would like to "deactivate" the question... does nothing... i suppose that the way i pass the strdomanda is not the good way. Any help? Advice? thanks in advance.
SOLVED:
i have mistaken this line:
private static String strdomanda = null;
I have deleted the Final property and i have deleted the other declaration of the same variable...
now it works.
public Cursor getBiggestInTheColumn()
{
return db.query(HEADER_TABLE, null,"MAX(key_Division)", null, null, null, null);
}
and I call this method as Cursor cc=db.getBiggestInTheColumn();
But it forcefully close the application.Please help me
You can use simpleQueryForLong and cast it accordingly.
public int getMaxColumnData() {
mDb = mDbManager.getReadableDatabase();
final SQLiteStatement stmt = mDb
.compileStatement("SELECT MAX(column) FROM Table");
return (int) stmt.simpleQueryForLong();
}
public int getBiggestInTheColumn()
{
Cursor c = db.query(HEADER_TABLE, null,new String[] {"MAX(key_Division)"}, null, null, null, null);
try {
c.moveToFirst();
return c.getInt(0);
} finally {
c.close();
}
}
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.