I need to populate the data from the query and populate it on ListView with custom Item.
on OnCreateView, I'm calling my adapter like this:
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(getContext(), android.R.layout.simple_list_item_1, stops)
This is my whole code of LoadData
public void LoadData() {
String query = "SELECT ticket_placeto, COUNT(CASE WHEN passenger_type <> 'Baggage' THEN 1 END) AS Pass,\n" +
"COUNT(CASE WHEN passenger_type = 'Baggage' THEN 1 END) AS Baggage FROM tickets GROUP BY ticket_placeto";
c = sqldb.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String placeto = c.getString(0);
String passengers = c.getString(1);
String baggages = c.getString(2);
stops.add(placeto + " " + passengers + " " + baggages);
} while (c.moveToNext());
}
}
}
This is the output of it
I've just hard coded the spacing on stops.add for temporary display of data. I already have a custom ListItem Layout but didn't use it for the mean time.
this is the result of the query on chrome://inspect
enter image description here
for your reference, i just re-code LoadData. thanks to pskink who help me here and to other that respond on this thread.
public void LoadData() {
String query = "SELECT _id, ticket_placeto, " +
"COUNT(CASE WHEN passenger_type <> 'Baggage' THEN 1 END) AS Pass," +
"COUNT(CASE WHEN passenger_type = 'Baggage' THEN 1 END) AS Baggage " +
"FROM tickets GROUP BY ticket_placeto";
final String[] columns = new String[]{
DBHelper.TICKET_ID,
DBHelper.TICKET_PLACETO,
"Pass",
"Baggage",
};
final int[] to = new int[]{
R.id.stops_id,
R.id.stops_location,
R.id.stops_passengers,
R.id.stops_baggages
};
c = sqldb.rawQuery(query,null);
if (c != null) {
adapter = new SimpleCursorAdapter(getContext(), R.layout.item_for_stops, c, columns, to, 0);
lv_stops.setAdapter(adapter);
}
}
1.First initialize your List in onCreate() method of activty,
ArrayList<String> stops = new ArrayList<>();
then pass it to ArrayAdapter.
2.After successfully executing query add data to your "stops" list,then
add following line to your code.
arrayAdapter.notifyDataSetChanged();//to notify that your data of list has been change
Related
I have a Listview that is filled by a sqlite query. One of the columns has duplicate entries (credit) and I would like to remove all duplicates in that column. I tried to do that at the sqlite query using the "distinct" method but it doesn't work.
Here's is the code
String query = "SELECT * FROM items " +
"WHERE type = 'month' OR type = 'income' OR type = 'regular' OR type = 'credit' AND" +
" month = " + monthOfYear + " ORDER BY day ASC, _id ASC";
Cursor cursor = db.rawQuery(query, null);
list = (ListView) findViewById(R.id.list);
ItemsCursorAdapter adapter = new ItemsCursorAdapter(
this, R.layout.row_layout, cursor, 0);
list.setAdapter(adapter);
Used also changing the query to
SELECT * FROM items (SELECT DISTINCT type FROM items WHERE type = 'credit')
"WHERE type = 'month' OR type = 'income' OR type = 'regular' OR type = 'credit' AND" +
" month = " + monthOfYear + " ORDER BY day ASC, _id ASC
As I've mentioned in the comment above you can change your query as:
String query = "SELECT * FROM items " +
"WHERE type = 'month' OR type = 'income' OR type = 'regular' OR type = 'credit' AND" +
" month = " + monthOfYear + " GROUP by _id ORDER BY day ASC, _id ASC";
In the Above query, you can see I've used the _id column for grouping the entries and it works great.
Try this
I have same problem, which is you have facing now, I had fixed it by following way.
Code for MainActivity.java file.
public class MainActivity extends AppCompatActivity {
ListView listview;
List<String> subject_list;
ArrayAdapter<String> arrayadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.listView1);
subject_list = new ArrayList<String>();
subject_list.add("ONE");
subject_list.add("TWO");
subject_list.add("THREE");
subject_list.add("FOUR");
subject_list.add("FIVE");
subject_list.add("SIX");
subject_list.add("SEVEN");
subject_list.add("EIGHT");
subject_list.add("NINE");
subject_list.add("TEN");
subject_list.add("THREE");
subject_list.add("FOUR");
subject_list.add("FIVE");
subject_list.add("THREE");
subject_list.add("FOUR");
subject_list.add("FIVE");
subject_list.add("THREE");
subject_list.add("FOUR");
subject_list.add("FIVE");
//Deleting Same entries
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(subject_list);
subject_list.clear();
subject_list.addAll(hashSet);
//Alphabetic sorting.
Collections.sort(subject_list);
arrayadapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, subject_list);
listview.setAdapter(arrayadapter);
}
}
I am pretty sure my sqlite syntax is right but I don't know why when database result is loaded in my listview it show all of my data. I think the problem is about my cursor snippet.
How can I fix this problem that load only rows where table_one.id = table_two.day_id
#Override
public List<Model> getAllEx() {
SQLiteDatabase db = helper.getWritableDatabase();
List<Model> list = new ArrayList<>();
String query = "SELECT * FROM " + Constants.TABLE_ONE + " INNER JOIN " + Constants.TABLE_TWO +" ON "+
Constants.ID_ONE + " = " + Constants.ID_DAY;
Cursor c = db.rawQuery(query, null);
while (c.moveToNext()) {
Model model = new Model();
model.setSecond_id(c.getInt(c.getColumnIndex(Constants.ID_TWO)));
model.setExercise(c.getString(c.getColumnIndex(Constants.EXERSICE)));
model.setNumber(c.getString(c.getColumnIndex(Constants.NUMBER)));
model.setReps(c.getString(c.getColumnIndex(Constants.REPS)));
model.setId_day(c.getInt(c.getColumnIndex(Constants.ID_DAY)));
list.add(model);
}
return list;
}
I am not sure what values you have in your constants but is your query like this
select * from table_one as one inner join table_two as two
on one.id = two.day_id
where one.category="cat_one"
and two.category="cat_two"
You can remove the category of second/first table if not required.
I'm trying to implement dynamic queries in my Android app, to let the users search according to some criteria. In this case I'm trying to search simply by an integer value. Here's my attempt:
...
public String[][] listarNegocio(int idProyecto,
int minimo,
int maximo)
{
String[][] arrayDatos = null;
String[] parametros = {String.valueOf(idProyecto)};
Cursor cursor = null;
cursor = querySQL("SELECT *" +
" FROM negocio" +
" WHERE ? in (0, id_proyecto)", parametros);
if(cursor.getCount() > 0)
{
int i = minimo - 1;
arrayDatos = new String[maximo - minimo + 1][20];
while(cursor.moveToNext() && i < maximo)
{
// Here I fill the array with data
i = i + 1;
}
}
cursor.close();
CloseDB();
return(arrayDatos);
}
public Cursor querySQL(String sql, String[] selectionArgs)
{
Cursor oRet = null;
// Opens the database object in "write" mode.
db = oDB.getReadableDatabase();
oRet = db.rawQuery(sql, selectionArgs);
return(oRet);
}
...
I tested this query using SQLFiddle, and it should return only the rows where the column id_proyecto equals the parameter idProyecto, or every row if idProyecto equals 0. But it doesn't return anything. If I remove the WHERE clause and replace "parametros" with "null", it works fine.
Additionally, I need to search by text values, using LIKE. For example, WHERE col_name LIKE strName + '%' OR strName = ''. How should I format my parameters and the query to make it work?
You should do one query for each case. For an id that exists, do SELECT * FROM negocio WHERE id_proyecto = ?. For an id that doesn't exist (I'm assuming 0 isn't a real id), just query everything with SELECT * FROM negocio.
Code should be something like this:
if(parametros[0] != 0){
cursor = querySQL("SELECT *" +
" FROM negocio" +
" WHERE id_proyecto = ?", parametros);
} else {
cursor = querySQL("SELECT *" +
" FROM negocio", null);
}
Regarding your second question, it depends on what you're looking for, you could use LIKE '%param%' or CONTAINS for occurrences in between text, LIKE param for partial matches or just = param if you're looking an exact match.
I have selected the records which matches the given month name and using simple cursor adapter i have to display it in listview. I'm getting no error but the list displays nothing.
Here is my code
public Cursor readData(String month){
String SELECT_MON = "select * from " + Diary_DBHandler.TABLE_PERSONAL + " where strftime('%m'," +Diary_DBHandler.PERSONAL_DATE + ") = '" + month +"';";
Cursor c = database.rawQuery(SELECT_MON, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Cursor c = dbcon.readData(month);
String[] from = new String[]{Diary_DBHandler.PERSONAL_ID,Diary_DBHandler.PERSONAL_TITLE,Diary_DBHandler.PERSONAL_DESC,Diary_DBHandler.PERSONAL_AMT_SPENT,
Diary_DBHandler.PERSONAL_PAYMETHOD, Diary_DBHandler.PERSONAL_DATE };
int[] to = new int[]{R.id.persID_tv,R.id.persTitle_tv,R.id.persDesc_tv,R.id.persAmt_tv,
R.id.persPaymethod_tv, R.id.persDate_tv};
adapter = new SimpleCursorAdapter(Diary_ListOfPersonalExpenses.this,R.layout.diary_personal_exp_entries,c,from,to);
adapter.notifyDataSetChanged();
The strftime documentation says:
%m month: 01-12
You have to convert month's value into the same format for the comparison to work.
In my app I want to put in an array some items from database. I can see them, as a list using this function :
private void fillData()
{
c = db.fetchListId(listid);
startManagingCursor(c);
adapter = new SimpleCursorAdapter(this, R.layout.listproduct, c,
new String[] { DbAdapter.KEY_ITEM,
DbAdapter.KEY_QUANTITY,
DbAdapter.KEY_UNITS },
new int[] { R.id.prod1,
R.id.prod2,
R.id.prod3 }
);
setListAdapter(adapter);
}
But I don't know how can I put them in an array.
Can anyone help me, please?
I suppose you would like to do something like this:
private String[] getItems(<the selection params>) {
Cursor c = db.retrieveItems(<the selection params>);
String[] items = new String[c.getCount()];
for (int i = 0; c.moveToNext() != null; i++) {
String item = c.getString(c.getColumnIndexOrThrow(DbAdapter.KEY_ITEM));
String quantity = c.getString(c.getColumnIndexOrThrow(DbAdapter.KEY_QUANTITY));
String units = c.getString(c.getColumnIndexOrThrow(DbAdapter.KEY_UNITS));
items[i] = item + " " + quantity + units;
}
c.close();
return items;
}
I have assumed that your DB class has a method called retrieveItems, that takes some selection params, in order to perform the appropriate query.
I have not tested the code, there may be some typo or minor error, but I hope it can direct you to the desired solution.
You're definitely going to begin by iterating through the cursor:
while(c.moveToNext()){
myString = c.getString(c.getColumnIndex("MyColumnName")); // or somesuch
array[x][y][z] = myString; // also somesuch
}
Without knowing more about how you want to store the data, it's impossible to guess what you need beyond c.moveToNext().
UPDATE:
OK, so you just want to accumulate them into a String. Try something like:
String theList="";
while(c.moveToNext()){
theList += c.getString(0) + " " + c.getString(1) + c.getString(2) + "\n";
}