not getting resource id of images in my code - android

I am trying to make a custom list view with Imageviews in each row that would set their image resource through a string i get from database. The database only contains the name of the images and I need to load it from resources. I've tried all the methods to get resource by name but the function always returns 0. I cannot get my id based on name no matter what I do. This is the Custom adapter that I am using....
public class OwnAddptor extends BaseAdapter {
private LayoutInflater mInflater;
String[] names;
String[] detailarray;
String[] adapimage;
int size;
Context mycont;
public OwnAddptor(Context context,String[] poi_names,String[] details,String[] imageadap) {
mInflater = LayoutInflater.from(context);
this.names = poi_names;
this.detailarray = details;
this.adapimage = imageadap;
this.mycont = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return names.length;
}
#Override
public Object getItem(int puhj) {
// TODO Auto-generated method stub
return puhj;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if (vi == null) {
vi = mInflater.inflate(R.layout.blockview, null);
holder = new ViewHolder();
holder.headline = (TextView) vi.findViewById(R.id.head_line);
holder.detail = (TextView) vi.findViewById(R.id.detail);
holder.image = (ImageView) vi.findViewById(R.id.image);
vi.setTag(holder);
}
else {
holder = (ViewHolder) vi.getTag();
}
holder.headline.setText(names[position]);
holder.detail.setText(detailarray[position]);
// Drawable imgdraw = mycont.getResources().getDrawable(adapimage[position]);
holder.image.setImageDrawable(getAndroidDrawable(adapimage[position], mycont));
System.out.println(adapimage[position]);
return vi;
}
static class ViewHolder {
TextView headline;
TextView detail;
ImageView image;
}
public int getImageId(Context context, String name) {
System.out.println("current name"+name);
return context.getResources().getIdentifier("drawable/"+name, null, context.getPackageName());
}
static public Drawable getAndroidDrawable(String pDrawableName,Context cont){
int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", cont.getPackageName());
System.out.println("resource ids****"+resourceId);
if(resourceId==0){
return null;
} else {
return Resources.getSystem().getDrawable(resourceId);
}
}
}
And this is the main activity where I query the database and pass the array to the custom adapter class. The text views set correctly according to the position. The only problem is in getting the int id of the images from the resource folder.
public class MainActivity extends Activity {
DataBaseHelper baseHelper ;
SQLiteDatabase database;
OwnAddptor adapcustom;
TextView detail;
ListView view;
TextView headline;
String[] name;
String[] images;
String[] desc;
int[] imgids;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<RowItem> rowItems;
view = (ListView) findViewById(R.id.mylist);
baseHelper = new DataBaseHelper(this);
try
{
baseHelper.createDatabase();
}
catch (IOException ioe)
{
throw new Error("Unable to create database");
}
try
{
baseHelper.openDataBase();
}
catch(SQLException sqle)
{
throw sqle;
}
database = baseHelper.getReadableDatabase();
Cursor cursor= database.rawQuery("Select * from tblArpoi_local", null);
int i = 0;
if (cursor.getCount()>0) {
cursor.moveToFirst();
name = new String[cursor.getCount()];
desc = new String[cursor.getCount()];
images= new String[cursor.getCount()];
imgids = new int[cursor.getCount()];
while (cursor.moveToNext()) {
images[i]= "poi_"+cursor.getString(cursor.getColumnIndex("arPoiImageLink"));
name[i] = cursor.getString(cursor.getColumnIndex("arPoiName"));
desc[i] = cursor.getString(cursor.getColumnIndex("arPoiDescription"));
i++;
}
System.out.println("****"+images.length);
database.close();
cursor.close();
adapcustom = new OwnAddptor(this,name,desc,images);
view.setAdapter(adapcustom);
}
}
public static int getImageId(Context context, String name) {
System.out.println("current name"+name);
return context.getResources().getIdentifier("drawable/"+name, null, context.getPackageName());
}
}

Try with this it will solve your problem.
ImageView my_image = (ImageView) findViewById(R.id.my_imageView);
my_image.setBackgroundResource(getResId("ic_launcher"));
Declare following function to get Drawable Resource Id from the passed drawable string name.
public static int getResId(String drawableName) {
try {
Class res = R.drawable.class;
Field field = res.getField(drawableName);
int drawableId = field.getInt(null);
System.out.println("resource ids****"+drawableId);
return drawableId;
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
return 0;
}
}
That's It.
Hope it helps you.
Thanks.

I use this
context.getResources().getIdentifier(drawableResourceName, "drawable", context.getPackageName());
and it works like a sharm.
you could try to call
holder.image.setImageDrawable(context.getResources().getIdentifier(drawableResourceName, "drawable", context.getPackageName()));
instead of
holder.image.setImageDrawable(getAndroidDrawable(adapimage[position], mycont));
hope this help

Related

How to change image resource in nth position of grid view, Need to change according to the received message How can i do this?

I need to change the image resource according to the message received. I tried to make change in database it will work but to see the change activity want to refresh, on refreshing time connection disconnected. Any solution for this? i can get position of image on receive().. can any one can provide a solution????
public void onDataReceived(String message, String ip) {
/ /--------------------------//
try
{
sqlitedatabase = openOrCreateDatabase(DatabaseName, Context.MODE_PRIVATE, null);
Cursor allrows = sqlitedatabase.rawQuery("SELECT * FROM "+UserConstruct.image_list.TableName+" WHERE "+UserConstruct.image_list.Device_ID+ "=="+fxddid+"", null);
if (allrows.moveToFirst()) {
do
{
String iconname1 = allrows.getString(1);
String imgidpos1 = allrows.getString(0);
iconnamefxd=iconname1;
imgidpos=Integer.parseInt(imgidpos1);
} while (allrows.moveToNext());
}
allrows.close();
db.close();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "",
Toast.LENGTH_LONG);
}
Toast.makeText(getApplicationContext(), iconnamefxd+"and"+imgidpos, Toast.LENGTH_SHORT).show();
String on="NO";
TextView ststs=(TextView)findViewById(R.id.txtonof);
String a="00";
if(iconnamefxd.equals("0"))
{
sqlitedatabase = openOrCreateDatabase(DatabaseName, Context.MODE_PRIVATE, null);
String query="UPDATE "+UserConstruct.image_list.TableName+" SET "+UserConstruct.image_list.Image_Name_fxd+"='00' WHERE "+UserConstruct.image_list.Id+" = "+imgidpos+"";
sqlitedatabase.execSQL(query);
call();
Toast.makeText(getBaseContext(), "clear", Toast.LENGTH_LONG).show();
}
else if(iconnamefxd.equals("00"))
{
sqlitedatabase = openOrCreateDatabase(DatabaseName, Context.MODE_PRIVATE, null);
String query="UPDATE "+UserConstruct.image_list.TableName+" SET "+UserConstruct.image_list.Image_Name_fxd+"='0' WHERE "+UserConstruct.image_list.Id+" = "+imgidpos+"";
sqlitedatabase.execSQL(query);
call();
}
}
else if
{-----------------}
class DrawerListAdapter extends BaseAdapter
{
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems)
{
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.itemgridlayout, null);
}
else {
view = convertView;
}
TextView letterText = (TextView) view.findViewById(R.id.item_title);
TextView dvcid=(TextView)view.findViewById(R.id.txtid);
ImageView iconView = (ImageView) view.findViewById(R.id.item_img);
TextView sttus=(TextView)findViewById(R.id.txtonof);
//ImageView iconView = (ImageView) view.findViewById(R.id.icon);
dvcid.setText(mNavItems.get(position).DvceId);
letterText.setText(mNavItems.get(position).IconName);
String fx=mNavItems.get(position).Icon;
if(fx.equals("0"))
{iconView.setImageResource(R.drawable.off1);}
else if(fx.equals("1"))
{--------------}
public void call()
{
try {
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
getTableValues(mNavItems);
try {
final DrawerListAdapter im = new DrawerListAdapter(this, mNavItems);
im.notifyDataSetChanged();
gridview.invalidateViews();
}catch (NullPointerException e){e.printStackTrace();}
You can pass the message params to the Adapter and and set the Resource based on that. Call notifyDataSetChanged after changing the resource.
Do below code
NavItem navItem=(NavItem)adapter.getItem(position);
navIte,.setImageId(newId);
adapter.notifyDatasetChanged();

Android AdapterView cannot display database records in some device

I would like to ask some question about AdapterView.
In my application, there is an activity which retrieve data from database and display them in AdapterView.
However, when i install the application in different devices, I found that the part I have just mentioned could only function on some devices. The others cannot show the database results.
Here is my code:
private void showResults(String query) {
Cursor cursor = searchCustByInputText(query);
if (cursor == null) {
//
} else {
// Specify the columns we want to display in the result
String[] from = new String[] {
"cust_code",
"chinese_name"};
// Specify the Corresponding layout elements where we want the columns to go
int[] to = new int[] {
R.id.scust_code,
R.id.schinese_name};
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter customers = new SimpleCursorAdapter(this,R.layout.cust_list_item, cursor, from, to);
mListView.setAdapter(customers);
// Define the on-click listener for the list items
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor) mListView.getItemAtPosition(position);
String cust_code = c.getString(c.getColumnIndex("cust_code"));
if (callFromAct.equals("Main")) {
String pay_term = c.getString(c.getColumnIndex("pay_term"));
String chinese_name = c.getString(c.getColumnIndex("chinese_name"));
String english_name = c.getString(c.getColumnIndex("english_name"));
String address_1 = c.getString(c.getColumnIndex("address_1"));
String address_2 = c.getString(c.getColumnIndex("address_2"));
String address_3 = c.getString(c.getColumnIndex("address_3"));
String address_4 = c.getString(c.getColumnIndex("address_4"));
String contact = c.getString(c.getColumnIndex("contact"));
String telephone = c.getString(c.getColumnIndex("telephone"));
String last_order_date = c.getString(c.getColumnIndex("last_order_date"));
//Pass data to another Activity
Intent it = new Intent(CustEnqActivity.this, CustEnqDetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("cust_code", cust_code);
bundle.putString("pay_term", pay_term);
bundle.putString("chinese_name", chinese_name);
bundle.putString("english_name", english_name);
bundle.putString("address_1", address_1);
bundle.putString("address_2", address_2);
bundle.putString("address_3", address_3);
bundle.putString("address_4", address_4);
bundle.putString("contact", contact);
bundle.putString("telephone", telephone);
bundle.putString("last_order_date", last_order_date);
it.putExtras(bundle);
startActivity(it);
}
else {
returnToCallingAct(cust_code);
}
//searchView.setQuery("",true);
}
});
}
}
Besides, I discovered there were two warnings in my logcat.
The constructor SimpleCursorAdapter(Context, int, Cursor, String[], int[]) is deprecated
AdapterView is a raw type. References to generic type AdapterView should be parameterized
Are they related to the problem?
Try to create a class that extends BaseAdapter and use ViewHolders for performance
eg:
public class MyBaseAdapter extends BaseAdapter {
ArrayList<ListData> myList = new ArrayList<ListData>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context, ArrayList<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context); // only context can also be used
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.tvTitle, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.tvDesc, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.ivIcon, myList.get(position).getImgResId());
return convertView;
}
// or you can try better way
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
More info/example:
http://www.pcsalt.com/android/listview-using-baseadapter-android/#sthash.lNGSCiyB.dpbs

getting listview row data

I have a listview in my application.I want to set the value of textview in that particular row when I click one of the textview in that row itself.so,I tried like below
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView t=(TextView)v;
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
}
});
the "likes" reference which I used is textview and I want to set the textview by getting the id of that particular row.
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
when I use this I am getting the id of the first visible row of the screen.
How can I get the id of textview of that particular row,on a textview click.
Thanks
I'm not sure how you are populating your list with data, however here is a method I use that works very well.
Data Models
public class Publication {
public String string1;
public String string2;
public Publication() {
}
public Publication(String string1, String string2) {
this.string1= string1;
this.string2= string2;
}
}
Create an array adapter
public class ContactArrayAdapter extends ArrayAdapter<ContactModel> {
private static final String tag = "ContactArrayAdapter";
private static final String ASSETS_DIR = "images/";
private Context context;
//private ImageView _emotionIcon;
private TextView _name;
private TextView _email;
private CheckBox _checkBox;
private List<ContactModel> contactModelList = new ArrayList<ContactModel>();
public ContactArrayAdapter(Context context, int textViewResourceId,
List<ContactModel> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contactModelList = objects;
}
public int getCount() {
return this.contactModelList.size();
}
public ContactModel getItem(int index) {
return this.contactModelList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d(tag, "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.contact_list_entry, parent, false);
Log.d(tag, "Successfully completed XML Row Inflation!");
}
// Get item
final ContactModel contactModel = getItem(position);
Resources res = this.getContext().getResources();
//Here are some samples so I don't forget...
//
//_titleCount = (TextView) row.findViewById(R.id.category_count);
// _category.setText(categories1.Category);
//
//if (categories1.Category.equals("Angry")) {
//Drawable angry = res.getDrawable(R.drawable.angry);
//_emotionIcon.setImageDrawable(angry);
//}
_checkBox = (CheckBox) row.findViewById(R.id.contact_chk);
_email = (TextView) row.findViewById(R.id.contact_Email);
_name = (TextView)row.findViewById(R.id.contact_Name);
//Set the values
_checkBox.setChecked(contactModel.IsChecked);
_email.setText(contactModel.Email);
_name.setText(contactModel.Name);
_checkBox.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View view) {
if (contactModel.IsChecked) {
contactModel.IsChecked = false;
notifyDataSetChanged();
}
else {
contactModel.IsChecked = true;
notifyDataSetChanged();
}
}
});
return row;
}
}
Use the array adapter to fill your list
ContactArrayAdapter contactArrayAdapter;
//
List<ContactModel> contactModelList;
//Fill list with your method
contactModelList = getAllPhoneContacts();
//
contactArrayAdapter = new ContactArrayAdapter(getApplicationContext(), R.layout.contact_list_entry, contactModelList);
//
setListAdapter(contactArrayAdapter);
A sample method to fill data:
public List<ContactModel> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
List<ContactModel> arrContacts = new Stack<ContactModel>();
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Email.DATA1
,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
,ContactsContract.CommonDataKinds.Phone._ID}, null , null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String email= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (email != null)
{
ContactModel contactModel = new ContactModel();
contactModel.Name = name;
contactModel.Email = email;
contactModel.IsChecked = false;
arrContacts.add(contactModel);
}
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
Accessing the data on click
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
//Click handler for listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
ContactModel contact= getItem(position);//This gets the data you want to change
//
some method here tochange set data
contact.email = "new#email.com"
//send notification
contactArrayAdapter.notifyDataSetChanged();
}
});

Unable to refresh database after deleting a row

I am using SQLiteDatabase in android. I am not able to refersh my listview after deleting a row.
My code is as follows:
public void delete(String i) {
// TODO Auto-generated method stub
String [] columns= new String[]{KEY_ROW_ID,KEY_FHR,KEY_ID,KEY_NAME,KEY_AGE};
Cursor c= our_db.query(KEY_TABLE, columns, null, null,null, null, null);
our_db.delete(KEY_TABLE, KEY_NAME+ "="+"\'"+i+"\'", null) ;
c.requery();
}
I call it from a viewholder in efficientadapter. Below is the code where I call it:
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
}
});
Can anyone help me finding out the problem. It doesn't give any error. it just deleted the row but doesn't update the view.
Here is the adapter i used:
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
private Bitmap mIcon4;
Context c;
int window;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.c=context;
// Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);
mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.del1);
mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.drawable.edit);
}
public int getCount() {
return DATA.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
//int i=0;
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.del=(ImageView)convertView.findViewById(R.id.icon1);
holder.edit=(ImageView)convertView.findViewById(R.id.icon2);
window=position;
holder.text.setOnClickListener(new OnClickListener() {
private int pos=position;
//private int pos = position;
public void onClick(View v) {
System.out.println(window);
sql_get db = new sql_get(c);
db.open();
String ret_id= db.getid(DATA[pos]);
String ret_name = db.getname(DATA[pos]);
String ret_age= db.getage(DATA[pos]);
String ret_fhr= db.getfhr(DATA[pos]);
String[] result = {ret_id,ret_name,ret_age,ret_fhr};
db.close();
Bundle b=new Bundle();
b.putStringArray("key",result);
Intent i =new Intent(c,Tabs.class);
i.putExtras(b);
c.startActivity(i) ;
Toast.makeText(c, getItemId(position)+""+" Click- text " +pos+" "+ret_name, Toast.LENGTH_SHORT).show();
}
});
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
Toast.makeText(c, "deleting " + DATA[pos], Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
holder.del.setImageBitmap(mIcon3);
holder.edit.setImageBitmap(mIcon4);
return convertView;
static class ViewHolder {
ImageView del;
TextView text;
ImageView icon;
ImageView edit;
}
}
You need to delete the row also from the object holding the data for the list view..
I think you also have to remove the same data from adapter and then use your_adapter.notifyDataSetChanged() method. That worked for me...
I found the solution. As said above, I had to change the DATA object.
I used the following commands to achieve it.
db.open();
db.delete(DATA[pos]);
DATA=db.getdata();
DATA_NAME=db.getname();
DATA_AGE=db.getage();
DATA_FHR=db.getfhr();
db.close();

ListView alphabetically arrange?

How does my listview automatically display data alphabetically. Because in my emulator it display data arrange by how it arranged in my database.
can anyone have a explanation with this issue?
this is how i retrieve data from my database.
SQLiteDatabase db = openOrCreateDatabase("database", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT DISTINCT category,cimage from FoodList", null);
int count = c.getCount();
String[] values = new String[count];
String[] values1 = new String[count];
c.moveToFirst();
for(int x = 0; x < count; x++){
values[x] = c.getString(c.getColumnIndex("category"));
values1[x] = c.getString(c.getColumnIndex("cimage"));
c.moveToNext();
}
list.setAdapter(new imageadapter(this,values,values1));
db.close();
c.close();
here is my imageadapter activity
public class imageadapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public final String[] mobileValues2;
public imageadapter(Context context, String[] mobileValues, String[] mobileValues1) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileValues2 = mobileValues1;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
viewHolder holder = new viewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.logo, null);
holder.category = (TextView) convertView.findViewById(R.id.cat);
holder.image = (ImageView) convertView.findViewById(R.id.imglogo);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.category.setText(mobileValues[position]);
holder.s = mobileValues2[position];
byte[] decodedString = null;
try {
decodedString = Base64.decode(holder.s, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.image.setImageBitmap(decodedByte);
return convertView;
}
public int getCount() {
return mobileValues.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
static class viewHolder{
ImageView image;
TextView category;
String s;
}
}
get the data from the database by arranging it in the order you are intersted and next add to the arrayadapter.
This may solve your problem
Are you using any query for getting the information from the database? If so, why don't you use a SQL statement like this:
SELECT * FROM your_table ORDER BY your_column
public Cursor fetchAllData() {
return database.query(urtablename, null, null, null, null, null,
null);
}
it will return all data using cursor,In ur activity
Cursor cr=dba.fetchAllData();
cr.movetofirst();
while(!cr.isAfterLast())
{
//fetch all data using column name
//like cr.getString(cr.getColumnIndex("ur column name"));
//it will return as per in dATABASE
cr.movetoNext();
}
Create a custom comparator as you need. And now Use this in the sort function of ArrayAdapter.
try this in constructor :
public imageadapter(Context context, String[] mobileValues, String[] mobileValues1) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileValues2 = mobileValues1;
Arrays.sort(mobileValues);
//Arrays.sort(mobileValues2);
}
enjoy.

Categories

Resources