Android - SQLite rawQuery Listview - android

I am trying to query all the users data that belong to him uniquely. through FK_ID of the user in the notes table.
// Listing all notes
public Cursor listNotes() {
SQLiteDatabase db = help.getReadableDatabase();
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Count how many Notes user has
public int NoteCount() {
String countQuery = "SELECT * FROM " + help.NOTE_TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public void editNote(long id, String title, String body) {
ContentValues edit = new ContentValues();
edit.put(help.COLUMN_TITLE, title);
edit.put(help.COLUMN_BODY, body);
open();
db.update(help.NOTE_TABLE, edit, help.NOTES_ID + "=" + id, null);
close();
}
// Deleting single note
public void deleteNote(long id) {
open();
db.delete(help.NOTE_TABLE, help.NOTES_ID + "=" + id, null);
close();
}
}
I have a tab that will then return all the users data uniquely to him. This tab is a fragment.the Method populateList() will be called onCreateView
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
This is a null pointer. Am i passing the data wrong
Cursor cursor = control.listNotes();

Your listNotes method should look like :
public Cursor listNotes(long userId) {
Cursor c = getActivity().getContentResolver().query(yourTodoTableURI, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, help.COLUMN_USER_ID + " = ?", new String[]{String.valueOf(userId)} , null);
return c;
}

try this:
public List<String> getAllTask(int userID){
String query = "Select * from tablename where ID =" + userID;
cursor = db.query(); //do your code here
int id = cursor.getInt(cursor.getColumnIndex(tablename.ID));
List<String> task = new ArrayList<String>();
String query = "Select * from tableTask where ID =" + id";
cursor = db.query(); //
if (cursor != null) {
cursor.movetofirst();
// do your code here
do{
String task = cursor.get......
task.add(task);
}while(cursor.movetonext);
}
return task;
}

Related

Return String[] From database

I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}

Sqlite query for multiple result

i want to query for data in sqlite, but in the case where 2item have the same name.. still it return only result... what should i add in this code?
public String getItemNameRbPrice(long lprice) throws SQLException{
String[] column = new String[]{Pro_ID, Pro_Name, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Price + "=" + lprice, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
Log.v(name,name + ("zz"));
return name;
}
return null;
}
Try sending List<String>
public List<String> getItemNameRbPrice(long lprice) throws SQLException{
String[] column = new String[]{Pro_ID, Pro_Name, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Price + "=" + lprice, null, null, null, null);
List<String> lst = new ArrayList<String>();
if (cursor.moveToFirst()) {
do {
String name = c.getString(1);
lst.add(name);
Log.v(name,name + ("zz"));
} while (cursor.moveToNext());
}
return lst;
}

update two tables on click inside a listview and passing parameters for the update

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.

update the listview after inserting a new record with simpleCursorAdapter - requery()

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.

Insert first column spinner into a table

I've a table (Categories) wich two columns (_id, name).
I've a spinner that shows the column name.
Now, I need to insert the column: "_id" into another table...but I don't know how to do it.
Any suggestions?
I paste the code I'm using:
public Cursor recuperaCategoria()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "Categorias";
String[] columns = {"_id","Nombre"};
return db.query(tableName, columns, null, null, null, null, null);
}
public void recCatSpinner() {
final Spinner addCatSpinner = (Spinner) findViewById(R.id.spIdCategoria);
catCursor = recuperaCategoria();
catCursor.moveToPosition(1);
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
addCatSpinner.setAdapter(catAdapter);
if (catCursor.moveToFirst()) {
do {
catAdapter.add(catCursor.getString(1));
Valor = catCursor.getString(1);
Log.v("valor Add Cat 100", Valor);
}
while (catCursor.moveToNext());
int id = catCursor.getInt(0);
String name = catCursor.getString(1);
Log.v("Dentro cursor","1");
if (db != null) {
Toast.makeText(getBaseContext(),catCursor.getString(0),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(catCursor);
//catCursor.close();
addCatSpinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view2, int pos, long id) {
//recID();
valor = parent.getItemAtPosition(pos).toString();
Log.v("valor Add Cat", valor);
}
public void onNothingSelected(AdapterView<?> parent) {
// view.setText("nada");
}
});
catCursor.close();
}
I'd like that when I select one item from spinner (it shows the column "Nombre"), I save into one variable the first column from cursor "_id".
Read values to collection then write a script to insert them to another taBLE
SQLiteDatabase db = getReadableDatabase();
String[] columns = { _id };
String selection = "column_name" + "=?";
String orderBy = "_id ASC";
String[] selectionArgs = new String[] { "something" };
String groupBy = null;
String having = null;
Cursor cursor = db.query("table_name", "columns", selection, selectionArgs, groupBy, having, orderBy);
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
// Add values to a collection
}
if(db.isOpen()) db.close();
SQLiteDatabase db = getWritableDatabase();
for(int id : idCollection) {
ContentValues values = new ContentValues();
values.put("_id", id);
try {
int id = db.insertOrThrow(TABLE_NAME, null, values);
}
catch (SQLException sqlEx) {
// do something with exception
}
}
if(db.isOpen()) db.close();

Categories

Resources