I am working on a project where I am displaying a list of Car owners. Upon accessing the application, an empty list is displayed. The user search for an owner, and we display all available owners that matche the search criteria.
The issue that I ran into is that the owner list is updated, but it also show "No record to be displayed" which is what an empty list is supposed to show. What I am missing here?
Here are the relevant classes
public class OwnerDetail extends ListFragment {
ListView mListView;
ArrayList<Owner> listItem = new ArrayList<Owner>();
public OwnerAdapter ownerAdapter;
private String[] searchParameter = null;
public void SearchParameters(String[] parameters)
{
searchParameter = parameters;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v1 = inflater.inflate(R.layout.customize_layout,container, false);
mListView = (ListView) v1.findViewById(android.R.id.list);
return v1;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail, listItem);
if(!(searchParameter == null))
{
ownerAdapter.clear();
ownerAdapter.addAll(listItem);
new OnwerAsyncTask().execute();
ownerAdapter.notifyDataSetChanged();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mListView.setAdapter(ownerAdapter);
ownerAdapter.notifyDataSetChanged();
}
private class OnwerAsyncTask extends AsyncTask<Void, Void, List<Owner>> {
#Override
protected List<Owner> doInBackground(Void... params) {
try
{
Owner items = new Owner();
items.setFirstName("John");
items.setLastName("Smith");
items.setCarId("1");
listItem.add(items);
Owner item1 = new Owner();
item1.setFirstName("Samantha");
item1.setLastName("Right");
item1.setCarId("2");
listItem.add(item1);
Owner item2 = new Owner();
item2.setFirstName("Regie");
item2.setLastName("Miller");
item2.setCarId("3");
listItem.add(item2);
Owner item3 = new Owner();
item3.setFirstName("Mark");
item3.setLastName("Adam");
item3.setCarId("4");
listItem.add(item3);
} catch(Exception ex)
{
ex.toString();
}
return listItem;
}
#Override
protected void onPreExecute() {
listItem.clear();
ownerAdapter.clear();
super.onPreExecute();
}
#Override
protected void onPostExecute(List<Owner> result) {
/*OwnerDetail fragment = (OwnerDetail) mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.SetAdapter(result);*/
super.onPostExecute(result);
if(listItem.size() > 0)
{
ownerAdapter.notifyDataSetChanged();
}
}
}
}
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText(item.getLastName());
holder.tvCId.setText(item.getCarId());
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
Edit on 08/06/2013
I updated the OwnerDetail class and added the asyncktask as a private inner class. It displayed the list, but it showed the "No Record to be displayed" too.
owner_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// customize_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:text="No record to be displayed."
/>
</LinearLayout>
You are not adding data to adapter in onPostExecute:
#Override
protected void onPostExecute(List<Owner> result) {
super.onPostExecute(result);
ownerAdapter.clear();
ownerAdapter.addAll(result);
ownerAdapter.notifyDataSetChanged();
Log.i("TESTING","Added " + result.size() + " items to adapter");
}
Also, I see you are using custom list layout, make sure empty TextView has id #android/id/empty and visibility set to gone.
You have to refresh the Adapter because when you create the Fragment owner will be null and so the fragment is initialized with the empty row.
Modify your SetAdapter(Owner[] o) as follows:
public void SetAdapter(Owner[] o) {
owner = o;
ownerAdapter.clear();
ownerAdapter.addAll(o);
ownerAdapter.notifyDataSetChanged();
}
Related
I am coding a listView that gets the data from mySQL Server.
I have created the followings classes.
Class ListView. It has two contractors all in Strings. And I sat getters and setters.
I believe I have a problem with the Adapter its self. I can click on more than one option. While I have created the custom adapter in the layout as the followings:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/RG_Adapter"
android:layoutDirection="rtl"
android:orientation="horizontal">
<RadioButton
android:id="#+id/TRIP_NAME"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:textAlignment="center"
android:textSize="25sp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/SUM_TRIPS"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textColor="#000000"
android:textAlignment="center"
android:textSize="25sp" />
</RadioGroup>
I believe my problem is with the Adapter class.
I have created it like the followings:
public class TRIPS_LISTVIEW_ADAPTER extends ArrayAdapter<TRIPS_LISTVIEW> {
private Context mContext;
private ArrayList<TRIPS_LISTVIEW> mData;
private MyFunctionsClass myFunctionsClass = new MyFunctionsClass();
public TRIPS_LISTVIEW_ADAPTER (Context mContext, ArrayList<TRIPS_LISTVIEW> mData) {
super(mContext, R.layout.summary_shape_layout,mData);
this.mContext = mContext;
this.mData = mData;
}
public int getCount() {
return mData.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.summary_shape_layout, null);
}
RadioGroup RG = (RadioGroup) convertView.findViewById(R.id.RG_Adapter);
TextView TRIP_NAME = (TextView) convertView.findViewById(R.id.TRIP_NAME);
TRIP_NAME.setTypeface(myFunctionsClass.FONT( TRIP_NAME.getContext().getAssets(),1));
TRIP_NAME.setText(myFunctionsClass.get_The_trip(mData.get(position).getTRIP_TITLE()));
TextView SUM_TRIPS = (TextView) convertView.findViewById(R.id.SUM_TRIPS);
SUM_TRIPS.setTypeface(myFunctionsClass.FONT( SUM_TRIPS.getContext().getAssets(),1));
SUM_TRIPS.setText(mData.get(position).getTRIP_COUNT());
return convertView;
}
}
The Data in my MainActivity Class are retrieved correctly. But as I mentioned I have multiple mode selection.
Try the following:
1) Demo2.class:-------------
public class Demo2 extends AppCompatActivity {
private ListView lv;
private CheckBox cb;
private Adapter adapter;
private List<Boolean> checkBoxState;
private List<String> checkBoxText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo2);
checkBoxState = new ArrayList<>();
checkBoxText = new ArrayList<>();
for(int i = 0 ; i<10 ; i++){
if(i == 0) {
checkBoxState.add(i, true);
}else{
checkBoxState.add(i , false);
}
checkBoxText.add( i , "C" + (i+1));
}
lv = (ListView) findViewById(R.id.lv);
adapter = new Adapter(getApplicationContext() , checkBoxState , checkBoxText);
lv.setAdapter(adapter);
}
}
2) Adapter.class:------
public class Adapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<Boolean> checkBoxState;
private List<String> checkBoxText;
public Adapter(Context context, List<Boolean> checkBoxState , List<String> checkBoxText) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.checkBoxState = checkBoxState;
this.checkBoxText = checkBoxText;
}
public int getCount() {
return checkBoxState.size();
}
public Object getItem(int position) {
return checkBoxState.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final CheckBox cb_list_item;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.list_item, null);
}
}
cb_list_item = (CheckBox) view.findViewById(R.id.cb_list_item);
cb_list_item.setText(checkBoxText.get(position));
cb_list_item.setOnCheckedChangeListener(null); // mask onCheckedChangeListener()
cb_list_item.setChecked(checkBoxState.get(position));
cb_list_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!b) { // already selected
compoundButton.setChecked(true);
} else { // is selected now
checkSelected(position);
}
}
});
return view;
}
private void checkSelected(int position){
try {
for (int i = 0; i < checkBoxState.size(); i++) {
checkBoxState.set(i, false);
}
checkBoxState.set(position, true);
this.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
}
}
}
3) demo2.xml:------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lv"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
</ListView>
</LinearLayout>
4) list_item.xml:----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="C"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/cb_list_item"/>
</android.support.constraint.ConstraintLayout>
5) Output:--------
I'm trying to create simple list of Objects which i created
the objects are ShopListItem, this is the code of the class:
public class ShopListItem {
private String name;
private double price;
public ShopListItem(String name , double price)
{
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
}
this is the ArrayAdatpter class:
public class shopItemAdapter extends ArrayAdapter<ShopListItem> {
public shopItemAdapter(Context context, ArrayList<ShopListItem> items){
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ShopListItem item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shop_item_row, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.itemName);
TextView price = (TextView) convertView.findViewById(R.id.itemPrice);
name.setText(item.getName());
price.setText(String.valueOf(item.getPrice()));
return convertView;
}
}
and this is my activity which is supposed to display this list:
public class check extends Activity {
ListView items = (ListView)findViewById(R.id.items);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ShopListItem item1 = new ShopListItem("milk" , 5.9);
ShopListItem item2 = new ShopListItem("bamba" , 4);
ArrayList<ShopListItem> list = new ArrayList<ShopListItem>();
list.add(item1);
list.add(item2);
shopItemAdapter adapter = new shopItemAdapter(this , list);
items.setAdapter(adapter);
}
}
I open the activity from another activity when user clicks a button, this is the on click method:
public void openList(View view){
Intent intent = new Intent(HomeActivity.this , check.class);
this.startActivity(intent);
}
shop_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF9F9F9"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/itemName"
android:layout_weight="0.61"
android:layout_margin="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/itemPrice"
android:layout_margin="5dp" />
</LinearLayout>
and content_check.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="atoa.roomates.QA"
tools:showIn="#layout/activity_q">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/items"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
thank you!
You are accessing view ListView items = (ListView)findViewById(R.id.items); before onCreate(). So move that line in onCreate method after setContentView().
initialize your list in setContentView instead of top
like following
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_demo);
items = (ListView) findViewById(R.id.items);
after change this work fine.
public class shopItemAdapter extends ArrayAdapter<ShopListItem> {
private Context mContext;
private List<ShopListItem> mListShop;
public shopItemAdapter(Context context, int resource, ArrayList<ShopListItem> items){
super(context, resource, items);
this.mContext= context;
this.mListShop = items;
}
#Override
public int getCount() {
return mListShop.size();
}
#Override
public ShopListItem getItem(int position) {
return mListShop.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.shop_item_row, null);
holder = new ViewHolder();
holder.mTextPrice = (TextView) view.findViewById(R.id.itemPrice);
holder.mTextName = (TextView) view.findViewById(R.id.itemName);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ShopListItem item = getItem(position);
holder.mTextName.setText(item.getName());
holder.mTextPrice.setText(item.getPrice());
return view;
}
public class ViewHolder {
public TextView mTextPrice;
public TextView mTextName;
}
}
In your Activity
public class check extends Activity {
ListView items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
items = (ListView)findViewById(R.id.items);
ShopListItem item1 = new ShopListItem("milk" , 5.9);
ShopListItem item2 = new ShopListItem("bamba" , 4);
ArrayList<ShopListItem> list = new ArrayList<ShopListItem>();
list.add(item1);
list.add(item2);
shopItemAdapter adapter = new shopItemAdapter(this , R.layout.shop_item_row, list);
items.setAdapter(adapter);
}
}
Try it!!!!
I have a custom row item xml and a Activity xml which has a button, a textbox and a listview. Can anybody give me a very simple example on how this is done? I know i will need a adapter (what it extends i dont know) and update it from the button
I have tried getting the list view updated from the button with the editview text but cant get the adapter code to be hit. I am looking at base adapters now but cant help but feel this shouldn't be complicated and need so many override methods.
Activity class
public class InvitePlayers_Activity extends Activity {
ListViewAdapter emailAdapter = null;
ImageView imgView_mail;
ImageView imgView_confirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //remove title bar
setContentView(R.layout.activity_inviteplayers);
//Generate list View from ArrayList
displayListView();
}
private void displayListView() {
//assign controls
final ListView listView = (ListView) findViewById(R.id.listView_invitePlayers);
imgView_mail = (ImageView)findViewById(R.id.imgView_mail);
//Test data
ArrayList<String> inviteNew = new ArrayList<String>();
final ArrayList<ArrayList<String>> inviteList = new ArrayList<ArrayList<String>>();
emailAdapter = new ListViewAdapter(this,inviteList);
listView.setAdapter(emailAdapter);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
//Edit listeners
imgView_mail.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
//variables
final String enteredMail = "testListViewEntry";
final ArrayList<ArrayList<String>> inviteList = new ArrayList<ArrayList<String>>();
ArrayList<String> invite = new ArrayList<String>();
invite.add(0, enteredMail);//add first email
invite.add(1,"icon_invitestatussent.png"); //add first status icon
inviteList.add(invite);
emailAdapter.notifyDataSetChanged();
listView.setAdapter(emailAdapter);
}
});
}
}
Adapter class
public class ListViewAdapter extends BaseAdapter {
private Activity context;
ArrayList<ArrayList<String>> inviteDetails = new ArrayList<ArrayList<String>>();
public ListViewAdapter(Activity context, ArrayList<ArrayList<String>> inviteDetails ) {
this.inviteDetails = inviteDetails;
this.context = context;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public View getView(int position, View view, ViewGroup parent){
//Inflater
LayoutInflater inflater = context.getLayoutInflater();
//get row view
if (view == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.list_item_email, null);
}
//assign controls
final TextView textView_playerEmail = (TextView) view.findViewById(R.id.textView_playerEmail);
ImageView imgView_inviteStatus = (ImageView) view.findViewById(R.id.imgView_inviteStatus);
//Assign control values that are dynamic
textView_playerEmail.setText(inviteDetails.get(position).get(0));
imgView_inviteStatus.setImageResource(R.drawable.icon_invitestatussent);
return view;
}
public ArrayList<ArrayList<String>> addInvite(ArrayList<String> inviteDetails, ArrayList<ArrayList<String>> currentInvites)
{
currentInvites.add(inviteDetails);
return currentInvites;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Custom row xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:id="#+id/textView_playerEmail"
android:textColor="#color/white"
android:text="item1">
</TextView>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView_inviteStatus" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView_remove"
android:src="#drawable/btn_cancel" />
Activity layout
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:gravity="left|center">
<ImageView
android:layout_width="45dp"
android:layout_height="34dp"
android:id="#+id/imgView_mail"
android:src="#drawable/btn_mail"
android:layout_weight="0.22"
android:padding="3dp" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView_invitePlayers"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/btn_confirm"
android:src="#drawable/btn_confirm"
android:clickable="false"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:padding="2dp"
android:layout_weight="1" />
</LinearLayout>
From reading the description of the question I think you need to set custom adapter to show the elements in you listview. This is how you set the custom adapter for the listview:
public class Notes_list extends BaseAdapter
{
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public Notes_list(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname)
{
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
return id.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int pos, View child, ViewGroup arg2) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.custom_row, null);
mHolder = new Holder();
// mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
child.setTag(mHolder);
} else
{
mHolder = (Holder) child.getTag();
}
// mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
return child;
}
public class Holder
{
// TextView txt_id;
TextView txt_fName;
TextView txt_lName;
}
}
now in your main activity where you have to call the list enter code like this:
private ListView userList;
private ArrayList<Employee> itemsList = new ArrayList<modelName>();
userList = (ListView) findViewById(R.id.List);
UserList disadpt = new UserList(MainActivity.this, itemsList);
userList.setAdapter(disadpt);
Hope it helps...
I am using CustomArrayAdapter with ListView. But, even after setting setAdapter it is not working. Following are my code snippets:
PastOrders.java Fragment displaying listView
public class PastOrders extends Fragment {
private View view;
private ListView pastOrdersList;
private Context context;
private ArrayList<Order> orders;
public PastOrders() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.fragment_pastorders, container, false);
context = getActivity();
pastOrdersList = (ListView) view.findViewById(R.id.pastOrdersList);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Order");
query.whereEqualTo("user_id", Vars.currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e != null) {
Log.e("TAG", e.getLocalizedMessage());
} else {
ArrayList<Order> orders = new ArrayList<Order>();
Log.i("TAG", objects.toString());
for (ParseObject object: objects) {
Order temp = new Order();
temp.orderId = object.getObjectId();
temp.date = object.getCreatedAt();
temp.status = object.getString("status");
Log.i("TAG", "orderID: "+ object.getObjectId() + " temp orderID"+ temp.orderId);
orders.add(temp);
Vars.pastOrders.add(object);
}
Log.i("TAG", "after for loop past orders: "+ orders.toString());
PastOrdersAdapter pastOrdersAdapter = new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, orders);
pastOrdersList.setAdapter(pastOrdersAdapter);
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
PastOrdersAdapter.java Custom Adapter
public class PastOrdersAdapter extends ArrayAdapter<Order> {
private Context context;
private ViewHolder holder;
//private ArrayList<Order> orders;
public PastOrdersAdapter(Context context, int resource, List<Order> orders) {
super(context, resource);
// this.orders = orders;
Log.i("TAG", "POA adapter called");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("TAG", "getView from POA");
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater
.inflate(R.layout.past_orders_row, parent, false);
holder = new ViewHolder();
holder.orderId = (TextView) convertView.findViewById(R.id.orderId);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.details = (ImageView) convertView.findViewById(R.id.details);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject order = Vars.pastOrders.get(position);
Log.i("TAG", "order id in adapter: "+ order.getObjectId());
if(order != null) {
holder.orderId.setText(order.getObjectId());
holder.date.setText(getFormattedDate(order.getCreatedAt()));
holder.status.setText(order.getString("status"));
if(order.getString("status").equals("Delivered")) {
holder.status.setTextColor(Color.GREEN);
} else if(order.getString("status").equals("Cancelled")) {
holder.status.setTextColor(Color.RED);
} else {
holder.status.setTextColor(Color.YELLOW);
}
}
return convertView;
}
static class ViewHolder {
TextView orderId;
TextView date;
TextView status;
ImageView details;
}
}
Order.java
public class Order {
public String orderId;
public Date date;
public String status;
}
fragment_pastorders.xml Layout File for Fragment showing ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/pastOrdersList"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
past_orders_row.xml Layout file for each row of listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="150dp"
android:orientation="vertical"
android:id="#+id/LinearLayout01">
<TextView
android:id="#+id/orderId"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textStyle="italic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/status"/>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_next_item"
android:layout_toRightOf="#id/LinearLayout01"
android:layout_centerVertical="true"
android:id="#+id/details"/>
</RelativeLayout>
I have tried printing getCount() as well and it is non-zero. I have tried everything. Kindly help
Thanks,
Arpit
In the constructor of your custom adapter, your forgot to pass your orders parameter to the parent constructor. So your adapter does not know what to display.
You are passing empty list orders to you adapter. And then in adapter you are using different list: Vars.pastOrders.
So your adapter has empty list.
Replace this:
PastOrdersAdapter pastOrdersAdapter =
new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, orders);
with this:
PastOrdersAdapter pastOrdersAdapter =
new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, Vars.pastOrders);
I've got a custom BaseAdapter and an add button in the main activity. The button opens a dialog with a textbox and you can add new elements to the list that way. The problem is that the list is not refreshing. In the onActivityResult() function I print the number of elements in the list and each time I hit OK in the dialog box the number increases, so I know it's just the refreshing that doesn't work. My BaseAdapter and my activity:
class ListaOrase extends BaseAdapter{
private Activity context;
ArrayList<String> orase;
public ListaOrase(Activity context){
this.context=context;
orase=new ArrayList<String>();
}
public void add(String string){
orase.add(string);
this.notifyDataSetChanged();
}
public View getView (int position, View convertView, ViewGroup list) {
View element;
if (convertView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
element = inflater.inflate(R.layout.lista, null);
}
else element = convertView;
TextView elementLista=(TextView)element.findViewById(R.id.elementLista);
elementLista.setText(orase.get(position));
return element;
}
}
public class WeatherAppActivity extends ListActivity {
Button buton;
ListaOrase lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lista=new ListaOrase(this);
buton=(Button)findViewById(R.id.buton);
lista.add("Bucuresti");
lista.add("Sibiu");
setListAdapter(lista);
}
public void add(View view){
Intent intent=new Intent();
intent.setClass(this, Adauga.class);
startActivityForResult(intent, 0);
}
public void onActivityResult (int requestCode, int responseCode, Intent data){
System.out.println("Apelata");
if(responseCode==1){
lista.add(data.getStringExtra("oras")); // e chiar getText()
System.out.println(lista.getCount());
lista.notifyDataSetChanged();
}
}
}
As you can see, I'm trying to refresh (notifyDataSetChanged();) both when adding a new element (in the BaseAdapter extending class) and in method onActivityResult, after the dialog passes the new element to the main Activity. I repeat, the element IS added to the list because the count increases, it just doesn't refresh.
Thanks for your answers!
It's normal that it doesn't refresh, you are adding an item to "lista" but the adapter keeps its own copy of that list, so or you set again the list in the adapter and then you call notifyDataChanged or you add the new item to the adapter.
Anyway I see couple of weird things, I thing you could semplify everything using an array adapter, you don't need to implement add,etc. I wrote some code simplyfing yours:
public class WeatherAppActivity extends ListActivity {
Button buton;
ItemsAdapter lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> initialList = new ArrayList<String>();
initialList.add("Bucuresti");
initialList.add("Sibiu");
lista=new ItemsAdapter(this, initialList);
buton=(Button)findViewById(R.id.button1);
buton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista.add(""+System.currentTimeMillis()); // e chiar getText()
lista.notifyDataSetChanged();
}
});
setListAdapter(lista);
}
class ItemsAdapter extends ArrayAdapter<String> {
public ItemsAdapter(Context context, List<String> list) {
super(context, R.layout.lista, list);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
}
}
These are the xml that I have used:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Button" />
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
lista.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
This is the version of the adapter using a baseadapter:
class ItemsBaseAdapter extends BaseAdapter {
private List<String> items;
private Context mContext;
public ItemsBaseAdapter(Context context, List<String> list) {
items = list;
mContext = context;
}
public void addItem(String str) {
items.add(str);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = (String) getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
And this is the version of the list item wich also include an imageview on the left:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:layout_height="wrap_content"
android:src="#android:drawable/btn_star_big_on"
android:scaleType="fitCenter"
android:layout_width="wrap_content"
/>
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>