How to switch database string to drawable resource in Android? - android

I have this codesnippet that gives me the fetched KEY_COLOR from database, and puts it at R.id.text_color for attachment in xml..
KEY_COLOR equals atm "Red" and "Blue".
I dont want "red" and "blue" i want images instead, a little dot.
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_COLOR};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1, R.id.text_color};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this,
R.layout.notes_row, notesCursor, from, to);
setListAdapter(notes);
}
I simply want to change the outcome of NotesDbAdapter.KEY_COLOR to R.drawable.red_dot or blue_dot... But i cant figure ot how...
Do you understand? :/

Use the same fillData that you have.
However, you need to have the URI to the drawables in the database with column name NotesDbAdapter.KEY_COLOR when inserting them into the database.
For the sample code below change image to your drawables, if its blue or red.
String nameToInsert = "android.resource://my.package.name/"+R.drawable.image;
Of course change my.package.name to the correct packagename.
Just let R.id.text_color be the id of the imageview and not a textview.

From the docs for SimpleCursorAdapter:
Binding occurs in two phases. First, if a SimpleCursorAdapter.ViewBinder is available, setViewValue(android.view.View, android.database.Cursor, int) is invoked. If the returned value is true, binding has occured. If the returned value is false and the view to bind is a TextView, setViewText(TextView, String) is invoked. If the returned value is false and the view to bind is an ImageView, setViewImage(ImageView, String) is invoked.
From the docs for SimpleCursorAdapter.setViewImage (ImageView v, String value):
By default, the value will be treated as an image resource. If the value cannot be used as an image resource, the value is used as an image Uri.
So basically if you make it so the KEY_COLOR column of your DB contains Uris to your images and replace R.id.text_color in your to array with the resource id of an ImageView, in theory your SimpleCursorAdapter will automatically fill the ImageView with the image resolved from the Uri.
Never tried it myself but it seems like how it should work.
See this example of how to use an image with a textview in list rows, Fancy ListViews Part One. It's written by Mark Murphy aka CommonsWare here on SO. It actually uses a different method to what I was suggesting with a view binder and uses the getView(...) method to set images and text for each row.

Related

How to access images from drawable folder in android studio according to my choice?

Suppose I have a list of item like String[] list={"item1","item2","item3",....,"itemN"}; I have corresponding images of each item having different formats(some in jpg,some in png etc.) and different names serially(as indices of list array) in drawable folder. I have to do some processing on the list array & each time it returns some particular & different indices of list.
So,I have to show the corresponding images of those items indicated by returned indices no as list view in android studio. how can I do this.
For example, If after processing I have indices no: { 3,7,1}, I have to show corresponding no of images for item3, item7 and item1 stored in drawable folder as listView. Again,indicated indices values may change depending on processing on it.
I want that here in the picture the sequence of displaying the images and texts will not be according to 'position',rather it will be according to my choice like in first row position of listview I will have the image of item3,in row position 2 ->image of item 7,in row position 3 -> image of item 1.
In your List Array processing class, define a Int array containing references to the images:
int imageRes[] = {R.drawable.image1, R.drawable.image2,...};
Now considering that only three indices are returned after processing:
ex:
indices[] ={1,5,6};
int imageArray[] - (Size can be three)
for(int i =0; i<3;i++){
imageArray[i] = imageRes[indices[i]];
}
Your ListView can contain one Image View. Create a custom adapter for the list view and pass imageArray as parameter.
Then you can set the Image for ImageView something like this:
imageView.setImageResource[imageArray[i]]
Store the R value of image in integer array and you can post according to indices from that array
int _rImage[] ={R.drawable.img1,R.drawable.img2}
If you want a ResourceId by name try something like
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
see How to get a resource id with a known resource name?

Confused by use of `from` and `to` params in Android SimpleAdapter class

The official Android docs say the following:
from A list of column names that will be added to the Map associated with each item.
to 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.
I've accomplished this as follows:
final String[] from = new String[] {"TEXT1", "TEXT2"};
final int[] to = new int[] {android.R.id.text1, android.R.id.text2};
a = new SimpleAdapter(this, list, resource, from, to)
I'm able to set data in the view just fine, but im extremely confused as to why the from parameter is necessary. Why not just supply a list of xml resources? Why do a list of (column names?) need to be passed in as well?
Please help me understand.
The first N views in this list are given the values of the first N columns in the from parameter.
This means the values in the from parameter will be set in the corresponding views in the to parameter. According to the SimpleAdapter Android docs, if the views are TextViews, then a list of Strings is expected, and will be bound to the TextViews by calling setViewText(TextView, String).

Checking the contents of the record before it is shown to listview using SimpleCursorAdapter

I would like to display a gray star image if column "status"==0 and display a golden star if column "status"==1. My code can display the record to listview, but without checking the "status" column first:
public void loadPertanyaan(){
Cursor soal = DBAdapter.fetchSemuaSoal();
String[] from = new String[]{DBAdapter.KEY_SOAL_PERTANYAAN};
int[] to = new int[]{R.id.txt_PilihSoal_Pertanyaan};
SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row, soal, from, to);
setListAdapter(dataAdapter);
}
Then I add code to check status column using moveToNext() after setListAdapter(dataAdapter). But the application always force stopped, code to check "answered" column below -
ImageView img = (ImageView) findViewById(R.id.imgBintang);
while(soal.moveToNext()){
if(soal.getInt(soal.getColumnIndex("status"))==1)
img.setImageResource(R.drawable.bintang_mas);
else
img.setImageResource(R.drawable.bintang_abu);
}
How can I check "status" column before displaying to ListView. Thanks in advance.
Agi, You need a good tutorial like link Populating a ListView with a CursorAdapter . Look at code bindView similar to getView method, mentioned in a previous answer. getView is less intensive so it may be good enough for you.
Look at LinearLayout resource XML. In it, there are 2 TextView elements. Instead, I think you need more columns in your ListView, like TextView, popular Checkbox, and an image for the star (bintang).
The code is different than your thoughts in design. It gets and displays data in virtual mode, and you can check the data by the position or Cursor parameter.
Good luck and tell me how it goes for you...

Scrollable clickable items from JSON string in android

I want to create a clickable items from a scrollview or listview where items came from a JSON which is fetched from my online database. Now I don't even have an idea on how to work with this one since I don't know how to dynamically create an object through codes to insert the database items. Well the concept is simple I just need to display a list through codes then assign an ID per row, click one of the row then move to a new intent where details are displayed matched by ID assigned on the selected row. Can anyone give me an example or links on how can I work with this one?
You need to study ArrayAdapter and JSONParsing, there are many tutorials for that, I will try to explain these in a brief:
An AdapterView is the view, which items/childs are determined by some adapter. Like ListView, Spinner.
An Adapter is a bridge between AdapterView and underlying data.
See ArrayAdapter as it seems best according to your requirements.
To Understand JSONParsing, you need to understand JSONObject, and JSONArray:
A JsonObject is a key: value pair, where key need to be string and value might be a number, a boolean value, or some other datatype, or JSONOjbect, or A JSONArray. and its represented by {}. like {"key":"value", "key1":"value1", .....}
A JSONArray is an array of values, values might be a number, a boolean value, or some other datatype, or JSONOjbect, or A JSONArray, and it is represented by []. for example: ["value1", "value2"....]
There is no need to set item view's Id, because you can find which item is being clicked, by:
http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html, method
onItemClick(AdapterView parent, View view, int position, long id), you would have position of item being clicked. But If you still want to assign an id to item view, then do it in getView method of Adapter. by View.setId() method.
check the samples that can be downloaded with the SDK manager, there you'll find everything you're looking for.

Android: How to check if a DB field is blank and, if so, add a value like "Unnamed Record"?

I am working off the Android Notepad Tutorial as a base. The problem is that when someone creates a record with a null name field, it shows up as a blank space in the listview and is unclickable, and therefore undeletable from the list.
I would like to have the program check for a null "name" field and replace it with the string "Unnamed Record" so that it comes up appropriately in the listview. Everything that I have tried so far has not worked correctly.
Another possible solution might be the give the name field an initial value of "Unnamed Record" but I am not sure that this would be effective.
Thanks.
I ran over the same problem during the Notepad Tutorial. I solved it with setting a manual SimpleCursorAdapter.ViewBinder to the SimpleCursorAdapter which connects the Cursor with the overview of notes:
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.list_item, notesCursor, from, to);
notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (cursor.getString(columnIndex).equals("")) {
((TextView) view).setText("no title");
return true;
}
return false;
}
});
setListAdapter(notes);
The first and Last line (instantiation of the SimpleCursorAdapter and setListAdapter(notes) are out of the tutorial, the notes.setViewBinder(...) is what you need to replace empty Note Titles with your text (in the example its 'no title').
I'm unsure how you're doing this. could we see some code? If its an edittext that you're using to retrieve the text just check if what is returned is equal to null? If there's no way of checking the input directly one such solution would be to check the field itself when you're extracting it from the database.
E.g: when you're using a cursor to extract the value in field name just check if it's equal to null?
It's kind of hard to come up with a more specific answer without seeing some code.

Categories

Resources