Android making a listview with numbered items - android

I want to make a dynamic ListView with numbered items. Here I have retrieved values from SQLite database into the ListView and actually it is numbered according to their id's which are stored in database. But I'm using a dynamic list view, so I want to show numbered items starting from 1 in each time I load the ListView. For example people booking flight tickets for different dates and flight authorities will display a final ListView for the current date including persons who booked for that date.
consider today is 10-12-2014
person A booked ticket for the date 12-12-2014, so his "id" might be "1" in database.
person B booked ticket for the date 13-12-2014,so his "id" might be "2" in database.
person c booked ticket for the date 13-12-2014,so his "id" might be "3" in database.
but when the day "13-12-2014" comes person B's id should be "1"(no need to have any connection with database, just enough a numberd representation to show today's list is this.
like
1.person B
2.person C
thats all.
This is my displayadapter class:
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String>name;
private ArrayList<String>phone;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> name, ArrayList<String> phone) {
this.mContext = c;
this.id = id;
this.name = name;
this.phone = phone;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.viewthem, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.d);
mHolder.txt_name = (TextView) child.findViewById(R.id.nm);
mHolder.txt_phone = (TextView) child.findViewById(R.id.ph);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_name.setText(name.get(pos));
mHolder.txt_phone.setText(phone.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_name;
TextView txt_phone;
}
}
This is my dbhelper class:
mydb = new DBhelper(this);
SQLiteDatabase database = mydb.getWritableDatabase();
Cursor mCursor=database.rawQuery("SELECT * FROM contacts WHERE dt='"+d+"'", null);
userId.clear();
user_name.clear();
user_phone.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DBhelper.CONTACTS_COLUMN_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DBhelper.CONTACTS_COLUMN_NAME)));
user_phone.add(mCursor.getString(mCursor.getColumnIndex(DBhelper.CONTACTS_COLUMN_PHONE)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(token.this,userId, user_name, user_phone);
obj.setAdapter(disadpt);
disadpt.notifyDataSetChanged();
mCursor.close();

If you want the list to simply be numbered (as you said, without regard to the actual IDs in the database) you simply need to use the pos parameter you receive in getView(). And you'd probably want to use pos + 1 so the list will be 1-based (more user friendly).
Assuming mHolder.txtId is the TextView you want to use to display the numbers, as I said in my comment, this should work:
mHolder.txt_id.setText(String.valueOf(pos + 1));
If you get an error when trying this please explain exactly what error.

Related

How do I manipulate listview so a specific phone number always appears at the top?

How can I make the phone number 3456781276 which is in my phone contacts appear at the very top of my listview, and then all other contacts below that as normal? I believe I pass that value into my custom adapter and into my getView() but not at all sure how to proceed. Can you help?
In my ListView I show all my phone contacts with the following code:
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// we want to delete the old selectContacts from the listview when the Activity loads
// because it may need to be updated and we want the user to see the updated listview,
// like if the user adds new names and numbers to their phone contacts.
selectPhoneContacts.clear();
// we have this here to avoid cursor errors
if (cursor != null) {
cursor.moveToFirst();
}
try {
// get a handle on the Content Resolver, so we can query the provider,
cursor = getApplicationContext().getContentResolver()
// the table to query
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
// display in ascending order
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
// get the column number of the Contact_ID column, make it an integer.
// I think having it stored as a number makes for faster operations later on.
// get the column number of the DISPLAY_NAME column
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// get the column number of the NUMBER column
int phoneNumberofContactIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
cursor.moveToFirst();
// We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
// get a handle on the display name, which is a string
name = cursor.getString(nameIdx);
// get a handle on the phone number, which is a string
phoneNumberofContact = cursor.getString(phoneNumberofContactIdx);
//----------------------------------------------------------
// get a handle on the phone number of contact, which is a string. Loop through all the phone numbers
// if our Hashset doesn't already contain the phone number string,
// then add it to the hashset
if (!ids.contains(phoneNumberofContact)) {
ids.add(phoneNumberofContact);
System.out.println(" Name--->" + name);
System.out.println(" Phone number of contact--->" + phoneNumberofContact);
SelectPhoneContact selectContact = new SelectPhoneContact();
selectContact.setName(name);
selectContact.setPhone(phoneNumberofContact);
selectPhoneContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
Toast.makeText(NewContact.this, "what the...", Toast.LENGTH_LONG).show();
e.printStackTrace();
// cursor.close();
} finally {
}
if (cursor != null) {
cursor.close();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectPhoneContactAdapter(selectPhoneContacts, NewContact.this);
// we need to notify the listview that changes may have been made on
// the background thread, doInBackground, like adding or deleting contacts,
// and these changes need to be reflected visibly in the listview. It works
// in conjunction with selectContacts.clear()
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
//this function measures the height of the listview, with all the contacts, and loads it to be that
//size. We need to do this because there's a problem with a listview in a scrollview.
justifyListViewHeightBasedOnChildren(listView);
}
}
My model, getters and setters, is like:
public class SelectPhoneContact {
String phone;
public String getPhone() {return phone;}
public void setPhone(String phone) {
this.phone = phone;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And my custom adapter:
public class SelectPhoneContactAdapter extends BaseAdapter {
//define a list made out of SelectContacts and call it theContactsList
public List<SelectPhoneContact> theContactsList;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectPhoneContact> arraylist;
Context _c;
//define a ViewHolder to hold our name and number info, instead of constantly querying
// findviewbyid. Makes the ListView run smoother
ViewHolder v;
public SelectPhoneContactAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
theContactsList = selectPhoneContacts;
_c = context;
this.arraylist = new ArrayList<SelectPhoneContact>();
this.arraylist.addAll(theContactsList);
Collections.sort(this.arraylist, new Comparator<SelectPhoneContact>() {
#Override
public int compare(SelectPhoneContact t1, SelectPhoneContact t2) {
if(t2.getPhone().equals ("3456781276")) { // put the phone number you want on top here
return 1;
} else {
return t1.getName().compareTo(t2.getName());
}
}
});
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public Object getItem(int i) {
return arraylist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
static class ViewHolder {
// In each cell in the listview show the items you want to have
// Having a ViewHolder caches our ids, instead of having to call and load each one again and again
CheckBox checkbox;
TextView title, phone, lookup;
// CheckBox check;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
//we're naming our convertView as view
View view = convertView;
if (view == null) {
//if there is nothing there (if it's null) inflate the layout for each row
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.phone_inflate_listview, null);
//or else use the view (what we can see in each row) that is already there
} else {
view = convertView;
}
v = new ViewHolder();
// So, for example, title is cast to the name id, in phone_inflate_listview,
// phone is cast to the id called no etc
v.title = (TextView) view.findViewById(R.id.name);
// v.check = (CheckBox) view.findViewById(R.id.check);
v.phone = (TextView) view.findViewById(R.id.no);
// store the holder with the view
final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);
v.title.setText(data.getName());
v.phone.setText(data.getPhone());
view.setTag(data);
return view;
}
}
What about using add(int index, E element)?
if (/* check your condition here: is it the number you are looking for? */) {
// insert the contact at the beginning
selectPhoneContacts.add(0, selectContact);
} else {
// insert it at the end (default)
selectPhoneContacts.add(selectContact);
}
Try to modify your adapter's constructor like this:
public SelectPhoneContactAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
theContactsList = selectPhoneContacts;
_c = context;
this.arraylist = new ArrayList<SelectPhoneContact>();
this.arraylist.addAll(theContactsList);
Collections.sort(this.arraylist, new Comparator<SelectPhoneContact>() {
#Override
public int compare(SelectPhoneContact t1, SelectPhoneContact t2) {
if(t2.getPhone().equals("3456781276")) { // put the phone number you want on top here
return 1;
} else {
return t1.getName().compareTo(t2.getName());
}
}
});
}
So we are basically sorting the ArrayList before the adapter starts using it.
So in this example, I am putting the phone number "3456781276" on top of everything else. If the phone number is NOT "3456781276", it will sort all the items by the name. (If you don't want to sort it by name, just remove the else statement.
Hope this helps.
EDIT:
in getView(), change:
final SelectPhoneContact data = (SelectPhoneContact) theContactsList.get(i);
to:
final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);
Change getCount() method like this:
#Override
public int getCount() {
return arraylist.size();
}
Change getItem() method like this:
#Override
public Object getItem(int i) {
return arraylist.get(i);
}
You must use arraylist everywhere since that is the list we are sorting.
An easy way to achieve this, just use a view in XML which contains your phone number, and set it to invisible in default, if the list shows, set the view to be visible. I hope this post help you!!!
You can easily manipulate with items positions in ArrayList with Collections.swap(); by looping through your contacts and by simply checking is number matching your number if does put it on the top for example:
Collections.swap(myArrayList, i, 0);
Refering to: http://www.java2s.com/Code/Java/Collections-Data-Structure/SwapelementsofJavaArrayList.htm

ListView with CheckBoxes filled with SQL values

I have created SQL database in my Android project and managed to populate ListView with data that I inserted. Next part of the project is to enable CheckBoxes for every item (from SQL database) in my ListView. I have found a way how to do it with String values, but I am not sure how to do it with values from SQL database.
Is it somehow possible to put SQL values into String ? Or I need to use different data values to populate my ListView ?
I am still nooby with SQL in Android, so every advice would be helpfull.
Here is code:
public class ModelBreakfast {
public String name; //This String need to be filled with SQL datas. If it's possible.
public boolean checked;
public ModelBreakfast(String name, boolean checked){
this.name = name;
this.checked = checked;
}
}
Just need to say that I tried to replace public String name; with my ContractClass
public FoodContract.FoodEntry entry; where I defined all String values for my database rows.
(_ID, NAME, etc). (I only saw that way to solve my problem). So, code is now looking like this:
public ModelBreakfast(FoodContract.FoodEntry entry, boolean checked){
this.entry = entry;
this.checked = checked;
}
Next class is CustomAdapter
public class CustomAdapterBreakfast extends ArrayAdapter<ModelBreakfast> {
private ArrayList<ModelBreakfast> dataSet;
Context mContext;
private static class ViewHolder {
TextView txtName;
CheckBox checkBox;
}
public CustomAdapterBreakfast(ArrayList<ModelBreakfast> data, Context context){
super(context, R.layout.activity_breakfast_checkbox, data);
this.dataSet = data;
this.mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_breakfast_checkbox, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtName);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
ModelBreakfast item = getItem(position);
viewHolder.txtName.setText(item.name); //Need to replace or modify this part
viewHolder.checkBox.setChecked(item.checked);
return result;
}}
Last part is the MainActivity
public class BreakfastActivity extends AppCompatActivity {
ArrayList<ModelBreakfast> modelBreakfastArrayList;
private CustomAdapterBreakfast customAdapterBreakfast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_breakfast);
ListView listView = (ListView) findViewById(R.id.listBreakfast);
modelBreakfastArrayList = new ArrayList<>();
modelBreakfastArrayList.add(new ModelBreakfast("This string will show in ListView. So I need to somehow replace that String with SQL datas.", false));
customAdapterBreakfast = new CustomAdapterBreakfast(modelBreakfastArrayList, getApplicationContext());
listView.setAdapter(customAdapterBreakfast);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ModelBreakfast modelBreakfast= modelBreakfastArrayList.get(position);
modelBreakfast.checked = !modelBreakfast.checked;
customAdapterBreakfast.notifyDataSetChanged();
}
});
}}
After I replaced public String name; with my ContractClass public FoodContract.FoodEntry entry; I understand that I can't use
modelBreakfastArrayList.add(new ModelBreakfast("This string will show in ListView", false));. But than what do I need to set, so my ListView with CheckBoxes will displaying my SQL database values ?
Should I use ArrayList instead String? And how?
Again as I said before in the last question. Look at the for loops. So within your SQLDB Activity and in the function that is taking the values out of the database, you need to populate an array list that you will call in the MainActivity.
public ArrayList<String> getAirportRegion(String code)
Cursor cursor = db.rawQuery("SELECT "+ AIRPORT_NAME +
" FROM " + AIRPORT_TABLE + " WHERE " + AIRPORT_CODE + " = " + code, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
arrayList.add(cursor.getString(cursor.getColumnIndex(AIRPORT_NAME)));
cursor.moveToNext();
}
}
cursor.close();
return arrayList;
}
Now in the Main Activity get a reference to the database and set it to modelBreakfastArrayList like so
airportArrayList = mdb.getAirportRegion();
Voila it is done
Do you see how I am extracting the data? For the most part, this is the best way to extract lists from the local database. Keep these Activities separate, also I hope you have the Database activity as a singleton, otherwise, you will have multiple databases and that will guzzle up resources. Look below for how I start these database activities.
private DBHelper(Context context) {
super(context, "db", null, DATABASE_VERSION);
}
private static DBHelper INSTANCE;
public static DBHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}

How to display multiple table data into one layout

I have 2 tables, Logs and Price. Content from table logs is displayed into textviews for each item. Now I would like to display some content form table Price into the same base adapter.
Is it possible and how should I done that?
This is my activity with base adapter in which i displayed content form table logs. How should I display here content form table Price?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_logs_listview);
boolean sort = getIntent().getBooleanExtra("sort", false);
mainListView = (ListView) findViewById(R.id.ListViewItem);
final String place = (String) getIntent().getExtras().get("keyPlace");
dbHandler = new LogsDBHandler(this);
ArrayList<Logs> logsList = sort ? dbHandler.getAllLogsByPlace() : dbHandler.getAllLogs(place);
TextView result = (TextView) findViewById(R.id.LogMassResult);
double sum = 0.0;
for( int i=0; i<logsList.size(); i++) {
sum += logsList.get(i).getResult();
}
result.setText(String.format("%.2f", sum));
listAdapter = new LogsArrayAdapter(logsList);
mainListView.setAdapter(listAdapter);
}
private class LogsArrayAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Logs> logsList;
private List<Price> priceList;
public LogsArrayAdapter(List<Logs> logsList) {
inflater = LayoutInflater.from(DisplayLogs.this);
this.logsList = logsList;
}
#Override
public int getCount() {
return logsList.size();
}
#Override
public Object getItem(int position) {
return logsList.get(position);
}
#Override
public long getItemId(int position) {
return logsList.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_display_logs, parent, false);
}
Logs log = logsList.get(position);
((TextView) convertView.findViewById(R.id.textPlace)).setText(log.getPlace());
((TextView) convertView.findViewById(R.id.textNumber)).setText(log.getPlate_number());
((TextView) convertView.findViewById(R.id.textSort)).setText(log.getSort_id());
((TextView) convertView.findViewById(R.id.textGrade)).setText(log.getGrade());
((TextView) convertView.findViewById(R.id.textDiameter)).setText(log.getDiameter());
((TextView) convertView.findViewById(R.id.textLength)).setText(log.getLength());
Log.d("Value", log.getCreatedAt());
try {
Date dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(log.getCreatedAt());
((TextView) convertView.findViewById(R.id.textDate)).setText(new SimpleDateFormat("dd.MM.yyyy HH:mm").format(dt));
} catch (ParseException e) {
e.printStackTrace();
}
Log.d("Masa Trupca", String.format("%.2f", log.getResult()));
String final_result = String.format("%.2f", log.getResult());
((TextView) convertView.findViewById(R.id.textAmount)).setText(final_result);
return convertView;
}
}
and this is my dbQuery for getting price. I created this in my Logs class. Here I'm displaying price based on parameters in string.
public Cursor getPrice() {
Cursor cursor = db.query("Price", new String[]{"price_stump_kn", "price_stump_eur", "road_price_kn", "road_price_eur"}, "sort = ? AND grade = ? AND length = ? BETWEEN diameter_dg = ? AND diameter_gg = ?",
new String[]{getSort_id(), getGrade(), getLength(), getDiameter(), getDiameter()}, null, null, null);
if (cursor.moveToFirst()) {
do {
Price price = new Price();
price.setStumpPrice_kn(cursor.getString(0));
price.setStumpPrice_eur(cursor.getString(1));
price.setRoadPrice_kn(cursor.getString(2));
price.setRoadPrice_eur(cursor.getString(3));
} while (cursor.moveToNext());
}
return cursor;
}
So how should I display content from two tables inside one base adapter (listview)?
It depends on how the records in those two tables are related. Your remark that you included a DB query in the Logs class (which I suppose is a domain class, not a DAO), I suspect that your class structure is somewhat confusing. Therefore, I try to sketch a class structure for each of the two ways of mixing your logs and prices.
Solution A: Each log is connected to a price, and data of both are to be displayed in one item.
class LogDAO extends SQLiteOpenHelper {
...
public Log getLogs(some selection parameters) {
Get logs according to selection parameters, and for each log
call getPrice(selection parameter according to log just found)
log.setPrice(price just found)
...
Now, in your adapter, the items are Logs, and with log.getPrice() you can get the price attributes and are free to mix log and price attributes in your adapter to display them in your view item.
Solution B: There is a mixed list -- some items are logs, others are prices
The key to this is that you can dynamically decide, for each item, which layout to use in your adapter. So the structure will be:
class LogPriceDAO extends SQLiteOpenHelper {
...
public Object getLogsAndPrices(some selection parameters)
Get logs and prices in some sequence, according to your business
logic and the selection parameters (If logs and prices have some
common superclass, use that instead of Object)
...
class LogsAndPricesAdapter extends BaseAdapter {
...
#Override
public View getView (int i, View view, ViewGroup viewGroup) {
...
Object currObject = this.getItem(i); // or common superclass
...
View v;
if (currObject instanceOf Log) {
v = layoutInflater.inflate(R.layout.log_layout, null)
now fill fields of your log layout
...
} else {
if (currObject instanceOf Price) {
v = layoutInflater.inflate(R.layout.price_layout, null)
now fill fields of your price layout
...
return v
The instanceOf operator is considered bad style by some people. So the immaculate way is to define a common superclass for Log and Price that offers an operation public Boolean isLog() from which the caller can decide which type of object it got.

Values are not Populating in Listview [duplicate]

This question already has answers here:
Custom Adapter getView() method is not called
(6 answers)
Closed 7 years ago.
I am trying to develop an android application that can display values from multiple tables.
I have used a Base Adapter to display the values since i just need to display the queried values in a list. But when I try to display the values in the list view it is blank.
I am not sure what I have done wrong.
I am Using the below method to query the data from the database to display only the required values.
public Cursor getAssetInStore()
{
SQLiteDatabase db_database = getReadableDatabase();
Cursor c = db_database.rawQuery("SELECT asset_name,warrenty,AssetImage,asset_status FROM `Assets`,`AseetIssued` WHERE Assets.Assetid = AseetIssued.Assetissuedid AND asset_status =?" ,
new String [] {"In Storage"}, null);
return c;
}
The below methods are used to populate the values onto the list view.
private void populateAssetListView()
{
Cursor c = db_database.getAssetInStore();
AssetListView.setAdapter(new AssetListAdapter(this, c));
}
public class AssetListAdapter extends BaseAdapter
{
private Context mContext;
Cursor cursor;
public AssetListAdapter(Context context, Cursor c) {
super();
mContext = context;
cursor =c ;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//The layout is assigned to the custome created created in this case it is customeassetview the cales will be displayed as per this list
view = inflater.inflate(R.layout.assetsinstore_placeholder, null);
cursor.moveToPosition(position);
TextView Assetsstatus = (TextView) view.findViewById(R.id.Assetssatutsstore_view);
int status = cursor.getInt(cursor.getColumnIndex("asset_status"));
Assetsstatus .setText(String.valueOf(status));
TextView Assetsname = (TextView) view.findViewById(R.id.Assetstore_name_view);
String Assetname = cursor.getString(cursor.getColumnIndex("asset_name"));
Assetsname.setText(Assetname);
TextView Warrenty = (TextView) view.findViewById(R.id.Assetstore_Warrenty_view);
String CustDesignation = cursor.getString(cursor.getColumnIndex("warrenty"));
Warrenty .setText(CustDesignation);
ImageView AssetImage = (ImageView) view.findViewById(R.id.list_image);
byte[] bb = cursor.getBlob(cursor.getColumnIndex("AssetImage"));
AssetImage.setImageBitmap(BitmapConver.getPhoto(bb));
return view;
}
}
Try to use a cursor adapter in place of a base adapter. Moreover, beware that the position you're passing to the cursor may not be what you think.

How to load data into spinner from database in android

In my application there is a spinner to provide the users to select units so that the data from that particular unit should be randomly displayed.My spinner looks like this
Unit-1
Unit-2
.
.
.
Unit-25
if user selects unit-2 from the spinner there are 12 words in the unit-2 so that the words from that unit should be displayed in random.
I have created a table and stored in the database the columns are unit,word
i have stored in the following way in the table
unit|word
1 bank
1 stack
1 over
1 flow
. .
. .
. .
2 google
2 facebook
2 gmail
so on upto 25 units there are 12 words per each unit.
Now i should retrieve them and display them randomly
How to write logic for this if user clicks unit-12 that particular units words only should be displayed.please help me to solve this
Thanks in advance
Here is a sample that i use to populate the data from Sqlite to
Spinner, You can customize this to your needs, remove the SQLite
part if you don't need it - instead pass an array
In onActivityCreated call this method
setDataForCity();
FunctionDefinition::
private void setDataForCity() {
DatabaseHandler mHelper;
SQLiteDatabase db = null;
Cursor mCursor = null;
ArrayList<LinkedHashMap<String,String>> listCollection=new ArrayList<LinkedHashMap<String,String>>();
LinkedHashMap<String, String> mapCollection;
try {
mHelper = new DatabaseHandler(getActivity());
db = mHelper.getReadableDatabase();
//QUERY:- select city_id,city_name,no_of_buffets,downloaded from city_mas
mCursor = db.rawQuery("select "
+""+city_mas.COLUMN_CITY_ID+","
+""+city_mas.COLUMN_CITY_NAME+","
+""+city_mas.COLUMN_DOWNLOADED+" "
+"from "
+""+city_mas.TABLE_NAME_CITY_MAS+"", null);
if(mCursor.moveToFirst()){
do{
mapCollection=new LinkedHashMap<String,String>();
mapCollection.put(city_mas.COLUMN_CITY_ID, mCursor.getString(mCursor.getColumnIndexOrThrow(city_mas.COLUMN_CITY_ID)));
mapCollection.put(city_mas.COLUMN_CITY_NAME, mCursor.getString(mCursor.getColumnIndexOrThrow(city_mas.COLUMN_CITY_NAME)));
mapCollection.put(city_mas.COLUMN_DOWNLOADED, mCursor.getString(mCursor.getColumnIndexOrThrow(city_mas.COLUMN_DOWNLOADED)));
listCollection.add(mapCollection);
}while(mCursor.moveToNext());
}
AdpSearchCitySpinner adapter=new AdpSearchCitySpinner(getActivity(),listCollection);
spnSearchByCity.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(db!=null){
if(db.isOpen()) db.close();
}
if(mCursor!=null){
if(!mCursor.isClosed())mCursor.close();
}
}
}
AdpSearchCitySpinner.java
public class AdpSearchCitySpinner extends BaseAdapter {
Context mContext;
ArrayList<LinkedHashMap<String, String>> city;
public AdpSearchCitySpinner(Context context, ArrayList<LinkedHashMap<String, String>> _listCollection) {
super();
this.mContext = context;
city=_listCollection;
}
#Override
public int getCount() {
return city.size();
}
#Override
public Object getItem(int position) {
return city.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
LinkedHashMap<String, String> mapCollection=city.get(position);
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
View row = inflater.inflate(R.layout.adp_search_city_spinner, parent, false);
TextView city_id = (TextView) row.findViewById(R.id.city_id);
TextView city_name = (TextView) row.findViewById(R.id.city_name);
TextView downloaded_id = (TextView) row.findViewById(R.id.downloaded_id);
city_id.setText(mapCollection.get(city_mas.COLUMN_CITY_ID));
city_name.setText(mapCollection.get(city_mas.COLUMN_CITY_NAME));
downloaded_id.setText(mapCollection.get(city_mas.COLUMN_DOWNLOADED));
return row;
}
}
Hope this helps !

Categories

Resources