I got two tables "links" and "categories" how do i get 4 colunms from links and one from categories?
**Links**
_id
link_title
link_desc
link_date
**Categories**
_id
cat_title
cat_desc
i need a single row like this
_id, link_title, link_desc, link_date, cat_title
and then use this in my cursor
private void fillData() {
Cursor linkCursor = mDbHelper.fetchAllLinks();
startManagingCursor(linksCursor);
String[] from = new String[]{ DbAdapter.LINK_TITLE, DbAdapter.LINK_DESC, DbAdapter.LINK_DATE, DbAdapter.LINK_ROWID, DbAdapter.CAT_DESC };
int[] to = new int[]{ R.id.title, R.id.content, R.id.date, R.id.headid, R.id.catdesc };
SimpleCursorAdapter links = new SimpleCursorAdapter(this, R.layout.linkrow, linkCursor, from, to);
//links.setViewBinder(new MyViewBinder());
setListAdapter(links);
}
I tried SQL UNION but it dont worked.
What you want is called a join. But to do this you need to either give two ids, or add a category_id column to the Links-table.
SELECT
l._id,
link_title,
link_desc,
link_date,
cat_title
FROM Links l, Categories c
WHERE l._id = ?
AND c._id = ?
or after adding the column
SELECT
l._id,
link_title,
link_desc,
link_date,
cat_title
FROM Links l
LEFT JOIN Categories c ON c._id = l.link_cat_id
WHERE l._id = ?
More information:
w3schools.com/sql - Tutorial about SQL. Generic SQL which works for most database engines.
sqlite.com/lang.html - Syntax reference for SQLite, which is used in Android.
Related
I have a listView populated with data from my db. I use a simpleCursorAdapter to show the values.
I have a table where i can add lessons : English, french...
In another table, i can create lessons developped (i add date of beginning and end, which days, a theme for the lesson). I must provide the lesson as a FK.
When I add a lesson, in my listView i want to show per example : English - Reading, but it shows 1 - Reading. Because 1 is the value i store in my 2nd table.
How can I change 1 to English ?
Here's my code :
Cursor cursor = dbhelper.getAllCours();
String[] from = { "branche_cours", "designation" }; //here 'branche_cours' is the lesson i store as an INT, it's the FK so
int[] to = { R.id.text_branche_cours, R.id.text_designation };
adapter = new SimpleCursorAdapter(this, R.layout.list_row, cursor, from, to, 0);
lvCours.setAdapter(adapter);
adapter.notifyDataSetChanged();
The method i use getAllCours()
public Cursor getAllCours()
{
//from here, i retrieve the ID, designation and branche_cours
String Query = ("select ID as _id, date_debut, date_dernier, dixieme_point, " +
"demi_point, description, designation, lundi, mardi, mercredi, jeudi," +
" vendredi, samedi, branche_cours from " + TABLE_COURS);
Open();
Cursor cursor = db.rawQuery(Query, null);
return cursor;
}
How can I link that int to the real value ( so how can the '1' become 'English')?
One solution would be to perform an SQL JOIN operation to fetch the data from both tables:
So the SQL query should be something thing like:
SELECT table1.branche_cours, table2.designation
FROM table1
INNER JOIN table2 ON table1.ID=table2.ID;
To look up a value in another table, you can use a correlated subquery:
SELECT ID AS _id,
...,
samedi,
(SELECT name
FROM other_table
WHERE other_table.id = cours.branche_cours
) AS branche_cours
FROM cours;
I have a db with table "mytable" having 2 colums "id","sampletext"
I want to query distinct values of sampletext and feed to a Spinner using SimpleCursorAdapter.
here is what is tried
String[] cols=new String[]{"sampletext"};
int[] lbls=new lbls[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", cols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, cols,lbls,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
When i run this i get error at line 4 : id does not exist.
when i changed first line to "id" the spinner got populated with id values.
But i need "sampletext", what am i doing wrong?
Appreciate any suggestions
what am i doing wrong
you didnt read documentation ...
there are two arrays of string with columns: first in used in query, second one in Adapter constructor(you used only one array for both)
first one tells sqlite which columns should be taken to Cursor, second tells Adapter which ones should be showed/mapped to Views in single row...
Next CursorAdapter needs Cursor with column named _id
So now it's pretty obvious that we should do smthin like this:
String[] queryCols=new String[]{"_id", "sampletext"};
String[] adapterCols=new String[]{"sampletext"};
int[] adapterRowViews=new int[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", queryCols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, adapterCols, adapterRowViews,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
Here's an example with raw query. Please note the first ID column returned by the query should be labeled as _id .
MyDatabase.java:
public class MyDatabase extends SQLiteAssetHelper {
...
public Cursor getListNamesForDropDown() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
MyActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
....
Cursor cursorTest = db.getListNamesForDropDown();
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursorTest,
new String[] {"Name"},
new int[] {android.R.id.text1}, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTest.setAdapter(adapter);
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursor,
new String[] { DBOpenHelper.ACCOUNT_BANK },
new int[] { android.R.id.text1 }, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
I have 2 activities(Novamensagem & Mensagenssalva) in Novamensagem.java I have a spinner with contacts values, a EditText and a Save button. I select a contact and write a text and hit save. The TEXT gets saved, and when i open Mensagenssalva.java all the TEXTs i write and save is there in a ListView. So i want to know how to the ListView show the name of the contact i selected in the Spinner and then show the message. eg:
Person's name
Message i have written.
//EDIT//
now the error is: Force to Close the app when i compile it. The code now:
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
list.add(c.getString(c.getColumnIndex("telefone")).toString());
if(!c.moveToNext()) break;
}
}
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.nome_entry, R.id.telefone_entry };
SimpleCursorAdapter myAdap = new SimpleCursorAdapter(this, R.layout.listview, c , campos, to, 0);
user.setAdapter(myAdap);
The LogCat errors:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mensagem/com.example.mensagem.Contato}: java.lang.IllegalArgumentException: column '_id' does not exist
So the thing is, its trying to pull a "_id" from my database, but i dont have a "_id" column/row in it.
Posted from comments
You will have more control over your app while writing less lines of code by using a SimpleCursorAdapter as we discussed.
In order to use any CursorAdapter, your table must have a _id INTEGER PRIMARY KEY column, which you don't have. While I still recommend altering your table to add this column, there is a quick fix. If you don't specify a primary key all SQLite tables create an integer primary key by default, you can reference it with rowid, oid or _rowid_. But Android requires that the integer primary key column is named _id... Simply create an alias with the keyword AS for the meantime:
String[] campos = new String[] {"rowid as _id", "nome", "telefone"};
You need to create customAdapter instead of ArrayAdapter. Check out this link http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
I am trying to get info from a database to a listadabter.
Here is my code for getting the information to the layout:
Cursor c = mnDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] columns = new String[] {EquationsDbAdapter.KEY_VALUE};
int to[] = new int[] {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1 ,c , columns , to);
setListAdapter(adapter);
My error is given by LogCat as :java.lang.IllegalArgumentException: column '_id' does not exist
I have seen some other questions and tutorials and none of those seem to solve my problem. I don't even have a column in my database for _id.
This is because SimpleCursorAdapter needs a field returned called "_id", though it doesn't have to be an actual name of a column in your table, but could be an alias. There's a few threads here on SO talking about this, such as:
Android: column '_id' does not exist
Android column '_id' does not exist?
From my main.java:
Cursor c = db.getDue();
String[] columns = new String[] { "_id", "date" };
int[] to = new int[] { R.id.num, R.id.date };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.lventer, c, columns, to);
ListView lv1 = (ListView)findViewById(R.id.ListView01);
lv1.setAdapter(mAdapter);
From my database wrapper class:
public Cursor getDue() {
//String getdue = "SELECT * FROM tb1"; // this returns _id+date and displays them in the listview via the cursor adapter, defined above
String getdue = "SELECT _id, max(date) AS date FROM tb1 GROUP BY _id";// this only works if I remove the "date" bindings defined above, only letting me see the _id, i want to see both _id and date in the lit view.
return db.rawQuery(getdue,null);
If I use the second select statment then it crashes unless I remove the "date" from the cursor adapter/listview bindings, if I do this then It will show the returned _id in the listview, but I want to see both _id and date in the listview.
I have been told that the second statment might returns a different type for date because of the max function ( I am not very sql literate, yet), but I thought that sqlite was loose with datatypes? Can anybody help, thanks in advance.
** UPDATE** This is the command that wont work with 2 columns fr the list view:
SELECT _id, max(date) FROM jobs GROUP BY _id HAVING max(date) < (date-21)
Use this:
String getdue = "SELECT _id, max(date) AS date FROM tb1 GROUP BY _id";