How to change background image of ImageView in Android from database - android

In my database I am storing data on various tourist attractions. I'm also storing the name of an image for each attraction, e.g. caste.jpg. The following method adds all written data to the text fields but I don't know how to add the image to the ImageView. Any help?
public void updateDisplay()
{
// get the comments
attractions = db.getAttractions();
// create a List of Map<String, ?> objects
ArrayList<HashMap<String, String>> data =
new ArrayList<HashMap<String, String>>();
for (Attraction attraction : attractions) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", attraction.getName());
map.put("times", attraction.getOpeningTimes());
map.put("descr", attraction.getDesc());
map.put("price", attraction.getPrice());
data.add(map);
}
// create the resource, from, and to variables
int resource = R.layout.listview_attraction;
String[] from = {"name", "times", "descr", "price", "web"};
int[] to = {R.id.name, R.id.times, R.id.descr, R.id.price, R.id.web};
// create and set the adapter
SimpleAdapter adapter =
new SimpleAdapter(this, data, resource, from, to);
attractionListListView.setAdapter(adapter);
}

String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
// Then use this for setting the drawable in either case:
Imageview.setBackground(drawable)

You could refer to the image with a path (local or remote)
for (Attraction attraction : attractions) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", attraction.getName());
map.put("times", attraction.getOpeningTimes());
map.put("descr", attraction.getDesc());
map.put("price", attraction.getPrice());
-> map.put("imagePath", attraction.getPath());
data.add(map);
}
And then, instead of using ther built in adapter, make a customer adapter
and load the image from the path in the adapter's getView() method. For example, the below code is a custom adapter I use in one of my apps:
private class ViewHolder {
TextView mItem;
ImageView mStore;
}
public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
int layout;
public MyDataAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.layout = layout;
this.context = context;
}
public View getView(final int pos, View inView, ViewGroup parent) {
ViewHolder holder = null;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(layout, null);
holder = new ViewHolder();
holder.mItem = (TextView) inView.findViewById(R.id.item);
holder.mStore = (ImageView)
inView.setTag(holder);
} else {
holder = (ViewHolder) inView.getTag();
}
final VisitProfile visit = VisitProvider.getProfile(c, pos);
if (visit != null) {
final int store = visit.getStore();
RetailStoreProfile rsp = RetailStoreProvider.fetchStore(ShowEventDetail.this, store);
if (rsp != null) {
holder.mStore.setDrawable(rsp.getPath());
} else {
Log.d(TAG, "Bogus Store in adapter " + store);
}
} else {
Log.d(TAG, "Bogus visit in adapter " + visit);
}
return inView;
}
}

Related

custom adapter with ArrayList<HashMap<String, List<String>>>

Its a really complicated question, but I hope someone can help me.
I want to make a custom adapter that can handle
Array List mentioned in the title
Currently I am doing this, but its not even going into getView(...) method.
public class EventsAdapter extends BaseAdapter{
ArrayList<HashMap<String, List<String>>> eventList;
private Context context;
private int resource;
private static final String TAG_TITLE = "e_title";
public EventsAdapter(Context context, int resId,ArrayList<HashMap<String, List<String>>> eventList)
{
this.context = context;
this.resource = resId;
this.eventList = eventList;
Log.v("chk", "1");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View event = convertView;
TextView title, desc, date, time, venue;
HashMap<String, List<String>> hm = eventList.get(position);
List<String> items = hm.get(TAG_TITLE);
Typeface font = Typeface.createFromAsset(context.getAssets(), "Ubahn.ttf");
if( event == null )
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
event = inflater.inflate( resource , parent, true );
event.setTag(items.get(position));
}
title = (TextView) event.findViewById( R.id.etitle);
desc = (TextView) event.findViewById( R.id.edesc );
date = (TextView)event.findViewById(R.id.edate);
time = (TextView)event.findViewById(R.id.etiming);
venue = (TextView)event.findViewById(R.id.elocation);
title.setTypeface(font);
System.out.print(items.get(0).toString());
title.setText(items.get(0).toString());
desc.setText(items.get(1).toString());
date.setText(items.get(2).toString());
time.setText(items.get(3).toString());
venue.setText(items.get(4).toString());
return event;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return eventList.get(position).get(position).get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
Any help would be greatly appreciated.
Here is how I am filling the data in the Array List
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String description = c.getString(TAG_DESC);
String date = c.getString(TAG_DATE);
String time = c.getString(TAG_TIME);
String venue = c.getString(TAG_VENUE);
// creating new HashMap
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> el = new ArrayList<String>();
el.add(title);
el.add(description);
el.add(date);
el.add(time);
el.add(venue);
// adding each child node to HashMap key => value
map.put(TAG_TITLE, el);
// map.put(TAG_DESC, description);
//muap.put(TAG_DATE, date);
// adding HashList to ArrayList
eventList.add(map);
}
and then here I am setting the adapter
EventsAdapter adapter = new EventsAdapter(getActivity(), R.layout.events_list_item, eventList);
lv.setAdapter( adapter);
I think it would be useful to consider when you are filling that list.
a good design pattern is to create the data as an empty hashmap, establish the adapter with that map, declare the listview( or whatever ) and then assign the adapter with the empty data set. later, fill the hashmap, and then adapter.notifydatasetchanged
I declare these feilds:
//array of places filtered by keyword
List<Place> places = new ArrayList<Place>( );
//spinner of places filtered by keyword
Spinner placesSpinner;
//adapter for spinner
private PlacesSpinnerAdapter placesSpinnerAdapter;
in onCreate:
//this is for a spinner, but same difference
placesSpinner = (Spinner)findViewById( R.id.placesSpinner );
placesSpinnerAdapter = new PlacesSpinnerAdapter( this,
android.R.layout.simple_spinner_dropdown_item, places );
placesSpinner.setAdapter( placesSpinnerAdapter );
and somewhere in the onPostExecute method of an AsyncTask you have no interest in
places.clear( );
places.addAll( result.results );
placesSpinnerAdapter.notifyDataSetChanged( );
placesSpinner.performClick( );
and lastly, here's a difference I see: adapters do Lists, I've never had a good time passing them hashmaps... do a map.keySet() or map.values(); as you hand the data over to the adapter; I know for certain the very standard pattern I just described does not work if the data set is hashmaps
gl hf
return list size from getCount method
#Override
public int getCount() {
return eventList.size();
}
As the array list inside the adapter does not have 5 items(it has only one item) so try return the size of the list
simply use this code for custom adapter java
public class CustomAdapter extends SimpleAdapter {
ArrayList<HashMap<String,String>> arrayList;
Context context;
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> arrayList, int resource, String[] from ,int[] to) {
super(context, arrayList, resource, from, to);
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
View view = super.getView(position,convertView,parent);
RelativeLayout container = (RelativeLayout)
view.findViewById(R.id.container);
return view;
}
}
and this is WelcomeActivity
ArrayList<HashMap<String, String>> userList = "Define your list here"
String[] from = new String[]{"name","phone"};
int[] to = new int[]{R.id.name,R.id.phone};
ListView lv = (ListView) findViewById(R.id.list);
CustomAdapter customAdapter = new CustomAdapter(this,userList,R.layout.user_list_f,from,to);
lv.setAdapter(customAdapter);
it has been working for me perfectly

ListView showing only one item or last item

The title of this question is same but technical issue are different.
Hi i am trying to get data from SQLite but i am able to show only last item in listview. I tried different- different solution but not getting success.
Problem is not getting item from SQLite(I am able to fetch all item) but showing item using adapter in listview.
Here is my code.
ListActivity.java
db=new DBHelper(getBaseContext());
db.getWritableDatabase();
try {
final DBHelper m = new DBHelper(getBaseContext());
final List<GetSet> NotesWiseProfile = m.getBabyDetails();
for (final GetSet cn : NotesWiseProfile) {
counter++;
String babyName = cn.getBabyName();
String babyImage = cn.getBabyImage();
int babyId = cn.getBabyId();
BabyData baby_data[] = new BabyData[]
{
new BabyData(R.drawable.ic_launcher, babyName,babyId),
};
adapter = new MobileArrayAdapter(this,
R.layout.list_row, baby_data);
listView1.invalidateViews();
listView1.setAdapter(adapter);
}
}
catch (Exception e) {
}
BabyData.java
public class BabyData {
public int icon;
public String title;
public int babyid;
public BabyData(){
super();
}
public BabyData(int icon, String title,int babyId) {
super();
this.icon = icon;
this.title = title;
babyid = babyId;
}
}
MobileArrayAdapter.java
public class MobileArrayAdapter extends ArrayAdapter<BabyData>{
Context context;
int layoutResourceId;
BabyData data[] = null;
public MobileArrayAdapter(Context context, int layoutResourceId, BabyData[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
DataHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder ();
holder.imgIcon = (ImageView)row.findViewById(R.id.imvBabyFace);
holder.txtTitle = (TextView)row.findViewById(R.id.tvbabyNameList);
holder.txtBabyId = (TextView)row.findViewById(R.id.tvBabyId);
row.setTag(holder);
}
else
{
holder = (DataHolder )row.getTag();
}
BabyData weather = data[position];
holder.txtTitle.setText(weather.title);
holder.txtBabyId.setText(String.valueOf(weather.babyid));
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class DataHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtBabyId;
}
}
I don't understand what's wrong in my code. Please give me any hint or reference.
Thanks in Advance.
Put the listview declarations out of the for loop, something like:
BabyData baby_data[] = new BabyData[NotesWiseProfile.size()];
for (final GetSet cn : NotesWiseProfile) {
String babyName = cn.getBabyName();
String babyImage = cn.getBabyImage();
int babyId = cn.getBabyId();
baby_data[counter] = new BabyData(R.drawable.ic_launcher, babyName,babyId);
counter++;
}
adapter = new MobileArrayAdapter(this,
R.layout.list_row, baby_data);
listView1.invalidateViews();
listView1.setAdapter(adapter);
I think you should use a field for storing you babies. Currrently, you are using a local Baby array for that. As far as I know, the ListView always gets its data from the array you passed to it (invalidating it causes the ListView to look up that data again.
To recap: Store your array as a field - if data changes, update the array and call notifyDatasetChanged() on your adapter, which will cause your ListView to reload the data.

Android List view SectionIndexer - list view not displaying curent scroll letter

I am trying to use secionIndexer with fast scroll in list view.
I have implemented but
on scroll of list it should popup the current letter at which we have scrolled,
but its not showing that.
on debug mode I came to know that getSectipons() and getPositionForSection() are never called in my case ,
but in any other simple example that i tried from web it does make a call to those functions.
Pelase suggest me what to do
//##################
here is code of my adapter
//#######################
public class MyListAdapter extends ArrayAdapter<Object> implements SectionIndexer {
Activity context;
Object[] listData;
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdapter(Activity context, Object[] objects) {
super(context, R.layout.new_invest_row, objects);
this.context = context;
listData = objects;
alphaIndexer = new HashMap<String, Integer>();
//changes here
ArrayList myArrayList = new ArrayList();
for (int ix=0; ix<objects.length; ix++) {
myArrayList.add(objects[ix]);
}
Collections.sort(myArrayList, new Comparator<HashMap<String, String>>(){
public int compare(HashMap<String, String> one, HashMap<String, String> two) {
return one.get("Name").compareToIgnoreCase(two.get("Name"));
}
});
listData = myArrayList.toArray();
//Arrays.sort(listData);
for (int i = listData.length - 1; i >= 0; i--) {
final HashMap<String, String> obj = (HashMap<String, String>)listData[i];
String element = obj.get("Name");
alphaIndexer.put(element.substring(0, 1).toUpperCase(), i);
}
Set<String> keys = alphaIndexer.keySet(); // set of letters
// Copy into a List for sorting
Iterator<String> it = keys.iterator();
ArrayList<String> keyList = new ArrayList<String>();
while (it.hasNext()) {
String key = it.next();
keyList.add(key);
}
Collections.sort(keyList);
// Convert to array
sections = new String[keyList.size()];
keyList.toArray(sections);
for(int c=0;c < sections.length;c++)Log.e("secction<"+c+">","+"+sections[c]);
Log.e("alphaIndexer","+"+alphaIndexer);
}
static class ViewHolder {
TextView txtName;
TextView txtOwner;
TextView txtStartDate;
TextView txtEndDate;
TextView txtStatus;
ImageView imgIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.new_invest_row, null, true);
holder = new ViewHolder();
**holder.txtName = (TextView) rowView.findViewById(R.id.invest_row_name);**
//my custom code here
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
#SuppressWarnings("unchecked")
final HashMap<String, String> obj = (HashMap<String, String>)listData[position];
String str = obj.get("Name");
if(null == str){
str = "";
}
holder.txtName.setText(str);
//#################
//my custom code here
return rowView;
}
public int getPositionForSection(int section) {
String letter = sections[section];
Log.e("alphaIndexer.get(letter)","+"+alphaIndexer.get(letter));
return alphaIndexer.get(letter);
}
public int getSectionForPosition(int arg0) {
// TODO Auto-generated method stub
return 1;
}
public Object[] getSections() {
return sections;
}
}
//#######################
I assume that in adapter when I am passing the textViewId its not taking the currect textVewId as the sectionIndexer functions are never called.
In the Layout new_invest_row I am getting custom row which have an icon and few textViews.
I am sorting the list on the basis of name of the Object that I am displaying in each row.
i want indexer to work on the name of the object.
Please help me with exact solution

How do i display my data when overriding getview

Ive been learning about the getview . But i cant get it to display the data in my listview. Can anyone help code is below
//public class OrderProductSearch extends Activity {
public class OrderProductSearch extends Activity {
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> item = new HashMap<String,String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.orderproducts);
}
catch (Exception e) {
//
String shaw="";
shaw = e.getMessage();
}
//Create view of the list where content will be stored
final ListView listContent = (ListView)findViewById(R.id.orderproductlistview);
//Set for fast scrolling
listContent.setFastScrollEnabled(true);
//Create instance of the database
final DbAdapter db = new DbAdapter(this);
//Open the Database and read from it
db.openToRead();
//Routine to call all product sub groups from the database
final Cursor cursor = db.getAllSubGroupProduct();
//Manages the cursor
startManagingCursor(cursor);
int i=0;
cursor.moveToFirst();
while (cursor.getPosition() < cursor.getCount()) {
item.put("ProdName",cursor.getString(2));
item.put("ProdSize", cursor.getString(3));
item.put("ProdPack",cursor.getString(4));
item.put("OrdQty","0");
//list.add(item);
list.add(i, item);
item = new HashMap<String,String>();
cursor.moveToNext();
i = i + 1;
}
String[] from = new String[] {"ProdName", "ProdSize", "ProdPack", "OrdQty"};
int[] to = new int[] { R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3, R.id.productlinerow4};
//SimpleAdapter notes = new SimpleAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
NewAdapter notes = new NewAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
listContent.setAdapter(notes);
//Close the database
db.close();
}
class NewAdapter extends SimpleAdapter{
int resource;
Context cxt;
private Context context;
List<? extends Map<String, ?>> DataList;
public NewAdapter(Context context, List<? extends Map<String, ?>> data,
int _resource, String[] from, int[] to) {
super(context, data, _resource, from, to);
resource = _resource;
this.context = context;
DataList = data;
// TODO Auto-generated constructor stub
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.productlinerow, null);
}
// TextView bTitle = (TextView) v.findViewById(R.id.productlinerow);
// bTitle.setText(DataList[position,1][1].toString());
return v;
}
}
}
If you're using a SimpleAdapter, you don't need to extend the class and customize the getView() as the SimpleAdapter handles the mapping of data to your layout via the resource, from and to parameters. Take a look at this tutorial for the idea:
http://vbsteven.com/archives/24
If you want to do more involved customization, use a BaseAdapter, which the SimpleAdapter actually extends. Here's a tutorial with examples of that:
http://android.amberfog.com/?p=296

in spinner items display the list array to replace drawable images how can implemented

i am using spinner in some application in spinner item list array this text replaced in drawable images how can its implemented
personalinformation = (Spinner) findViewById(R.id.SpinnerCategory);
ArrayAdapter<?> adapterDefaultpersonal = ArrayAdapter.createFromResource(Animals.this, R.array.Animalinformation, android.R.layout.simple_spinner_item);
adapterDefaultpersonal.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
personalinformation.setAdapter(adapterDefaultpersonal);
How can the R.array.Animalinformation array list items replaced in drawable images be implemented?
Yes it is look at the code below..
array of data
//stores the image database icons
private static Integer[] imageIconDatabase = { R.drawable.ball, R.drawable.catmouse, R.drawable.cube, R.drawable.fresh, R.drawable.guitar, R.drawable.orange, R.drawable.teapot };
//stores the image database names
private String[] imageNameDatabase = { "ball", "catmouse", "cube", "fresh", "guitar", "orange", "teapot" };
creating List of hashmaps
private void initializeImageList() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, Object>> spinnerList = new ArrayList<HashMap<String,Object>>();
for (int i = 0; i < imageNameDatabase.length; i++) {
HashMap map = new HashMap();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
spinnerList.add(map);
}
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource((spinnerList.get(0).get("Icon"));
spinnerList.get(0).get("Name");
}
// assigning spinner to adapter
public void createAddDialog() { // TODO
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_editoradd_dialog);
Spinner spin = (Spinner) findViewById(R.id.spinnerAddImageList);
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, spinnerData, R.layout.spinner_view, new String[] { "Name", "Icon" }, new int[] { R.id.imageNameSpinner, R.id.imageIconSpinner });
spin.setAdapter(adapter);
}
the adapter used above is as given below..
class CustomSpinnerAdapter extends SimpleAdapter {
LayoutInflater mInflater;
private List<? extends Map<String, ?>> dataRecieved;
public CustomSpinnerAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
dataRecieved = data;
mInflater = LayoutInflater.from(context);
}
#SuppressWarnings("unchecked")
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = mInflater.inflate(R.layout.spinner_view,null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.imageNameSpinner)).setText((String) dataRecieved.get(position).get("Name"));
((ImageView) convertView.findViewById(R.id.imageIconSpinner)).setBackgroundResource(dataRecieved.get(position).get("Icon")));
return convertView;
}
}

Categories

Resources