i have an array from SQLite return value to passing at Spinner
At DatabaseHelper.java i create 1 void
public List<String> getSpinnerSupir(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sopir";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0)+cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
I consume the labels value to display at Spinner
List<String> lables = db.getSpinnerSupir();
Log.d("array:", String.valueOf(lables));
And at Log display
[1Juniarto, 2Agus Haryanto, 3Supriadi, 4Cahyanto]
I need to manipulate to
[Juniarto, Agus Haryanto, Supriadi, Cahyanto]
How to manipulate it?
Thanks
You are adding two columns column 0 and column 1 into labels
labels.add(cursor.getString(0)+cursor.getString(1));
So u have IDs as column 0 so its getting added along with the string
Modify it to
labels.add(cursor.getString(1));
Edit
returning both id and name
create a class like below
class Data {
private String id;
private String label;
public Data(String id,String label){
this.id=id;
this.label=label;
}
}
insert data into class
ArrayList<Data> arrayList=new ArrayList<Data>();
arrayList.add(new Data(cursor.getString(0),cursor.getString(1)));
return the array list and use it :)
You are adding values from both columns column 0 and column 1. If you need values only from column 1 don't add column 0 values
Change your code to add items as follows
labels.add(cursor.getString(1));
You can also use column name while getting the value from cursor in your getSpinnerSupir method.
Instead of below line;
labels.add(cursor.getString(0)+cursor.getString(1));
Use something like;
labels.add(cursor.getString(cursor.getColumnIndex("your_column_name"));
It seems that you want only the second column from each record. When calling:
labels.add(cursor.getString(0)+cursor.getString(1));
you get the numbers that you don't want.
Instead, replace with labels.add(cursor.getString(1));
Related
I am populating a RecyclerView with a table that has two columns it's basically a dictionary and when ever I call the method to start populating something unusual happens, the code ignores the rows with the same values in the first column "col1" and just get the last one and moves to the next and so on
JAVA
public void fetchData()
{
db =new DataBaseHelper(getContext());
try {
db.createDataBase();
db.openDataBase();
}
catch (Exception e)
{
e.printStackTrace();
}
namelist=new LinkedHashMap<>();
int ii;
SQLiteDatabase sd = db.getReadableDatabase();
Cursor cursor = sd.query("dictionary_lib" ,null, null, null, null, null, null);
ii=cursor.getColumnIndex("English_lib");
eng_list=new ArrayList<String>();
nor_list= new ArrayList<String>();
while (cursor.moveToNext()){
namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("German_lib")));
}
Iterator entries = namelist.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry thisEntry = (Map.Entry) entries.next();
eng_list.add(String.valueOf(thisEntry.getKey()));
german_list.add(String.valueOf(thisEntry.getValue()));
}
for (int i = 0; i < eng_list.size(); i++) {
data.add(new DictObjectModel(eng_list.get(i), german_list.get(i)));
}
adapter = new CustomAdapter(data);
rv.setAdapter(adapter);
}
EXAMPLE OF THE DATABASE
here the recyclerview will ignore the first two rows of alpha and prints the third one and move to the next
This is actually most likely because you are putting the values in a LinkedHashMap which implements the map interface which states
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
You are retrieving duplicate keys here:
while (cursor.moveToNext()){
namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("German_lib")));
}
So the first two example values are replaced in the map as the key "alpha" is duplicated.
To verify this you could just print out or step over the values within the loop above.
One way to resolve this would be to create your own java object:
public class Example
{
public String col1; // but appropriate names
public String col2;
// Add constructors or getters and setting if you want private members
}
then use an Arraylist and in your loop
List<Example> rows = new ArrayList<>;
while (cursor.moveToNext()){
Example e = new Example();
e.col1 = cursor.getString(ii);
e.col2 = cursor.getString(cursor.getColumnIndex("German_lib"))
rows.add(e)
}
EDIT
You are creating multiple loops just to get to the same result. So you could just within your cursor loop just put
data.add(new DictObjectModel(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("German_lib")));
I got this method setListView() which I use to populate ListView lv with data from SQLite database:
public void setListView (){
String[] columns= {DbHelper.C_ID, DbHelper.col1, DbHelper.col2, DbHelper.col3, DbHelper.col4,DbHelper.col5};
Cursor cursor = db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, "_id DESC");
String[] from= { DbHelper.col1, DbHelper.col2, DbHelper.col3, DbHelper.col4, DbHelper.col5};
int[] to = {R.id.tvCol1, R.id.tvCol2, R.id.tvCol3, R.id.tvCol4, R.id.tvCol5};
SimpleCursorAdapter adapter = new SimpleCursorAdapter (getApplicationContext(), R.layout.list_row, cursor, from, to);
lv.setAdapter(adapter);
}
There is a textView R.id.tvCol5 which is a part of list row (R.layout.list_row). I would like to dynamically change properties of that R.id.tvCol5 (setText, set background color etc.) based on what was entered in SQLite database column DbHelper.col5.
For example, if entry in DbHelper.col5 for that particular row is string "RED", I want to make that textView R.id.tvCol5 in that particular row to have red background and to set text to "red".
Is it possible to do that or is there some other way to accomplish that same effect?
Thank you all. Best regards.
You would need to do this in your adapter, in other words you're going to have to make a custom adapter that extends a cursoradapter or baseadapter or something similar.
Then you can just simply check the value of the string and do something to the view it returns based on that value (i.e. set the background to red).
I have a class in Java such like this
for (....) {
tarik_id.add(id);
}
which is tarik_id is a List<String> and I want to add the (id) to be written in tarik_id arrayList. And then....
hasil = db.getDetailResult(tarik_id);
getDetailResult is a class for selecting all the (id) that I have pulled out with tarik_id.
And hasil is two dimensional table (List.List.String..)
I think that tarik_id doesn't return a value in my second line above. I have tried to Log.i my id, and the LogCat returns true values of my id. My question is how can the tarik_id in .getDetailResult returns all of the array values?
make your code as the following:
// put the first id in first
StringBuilder stringBuilder = new StringBuilder(id.get(0));
// start the loop from the 2nd
for (i=1; i < idList.size(); i++)
{
stringBuilder.append(",").append(id.toString());
}
String ids = stringBuilder.toString()
hasil = db.getDetailResult(ids);
Change the code in getDetailResult() for the query to be something like
if(ids.equals("")){
return null;
}
String sql = "SELECT * FROM...... WHERE ID IN("+ids+").....";
I think this is much faster, all records in 1 hit and no need for a second loop.
Hi, I have an SQLite database and I'm using a simple cursor to read the database and then show it to a TextView. However, I would like to show the data in a ListView.
So I have the string but I don't know how to show it in ListView. Is there a simple method or will I have to create an adapter of sorts?
I was also wondering how you can set parts of the list view to the header and others to the subheading. I want it so that each row is a different list item if that's possible.
Here is a simple example.Lets say you have two array lists named "Items" and "ItemsId" in your main activity.
Now, in your database handler class fetch your table and store the values to the Items and ItmesId array lists using below code.
MainActivity.Items.clear();
MainActivity.ItemsId.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
// Adding values to list
MainActivity.Items.add(cursor.getString(0));
MainActivity.ItemsId.add(cursor.getString(0));
} while (cursor.moveToNext());
}
Now populate your list view with Items array list in Main activity.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, Items);
listview.setAdapter(adapter);
Use the SimpleCursorAdapter.
Here is a trivial example:
yourListView.setAdapter(new SimpleCursorAdapter(
/* The context where the ListView associated with this SimpleListItemFactory is running */,
/* resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to" */,
/* The database cursor. Can be null if the cursor is not available yet. */,
/* A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet. */,
/* The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet. */,
/* Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int). */));
I come from an action script back ground and i am baffled by how to use arrays in java.
In my main activity i created an empty array called mIcons like so
private Array mIcons;
Now i want to set the value of that array by using a method from my DataBaseHelper class which looks like this:
public Array getHomeScreenIcons() {
Array iconList;
// Select All Query
String selectQuery = "SELECT * FROM " + homeIcons;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
iconList.push(Integer.parseInt(cursor.getString(0)));
} while (cursor.moveToNext());
}
Log.v(TAG, "List Created");
// return contact list
}
that bold line jumping out of the code is the problem so far.. how do i PUSH to my array
Then later i will want to run a for loop for the array from my main activity using.length
Use an ArrayList paramaterized to any type you want
ArrayList<Integer> iconList = new ArrayList<Integer>();
add with
iconList.add(Integer.parseInt(cursor.getString(0)));
Iterate with
for (int i: iconList)
{
// i is your entire array starting at index 0
}
or
for (int i=0; i< iconList.size(), i++)
{
}
You're probably thinking about ArrayList
private ArrayList<String> iconList = ArrayList<String>();
iconList.add("Stuff");
and then later to loop through
for (int i=0; i<iconList.size(); i++) {
String newStuff = iconList.get(i);
}
You should probably hit up some basic java tutorials to get used to the array syntax and functionality. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html could be a good starting point.
Looking at your specific problem -
You generally don't want to use the Array class in the manner that you do. It's more of a helper class. Also, it seems that you are going for stack semantics, and you'd likely want to use a Stack instead.
First, arrays:
you declare an array like so:
Type[] myArray = new Type[arraySize];
and then you access it with index like so:
Type myThingFromArray = myArray[myArrayIndex];
and you put things in it like so:
myArray[myTargetIndex] = myObjectOfTypeType;
Raw arrays in java have static size and are not easily growable. For most applications it would be a better idea to use a member of the Collections framework instead. If you're actively looking for a stack (as you mention pushing) then you could use Stack<Integer> and have all the regular stack operations.
Another benefit of using a modern collection class is that you can iterate through your collection using the for-each construct, which eliminates some regular for boilerplate. An example:
public ArrayList<Integer> iconList;
public Array getHomeScreenIcons() {
Array iconList = new ArrayList<Integer>();
// Select All Query
String selectQuery = "SELECT * FROM " + homeIcons;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
iconList.add(Integer.parseInt(cursor.getString(0)));
} while (cursor.moveToNext());
}
Log.v(TAG, "List Created");
// return contact list
//Iterate like so:
for (Integer i : iconList){
System.out.println("Here's all integers in the icon-list: " + i);
}
}
You can define arrays in Java like this:
int[] intArray = new int[3]; // array for three ints
String[] stringArray = new String[10]; // array for 10 Strings
So for your code, you can do something like this:
if (cursor.moveToFirst()) {
int[] iconList = new int[cursor.getCount()];
int index = 0;
do {
iconList[index] = Integer.parseInt(cursor.getString(0));
index++;
} while (cursor.moveToNext());
}
After that you can loop over the array like this:
for (int icon : iconList) {
// Do something with icon
}