android ImageView setContentDescription with ListAdapter - java

I have a news list. I use this;
ListAdapter adapter = new SimpleAdapter(this, getXmlData(URL,KEY_ITEM,KEY_COLUMN),
R.layout.news_list,
new String[] { KEY_COLUMN[1],KEY_COLUMN[0] }, new int[] {
R.id.name,R.id.list_image});
KEY_COLUMN[1] is caption.
KEY_COLUMN[0] is id value. It must be hidden.
My problem is R.id.list_image.
I can set KEY_COLUMN[0] to src of R.id.list_image. But i want to set KEY_COLUMN[0] to contentDescription of R.id.list_image.
Can you help? I don't use lazyadaptor etc.
EDİT:
i have new problem. if i need 2 data for imageview, how can i use?
ListAdapter adapter = new SimpleAdapter(this, getXmlData(URL,KEY_ITEM,KEY_COLUMN),
R.layout.news_list,
new String[] { KEY_COLUMN[1],KEY_COLUMN[0],KEY_COLUMN[2] }, new int[] {
R.id.name,R.id.list_image,R.id.list_image});
KEY_COLUMN[0] set to setContentDescription of R.id.list_image
KEY_COLUMN[2] set to src of R.id.list_image

You'll need to use custom binder to do this. It can be accomplished with adding something like this in the next line:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// Log.v(TAG, "Binding view: " + view);
if (view.getId() == R.id.list_image) {
((ImageView) view).setContentDescription((CharSequence)) data);
return true;
}
return false;
}
});

Related

Adding Toast to Every ChildItem of a Multi Level Expandable LisView

I found this multilevel expandable listview which is very accurate with my project, but I also want to add a different toast to every third level (which is the last layer of view) child items. I tried this:
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(thirdLevelq1.put(q1[0] this, "The first child" , Toast.LENGTH_LONG).show();
return false;
}
});
But it gives error. I even tried to use same toast text to every childItem, app installed but crashed when I opened the adapter. So, how to add them properly?
Java:
package com.bacon.expandablelistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
String[] parent = new String[]{"What is View?", "What is Layout?", "What is Dynamic Views?"};
String[] q1 = new String[]{"List View", "Grid View"};
String[] q2 = new String[]{"Linear Layout", "Relative Layout"};
String[] q3 = new String[]{"Recycle View"};
String[] des1 = new String[]{"A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen."};
String[] des2 = new String[]{"Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent)."};
String[] des3 = new String[]{"This list contains linear layout information"};
String[] des4 = new String[]{"This list contains relative layout information,Displays a scrolling grid of columns and rows"};
String[] des5 = new String[]{"Under the RecyclerView model, several different components work together to display your data. Some of these components can be used in their unmodified form; for example, your app is likely to use the RecyclerView class directly. In other cases, we provide an abstract class, and your app is expected to extend it; for example, every app that uses RecyclerView needs to define its own view holder, which it does by extending the abstract RecyclerView.ViewHolder class."};
LinkedHashMap<String, String[]> thirdLevelq1 = new LinkedHashMap<>();
LinkedHashMap<String, String[]> thirdLevelq2 = new LinkedHashMap<>();
LinkedHashMap<String, String[]> thirdLevelq3 = new LinkedHashMap<>();
/**
* Second level array list
*/
List<String[]> secondLevel = new ArrayList<>();
/**
* Inner level data
*/
List<LinkedHashMap<String, String[]>> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//The problem starts here
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), "The first child", Toast.LENGTH_LONG).show();
return false;
}
});
setUpAdapter();
}
private void setUpAdapter() {
secondLevel.add(q1);
secondLevel.add(q2);
secondLevel.add(q3);
thirdLevelq1.put(q1[0], des1);
thirdLevelq1.put(q1[1], des2);
thirdLevelq2.put(q2[0], des3);
thirdLevelq2.put(q2[1], des4);
thirdLevelq3.put(q3[0], des5);
data.add(thirdLevelq1);
data.add(thirdLevelq2);
data.add(thirdLevelq3);
expandableListView = (ExpandableListView) findViewById(R.id.expandible_listview);
//passing three level of information to constructor
ThreeLevelListAdapter threeLevelListAdapterAdapter = new ThreeLevelListAdapter(this, parent, secondLevel, data);
expandableListView.setAdapter(threeLevelListAdapterAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
int previousGroup = -1;
#Override
public void onGroupExpand(int groupPosition) {
if (groupPosition != previousGroup)
expandableListView.collapseGroup(previousGroup);
previousGroup = groupPosition;
}
});
}
}
Thanks in advance.
Edit: When I use Toast.makeText(getApplicationContext(), "The first child", Toast.LENGTH_LONG).show(); its crash logs says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ExpandableListView.setOnChildClickListener(android.widget.ExpandableListView$OnChildClickListener)' on a null object reference
#Override
public void onFinalChildClick(int plpos, int slpos, int tlpos) {
String msg = "";
switch (tlpos) {
case 0:
msg = "Shakespear is a good poet";
break;
case 1:
msg = "Earth isn't flat";
break;
default:
msg = "Unknown";
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFinalItemClick(String plItem, String slItem, String tlItem) {
String inMsg = plItem + ", " + slItem + ", " + tlItem;
String outMsg = "";
if (inMsg.equals("group 1, Child Level 1, A")){
outMsg = "Shakespear is a good poet";
} else if (inMsg.equals("group 1, Child Level 1, B")){
outMsg = "Earth isn't flat";
} else {
outMsg = "Unknown";
}
Toast.makeText(this, outMsg, Toast.LENGTH_SHORT).show();
}
Please set this listener expandableListView.setOnChildClickListener after the expandableListView is initialized, that is after setUpAdapter() in your case as expandableListView is still null when you are trying to set the listener because your initialization of this is afterwards.
That is the reason for NullPointerException. because expandableListView is null while setting the listener.
Cheers

Using both OnTouchListener and OnClickListener

I have a recyclerview. After setting adapter, user should be reorder their list and save it. And afterwards it should be populate like saved one. But onclicking list items, it color has to change and one of item will open a popup. I've write my codes, but when i add both onclick and ontouch, neither of them worked. If i comment one of them, they work fine. How can i solve this?
holder.itemView.setOnTouchListener((v, event) -> {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
touchHelper.startDrag(holder);
}
return false;
});
holder.clData.setOnLongClickListener(view -> {
row_index = position;
notifyDataSetChanged();
return true;
});
if (row_index == position) {
holder.clData.setBackgroundColor(context.getResources().getColor(R.color.blue_back));
holder.txtAmount.setTextColor(Color.WHITE);
} else {
holder.clData.setBackgroundColor(context.getResources().getColor(R.color.darkestGrey));
holder.txtAmount.setTextColor(context.getResources().getColor(R.color.blue_current));
}
/// https://github.com/sjthn/RecyclerViewDemo/blob/advanced-usecases/app/src/main/java/com/example/srijith/recyclerviewdemo/SwipeAndDragHelper.java
////// My Adapter
AdapterDatas adapter = new AdapterDatas (context, lstDatas);
SwipeAndDragHelper swipeAndDragHelper = new SwipeAndDragHelper(adapter);
ItemTouchHelper touchHelper = new ItemTouchHelper(swipeAndDragHelper);
adapter.setTouchHelper(touchHelper);
rvDatas.setAdapter(adapter);
touchHelper.attachToRecyclerView(rvDatas);

Need Help Refreshing my database ListView in my app

My app layout apparently isn't a normal layout so I a having trouble setting my List Adapter to auto updated when an edit is made.
I make my edits to my database in this Java File which is controlled in its own activity and layout.
public void onClick(View view){
if (view == findViewById(R.id.addsave)) {
RecipeRepo repo = new RecipeRepo(this);
Recipe recipe = new Recipe();
if (editTextName.getText().toString().equals("")) {
editTextName.setError("Recipe name required!");
return;
} else {
recipe.name = editTextName.getText().toString();
}
if (textImagePath.getText().toString().equals("") ) {
recipe.image = ("");
}else{
recipe.image = textImagePath.getText().toString();
}
recipe.category = staticSpinner.getSelectedItem().toString();
if (editTextIngredients.getText().toString().equals("")) {
editTextIngredients.setError("Ingredient required!");
return;
} else {
recipe.ingredients = editTextIngredients.getText().toString();
}
if (editTextInstruct.getText().toString().equals("")) {
editTextIngredients.setError("Instruction required!");
return;
} else {
recipe.instructions = editTextInstruct.getText().toString();
}
recipe.cooktemp = editTextCookTemp.getText().toString();
recipe.cooktime = editTextCookTime.getText().toString();
recipe.serves = editTextServings.getText().toString();
recipe.recipe_Id = _Recipe_Id;
if (_Recipe_Id == 0) {
_Recipe_Id = repo.insert(recipe);
Toast.makeText(this, "New Recipe Added", Toast.LENGTH_SHORT).show();
finish();
it actually inserts and updates in this java file
int insert(Recipe recipe){
//Open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Recipe.KEY_SERVES, recipe.serves);
values.put(Recipe.KEY_COOKTIME, recipe.cooktime);
values.put(Recipe.KEY_COOKTEMP, recipe.cooktemp);
values.put(Recipe.KEY_INSTRUCT, recipe.instructions);
values.put(Recipe.KEY_INGREDIENTS, recipe.ingredients);
values.put(Recipe.KEY_CATEGORY, recipe.category);
values.put(Recipe.KEY_IMAGE, recipe.image);
values.put(Recipe.KEY_NAME, recipe.name);
//Inserting Row
long recipe_Id = db.insert(Recipe.TABLE, null, values);
db.close();// Closing database connection
return (int) recipe_Id;
}
void delete(int recipe_Id){
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(Recipe.TABLE, Recipe.KEY_ID + "=?", new String[] {String.valueOf(recipe_Id)});
db.close();
}
void update(Recipe recipe){
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Recipe.KEY_SERVES, recipe.serves);
values.put(Recipe.KEY_COOKTIME, recipe.cooktime);
values.put(Recipe.KEY_COOKTEMP, recipe.cooktemp);
values.put(Recipe.KEY_INSTRUCT, recipe.instructions);
values.put(Recipe.KEY_INGREDIENTS, recipe.ingredients);
values.put(Recipe.KEY_CATEGORY, recipe.category);
values.put(Recipe.KEY_IMAGE, recipe.image);
values.put(Recipe.KEY_NAME, recipe.name);
db.update(Recipe.TABLE, values, Recipe.KEY_ID + "=?", new String[]{String.valueOf(recipe.recipe_Id)});
db.close();
}
and lastly it gets put into the list view from this Java file and separate layout. Which is where my adapters are but i cannot get the notifyDataSetChanged() to work here at all... as in it wont even come up.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
RecipeRepo repo = new RecipeRepo(this);
if (id == R.id.nav_meat) {
final ArrayList<HashMap<String, String>> recipeList = repo.getRecipeMeat();
if(recipeList.size()!=0) {
ListView lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
recipe_Id = (TextView) view.findViewById(R.id.recipe_Id);
String recipeId = recipe_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(), RecipeDetail.class);
objIndent.putExtra("recipe_Id", Integer.parseInt(recipeId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter(SousChef.this, recipeList, R.layout.view_recipe_entry, new String[]{"id", "category", "name"}, new int[]{R.id.recipe_Id, R.id.recipe_list_category, R.id.recipe_list_name});
lv.setAdapter(adapter);
}else {
Toast.makeText(this, "No recipe!", Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.nav_veg) {
final ArrayList<HashMap<String, String>> recipeList = repo.getRecipeVeg();
if(recipeList.size()!=0) {
ListView lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
recipe_Id = (TextView) view.findViewById(R.id.recipe_Id);
String recipeId = recipe_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(), RecipeDetail.class);
objIndent.putExtra("recipe_Id", Integer.parseInt(recipeId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter(SousChef.this, recipeList, R.layout.view_recipe_entry, new String[]{"id", "category", "name"}, new int[]{R.id.recipe_Id, R.id.recipe_list_category, R.id.recipe_list_name});
lv.setAdapter(adapter);
}else {
Toast.makeText(this, "No recipe!", Toast.LENGTH_SHORT).show();
}
So any advise on setting this up to automatically update would be a huge help. I have been racking my brain over this for a couple days now looking at different examples and what not, but no setup is quite like this one which doesnt allow me to have everything in one file.
And thank you in advance.
category picking image:
Category picking Image
There are for sure more answers but this is one that might help,
Quick Example for the proposed solution
SHORT EXPLANATION
inside MainActivity
//create a public static adapter
public static ListAdapter adapter
inside onCreateView()
//Create your adapter and set it to the right ListView
ListView lv = findViewById(R.id.listView_in_xml);
adapter = new SimpleAdapter(...)
lv.setAdapter(adapter)
inside CustomAdapter which in your case I assume is SimpleAdapter
//add a public method to be called so that the Adapter updates and displays the new data
public void updateMethod(){
//update your List<Recipe> that I would guess you have calling the database again
//if needed update your getCount() return value so that it returns the number of childs in your ListView which most of the cases is just the List<Recipe>.size()
//notifyDataSetChanged()
}
inside your DB HANDLER CLASS
//in every update, add, delete or any method that requires the ListView to Update just call the created method,
MainActivity.CustomAdapter.updateMethod();
PROBLEMS
You will have to make sure the public static adapter has been initialized and is not null, or simply check whether the adapter is not null and update, because if the adapter is null that activity has not launched yet thus no need to trigger the updateMethod().
OTHER SOLUTIONS
Instead of creating a public static adapter create a public static boolean, then whenever data changes set that boolean to true from the database.
Finally, whenever you resume your activity check against that boolean and update your ListViewAdapter if needed.
MORE COMPLICATED SOLUTIONS WHICH I KNOW WORK CAUSE I USE IT
Use TaskAsyncTaskLoader which utilizes a Loader in your MainActivity and implements LoaderManager.LoaderCallbacks.
Optionally, you can make the Loader be, public static Loaderand inside your DBHandler you trigger the loader to load the data again or use any other logic you want.
Proofs of Working suggested solution,
You can Broadcast Intent from the change database file after you get the response in the onCreate() of adapter loading class
Intent intent = new Intent("key_to_identify_the_broadcast");
Bundle bundle = new Bundle();
bundle.putString("edttext", "changed");
intent.putExtra("bundle_key_for_intent", bundle);
context.sendBroadcast(intent);
and then you can receive the bundle in your fragment by using the BroadcastReceiver class
private final BroadcastReceiver mHandleMessageReceiver = new
BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle =
intent.getExtras().getBundle("bundle_key_for_intent");
if(bundle!=null){
String edttext = bundle.getString("edttext");
}
//you can call any of your methods for using this bundle for your use case
}
};
in onCreate() of your adapter adding class you need to register the broadcast receiver first otherwise this broadcast receiver will not be triggered
IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
getActivity().getApplicationContext().
registerReceiver(mHandleMessageReceiver, filter);
Finally you can unregister the receiver to avoid any exceptions
#Override
public void onDestroy() {
try {
getActivity().getApplicationContext().
unregisterReceiver(mHandleMessageReceiver);
} catch (Exception e) {
Log.e("UnRegister Error", "> " + e.getMessage());
}
super.onDestroy();
}

Android - Wanting to alternate icon images in a listview using cursorLoader

I have an application that displays a listView of contacts sorted by Last, then first names. Beside each contact is an image (icon). There are 3 kinds of contacts for which I'd like to display 3 different images (customers/suppliers/other) I have a default image now that is set to customer. I'm wondering if there's a way using the cusorLoader shown below to alternate images on the fly, or whether it would just be best to add a method involving a cursor in my onResume. (onResume is called each time I need to display the images). I believe simpleCursorAdapter can only take textViews as args, so if it's possible, maybe a compound textview/image would work. My icons are not stored in the database, just in the drawables.
Thanks in advance for any replies.
#Override
protected void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
getLoaderManager().restartLoader(0, null, this);
}
/*
* The fillData method binds the simpleCursorAadapter to the listView.
*/
private void fillData() {
String[] from = new String[] { ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
//The XML views that the data will be bound to:
int[] to = new int[] {R.id.label2, R.id.label};
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.contact_row, null, from,
to, 0);
setListAdapter(adapter);
}
// Sort the names by last name, then by first name
String orderBy = ContactsDB.COLUMN_LAST_NAME + " COLLATE NOCASE ASC"
+ "," + ContactsDB.COLUMN_FIRST_NAME + " COLLATE NOCASE ASC" ;
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { ContactsDB.ROW_ID, ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
CursorLoader cursorLoader = new CursorLoader(this,
SomeContentProvider.CONTENT_URI, projection, null, null, orderBy);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in.
// (The framework will take care of closing the old cursor once we return.)
adapter.swapCursor(data); //Call requires Min API 11
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed.
// Data is no longer available, delete the reference
adapter.swapCursor(null);
}
}
Here is the code I use to dynamically show a drawable on a ListView, you have to use the function setViewBinder on your adapter:
mAdapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
//Modification of the icon to display in the list
if (aColumnIndex == aCursor.getColumnIndex(DatabaseHandler.RATE_EMOTION)) {
int emotionID = aCursor.getInt(aColumnIndex);
Drawable emotionDrawable = resources.getDrawable(R.drawable.ic_unknown_rate);
//if emotion is set
if(emotionID > 0){
String emotionDrawablePath = "ic_smi" + emotionID;
int emotionDrawableID = resources.getIdentifier(emotionDrawablePath,"drawable", getPackageName());
//if a drawable is found
if(emotionDrawableID > 0){
emotionDrawable = resources.getDrawable(emotionDrawableID);
}
}
ImageView emotionImage = (ImageView) aView;
emotionImage.setImageDrawable(emotionDrawable);
return true;
}
return false;
}
});
You can see in this example that I change the drawable according to the data I get from the cursor for every row.

How to display data fetched from the database table into listview?

My Function In SQLAdapter class is
public ArrayList<Airline> getairlinedetails(String bookingdate) {
Cursor curCalllog =db.rawQuery("SELECT * FROM "+ BOOK +
" WHERE " + date +
" BETWEEN '" + startdate + "' AND '" + enddate + "'", null);
if (curCalllog != null) {
if (curCalllog.moveToFirst()) {
do {
a=new Airline();
//a.setBookingdate(curCalllog.getString(1));
a.setPickupadd(curCalllog.getString(2));
a.setCity(curCalllog.getString(3));
a.setTrip(curCalllog.getString(4));
a.setFdate(curCalllog.getString(5));
a.setFtime(curCalllog.getString(6));
a.setCdate(curCalllog.getString(7));
a.setPtime(curCalllog.getString(8));
a.setSeats(curCalllog.getInt(9));
a.setAmount(curCalllog.getInt(10));
update.add(a);
} while (curCalllog.moveToNext());
}
}
return update;
}
M Fetching data between two dates and
I Want To show the fetched data into listview please help me how to do it I m new in android development.
You can use SimpleCursorAdapter for showing Databse contents in Listview. Make instance of SimpleCursorAdapter and pass Cursor object into it. Refer this link
If you want Customized Listview, you can customize SimpleCursorAdapter by extending this with your custom adapter class.
you can follow this example :
DataManipulator.java -helper class
//to retrieve data in a list
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
null, null, null, null, "name asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
CheckData.java
// to show data in a list view
public class CheckData extends ListActivity {
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,
stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
selection.setText(stg1[position]);
}
}
follow this link for complete tutorial
I assume you are getting data from database and there by complete ArrayList with Airline objects.
Now to display data in ListView from ArrayList<Airline>, you have to define Custom adapter class by extending either BaseAdapter or ArrayAdapter.
Here you go: How to define custom adapter for ListView?
I Want To show the fetched data into listview please help me how to do
it I m new in android development
Simpliest way is to use ArrayAdapter with build-in ListView's row layout.
ListView list = (ListView) findViewById(R.id.yourList);
ArrayList<Airline> data = db.getairlinedetails("someString");
ArrayAdapter<Airline> adapter = new ArrayAdapter<Airline>(this,
android.R.layout.simple_list_item_1, data);
list.setAdapter(adapter);
But since this you need to also override toString() method in your Airline class.
Reason is that your ArrayAdapter will convert each child(provided list of airlines) to String and if you won't override toString() you will get default string representation of object but you probably need to show for instance name of airline so your method can looks like
#Override
public String toString() {
return this.name;
}
Note:
This is simple way. But if you want to get more control over ListView and create custom list i recommend you to create own subclass of ListAdapter for example BaseAdapter and define your own Adapter. Sorry but i won't write you implementation because it requires much more code but nice examples you can find here:
Customizing Android ListView Items with Custom ArrayAdapter
Android ListView, ListActivity and ListFragment - Tutorial
Android Custom ListView with Image and Text

Categories