List view inside Fragment is not getting populated - android

I am trying to populate a ListView and display it under Fragment. I see that the count is returning correctly (greater than 0) after calling the adapter. Initially I had an issue with getView not being called but it was in a way resolved by changing layout_height to wrap_content as suggested by one of the article. I see that getView is now called while swiping for one Fragment to another. But getView doesn't get called when the Fragment is initially loaded. and also I don't ListView is displayed on screen regardless of any action.
First Fragment:
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
//private ListView mListView;
GridView grid;
String[] web = {
"Doctors","Movies","Dentists"} ;
int[] imageId = {
R.mipmap.doctors,
R.mipmap.dentists,
R.mipmap.restaurants
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
CustomGrid adapter = new CustomGrid(view.getContext(), iconSize);
GridView gridview = (GridView) view.findViewById(R.id.grid);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(), "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
ListItemMainFragment nextFrag = new ListItemMainFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(((ViewGroup) getView().getParent()).getId(), nextFrag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);// it will anim while calling fragment.
ft.addToBackStack(null); // it will manage back stack of fragments.
ft.commit();
}
});
return view;
}
}
Next Fragment:
public class ListItemMainFragment extends Fragment implements Item.DataListener {
private ListView mListView;
private ItemAdapter adapter;
public ListItemMainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item_main, container, false);
mListView = (ListView) view.findViewById(R.id.item_list_view);
mListView.setAdapter(adapter);
//final String DBReference = "all/" + position + "/" + web[+position];
final String DBReference = "all/0/Doctors";
Item.getRecipesFromDB(ListItemMainFragment.this, DBReference);
return view;
}
#Override
public void newDataReceived(ArrayList<Item> itemList) {
adapter = new ItemAdapter(getActivity(), itemList);
mListView.setAdapter(adapter);
Log.d("records ", String.valueOf((adapter.getCount())));
}
}
Adapter:
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Item> mDataSource;
public ItemAdapter(Context context, ArrayList<Item> items) {
Log.d("MyApp", "I am here1000A");
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//1
#Override
public int getCount() {
return mDataSource.size();
}
//2
#Override
public Object getItem(int position) {
return mDataSource.get(position);
}
//3
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get view for row item
View rowView = mInflater.inflate(R.layout.list_item_detail, parent, false);
Log.d("MyApp", "I am here1000");
TextView titlePrefixTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_title_prefix);
TextView titleTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_title);
TextView specialityTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_speciality);
TextView addressTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_address);
TextView distanceTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_distance);
TextView timingsTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_timings);
TextView contactTextView =
(TextView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_contact);
// Get thumbnail element
//ImageView thumbnailImageView =
// (ImageView) rowView.findViewById(com.ferainc.kudla.R.id.item_list_thumbnail);
Item item = (Item) getItem(position);
titlePrefixTextView.setText(String.valueOf(position+1) + ".");
titleTextView.setText(item.title);
specialityTextView.setText(item.speciality);
addressTextView.setText(item.address);
distanceTextView.setText(item.distance);
timingsTextView.setText(item.timings);
contactTextView.setText(item.contact);
return rowView;
}
}
Item.java:
public class Item {
public String title;
public String speciality;
public String timings;
public String address;
public String contact;
public String distance;
public interface DataListener {
void newDataReceived(ArrayList<Item> itemList);
}
public Item () {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
public String getTitle() {
return title;
}
public String getSpeciality() { return speciality; }
public String getTimings() {
return timings;
}
public String getAddress() { return address; }
public String getContact() { return contact; }
public String getDistance() { return distance; }
public static void getRecipesFromDB(final DataListener dataListener, String DBReference){
final ArrayList<Item> itemList = new ArrayList<>();
final DatabaseReference mDatabase;
final Item item = new Item();
mDatabase = FirebaseDatabase.getInstance().getReference(DBReference);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("There are " + snapshot.getChildrenCount() + " recipes");
Log.d("MyApp", "I am here100");
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Item post = postSnapshot.getValue(Item.class);
Item item = new Item();
item.title = post.getTitle();
item.speciality = post.getSpeciality();
item.timings = post.getTimings();
item.address = post.getAddress();
item.contact = post.getContact();
item.distance = post.getDistance();
itemList.add(item);
}
// Transaction complete, sending to listener
dataListener.newDataReceived(itemList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}
ListView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.ferainc.kudla.ListItemMainFragment">
<ListView
android:id="#+id/item_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
ListView Item detail:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#android:color/holo_green_light"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:id="#+id/list_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#android:color/holo_green_light">
<TextView
android:id="#+id/item_list_title_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:textSize="18sp"
android:textColor="#android:color/holo_red_light"
tools:text="Title" />
<TextView
android:id="#+id/item_list_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_toEndOf="#id/item_list_title_prefix"
android:textSize="18sp"
android:textColor="#android:color/holo_red_light"
tools:text="Title" />
<TextView
android:id="#+id/item_list_speciality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_title"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:textColor="#000000" />
<View
android:id="#+id/center_divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/item_list_speciality"
android:background="#android:color/darker_gray" />
<TextView
android:id="#+id/item_list_contact_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/center_divider"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Ph:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_contact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/center_divider"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_contact_prefix"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_address_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_contact"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Address:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_contact"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_address_prefix"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_distance_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_address"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Distance:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_address"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_distance_prefix"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_timings_prefix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_distance"
android:layout_marginTop="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:text="Timings:"
android:textColor="#fff092b0" />
<TextView
android:id="#+id/item_list_timings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/item_list_distance"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="4dp"
android:layout_toEndOf="#id/item_list_timings_prefix"
android:textColor="#fff092b0" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

I am not sure what you wanted by Item.getRecipesFromDB(ListItemMainFragment.this, DBReference);
as there is no code regarding "Items" it your Fragment.
But it think it doesn't populate your ListView.
So after ListView initialisation you have to create an adapter (it is missing in your onCreateView). And then set it onto ListView.
You also may try to call newDataReceived() from onCreteView.
But I suggest you to create the Adapter in onCreteView and then in newDataReceived() you can just update data and call notifyDataSetChanged() instead of creating new one each time

Related

trying to iterate spinners RecycleView by clicking a button miss few items

PLEASE READ THE EDIT SECTION BELLOW
I have a Spinners Recyclerview (list) I want to iterate after clicking a button(finishBtn).
in order to get the selected results entered by the user, I try to iterate the list using list.findViewHolderForAdapterPosition.
The size of the list is supposed to be 6 (by viewing Recyclerview I can see all 6) but when I try to iterate, the size is smaller than what actually there is. (instead of 6 the list.getChildCount() is only 3).
Fragment:
public class FragmentUserDetails extends Fragment {
Button finishBtn;
LinkedHashMap<String, ArrayList<String>> detailsQuestions;
DetailsViewModel detailsViewModel;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
detailsViewModel = new ViewModelProvider(this).get(DetailsViewModel.class);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_details, container, false);
detailsQuestions =getQuestions();
Log.d("TAG", "size: "+detailsQuestions.size());
RecyclerView list = view.findViewById(R.id.details_list_rv);
list.setHasFixedSize(true);
list.setLayoutManager(new LinearLayoutManager(getContext()));
DetailsAdapter detailsAdapter = new DetailsAdapter(this);
list.setAdapter(detailsAdapter);
finishBtn = view.findViewById(R.id.userDetails_next_btn);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
finishBtn.setOnClickListener(v -> {
Log.d("TAG", ""+list.getChildCount());
for (int i = 0; i < list.getChildCount(); i++) {
DetailsHolder holder = (DetailsHolder) list.findViewHolderForAdapterPosition(i);
if (holder!=null) {
String question = (String) detailsQuestions.keySet().toArray()[i];
Log.d("TAG", "The answer for " +question+"is :"+ holder.questionSp.getSelectedItem().toString());
}
}
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
});
return view;
}
interface OnItemClickListener {
void onItemClick(int position);
}
public LinkedHashMap<String, ArrayList<String>> getQuestions() {
ArrayList<Detail> arrayList = detailsViewModel.getDetails();
detailsQuestions = new LinkedHashMap<>();
for (Detail detail : arrayList) {
detailsQuestions.put(detail.getQuestion(), detail.getAnswers());
}
return detailsQuestions;
}
}
Adapter:
class DetailsAdapter extends RecyclerView.Adapter<DetailsHolder> {
private final FragmentUserDetails fragmentUserDetails;
FragmentUserDetails.OnItemClickListener listener;
public DetailsAdapter(FragmentUserDetails fragmentUserDetails) {
this.fragmentUserDetails = fragmentUserDetails;
}
public void setOnItemClickListener(FragmentUserDetails.OnItemClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public DetailsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = fragmentUserDetails.getLayoutInflater().inflate(R.layout.details_list_row, parent, false);
DetailsHolder detailsHolder = new DetailsHolder(view, listener);
return detailsHolder;
}
#Override
public void onBindViewHolder(#NonNull DetailsHolder detailsHolder, int position) {
if(fragmentUserDetails.detailsQuestions.size()!=0) {
String detail = (String) fragmentUserDetails.detailsQuestions.keySet().toArray()[position];
fragmentUserDetails.detailsQuestions.get(detail).add(0,detail);
String[] array = fragmentUserDetails.detailsQuestions.get(detail).toArray(new String[0]);
ArrayAdapter adapter = new ArrayAdapter<String>(fragmentUserDetails.getContext(), R.layout.spinner_item, array){
#Override
public boolean isEnabled(int position) {
if (position == 0) {
return false;
} else {
return true;
}
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
} else {
tv.setTextColor(Color.WHITE);
}
return view;
}};
detailsHolder.questionSp.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_item);
}
}
#Override
public int getItemCount() {
return fragmentUserDetails.detailsQuestions.size();
}
}
Holder:
class DetailsHolder extends RecyclerView.ViewHolder {
Spinner questionSp;
public DetailsHolder(#NonNull View itemView, FragmentUserDetails.OnItemClickListener listener) {
super(itemView);
questionSp = itemView.findViewById(R.id.listrow_question_sp);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onItemClick(pos);
}
});
}
}
details_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true">
<Spinner
android:id="#+id/listrow_question_sp"
android:layout_width="409dp"
android:layout_height="90dp"
android:layout_weight="1"
android:clickable="true"
android:drawablePadding="14dp"
android:focusable="true"
android:maxLines="1"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:spinnerMode="dialog"
android:textSize="18sp"
android:theme="#style/mySpinnerItemStyle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_user_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:background="#color/black"
tools:context=".details.FragmentUserDetails">
<ImageView
android:id="#+id/userDetails_img_main"
android:layout_width="306dp"
android:layout_height="160dp"
android:layout_marginTop="30dp"
android:src="#drawable/logo__nobg_2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/homeScr_text_title"
android:layout_width="350dp"
android:layout_height="90dp"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:text="Please enter the following details:"
android:textColor="#color/white"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/userDetails_img_main" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/details_list_rv"
android:layout_width="402dp"
android:layout_height="211dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/homeScr_text_title" />
<com.google.android.material.button.MaterialButton
android:id="#+id/userDetails_next_btn"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginTop="3dp"
android:fontFamily="sans-serif-black"
android:text="NEXT"
android:textSize="20sp"
app:cornerRadius="35dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_ti" />
<com.google.android.material.button.MaterialButton
android:id="#+id/userDetails_btn_back"
style="#style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="88dp"
android:layout_height="50dp"
android:layout_marginTop="3dp"
android:backgroundTint="#color/black"
android:fontFamily="sans-serif"
android:text="BACK"
android:textSize="20sp"
app:cornerRadius="35dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_ti"
app:strokeColor="#color/primeOrng"
app:strokeWidth="1dp" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/details_ti"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif-light"
android:hint="map.."
android:textColorHint="#color/white"
app:layout_constraintTop_toBottomOf="#+id/details_list_rv"
tools:layout_editor_absoluteX="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/listrow_question_et"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_input"
android:drawablePadding="14dp"
android:fontFamily="sans-serif-light"
android:inputType="text"
android:maxLines="1"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/details_ti"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:layout_editor_absoluteX="0dp" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
How can I solve this?
EDIT:
By replacing :
list.getChildCount();
with:
list.getAdapter().getItemCount()
I get the exact size (6) and now I understand it is related to the fact RecycleView recycles the views and not keeping them all, so it will always be a maximum of 3 items(in my example).
now, my question is still how could I achieve my target of saving the selected answers in the spinners by clicking finishBtn(I understand that iterating them is not an option because of the same thing, or maybe there is a way?)

listview item is not displaying the assigned value in getview method of custom adapter

I ran into a problem and still don't know how to get out. I made a listview with a custom adapter for it. I also implemented a searchview which will update the listview everytime I type in a character. But the problem is that the listview is not showing the correct results. I put some checkpoints in getView method of the custom adapter to check if the values which will be displayed are right or not and they're all right.
I have two items, let's call them HD03 and HD02 as you can see their name on the top left corner of each item.
when I type in the search bar 02, the result must be item HD02 but I got item HD03 instead. Although, the value I checked in the getView method using debugger was HD02
I think I made a silly mistake somewhere but I can't find it. Thank you for your time !
Here're my fragment and my adapter code.
Fragment
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
private ListView listViewContract;
private SearchView contractSearchView;
private ContractAdapter productListAdapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
initView(root);
return root;
}
private void initView(View view) {
listViewContract = view.findViewById(R.id.contract_list);
listViewContract.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listViewProduct_onItemClick(adapterView, view, i, l);
}
});
loadData();
contractSearchView = view.findViewById(R.id.search_bar);
contractSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
DashboardFragment.this.productListAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
DashboardFragment.this.productListAdapter.getFilter().filter(newText);
return false;
}
});
}
private void loadData() {
List<Contract> products = new ArrayList<Contract>();
products.add(new Contract("p03", "Name 1", "4", "Mới", "HD03" ));
products.add(new Contract("p02", "Name 2", "5", "Mới", "HD02"));
productListAdapter = new ContractAdapter(getContext(), products);
listViewContract.setAdapter(productListAdapter);
}
private void listViewProduct_onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Product product = (Product) adapterView.getItemAtPosition(i);
// Toast.makeText(getApplicationContext(), product.getName(), Toast.LENGTH_LONG).show();
}
}
Adapter
public class ContractAdapter extends BaseAdapter implements Filterable {
private Context context;
private List<Contract> products;
private List<Contract> filteredData;
private ItemFilter itemFilter = new ItemFilter();
public ContractAdapter(Context context, List<Contract> products){
this.context = context;
this.products = products;
this.filteredData = products;
}
#NonNull
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder viewHolder;
if (view == null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.phan_anh_cardview, parent, false);
viewHolder.textViewContractName = view.findViewById(R.id.ten_hd);
viewHolder.textViewCustomerName = view.findViewById(R.id.ten_dt);
viewHolder.textViewEmployeeName = view.findViewById(R.id.ten_nv);
viewHolder.textViewId = view.findViewById(R.id.ma_hd);
viewHolder.buttonStatus = view.findViewById(R.id.report_status);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
Contract product = filteredData.get(position);
viewHolder.textViewContractName.setText(product.getName());
viewHolder.textViewEmployeeName.setText(product.getNhanvien());
viewHolder.textViewCustomerName.setText(product.getCustomer());
viewHolder.textViewId.setText(product.get_id());
viewHolder.buttonStatus.setText(product.getStatus());
Log.i("view", viewHolder.textViewId.getText().toString());
return view;
}
public int getCount(){
return filteredData.size();
}
public Contract getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public Filter getFilter() {
return itemFilter;
// return super.getFilter();
}
private static class ViewHolder {
public static TextView textViewContractName;
public static TextView textViewCustomerName;
public static TextView textViewEmployeeName;
public static TextView textViewId;
public static Button buttonStatus;
}
private class ItemFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String query = constraint.toString();
FilterResults results = new FilterResults();
List<Contract> originalData = products;
int count = originalData.size();
List<Contract> nList = new ArrayList<>();
for (Contract contract : originalData) {
if(contract.get_id().contains(query) || contract.getName().contains(query) || contract.getCustomer().contains(query)){
nList.add(contract);
}
}
results.values = nList;
results.count = nList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (List<Contract>) results.values;
notifyDataSetChanged();
}
}
}
fragment_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".ui.dashboard.DashboardFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/tag_spinner_constraint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<SearchView
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="45dp"
android:iconifiedByDefault="false"
app:layout_constraintEnd_toEndOf="#id/tag_spinner_constraint"
app:layout_constraintStart_toStartOf="#id/tag_spinner_constraint"
app:layout_constraintTop_toTopOf="#id/tag_spinner_constraint" />
<HorizontalScrollView
android:id="#+id/filter_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/search_bar">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/empty_rooms_btn"
android:layout_width="99dp"
android:layout_height="34dp"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Phòng trống"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/floor_spinner" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/not_full_rooms_btn"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Phòng ghép"
android:textSize="12sp"
app:layout_constraintStart_toEndOf="#+id/empty_rooms_btn"
app:layout_constraintTop_toBottomOf="#+id/floor_spinner" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/full_rooms_btn"
android:layout_width="105dp"
android:layout_height="34dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Phòng đã đầy"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/not_full_rooms_btn"
app:layout_constraintTop_toBottomOf="#+id/floor_spinner" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/all_rooms_btn"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Tất cả"
android:textSize="12sp" />
</LinearLayout>
</HorizontalScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
<ListView
android:id="#+id/contract_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tag_spinner_constraint">
</ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
phan_anh_cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="162dp"
android:layout_marginTop="5dp"
android:padding="6dp">
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/report_status"
android:layout_width="68dp"
android:layout_height="15dp"
android:background="#drawable/rounded_button"
android:text="Mới"
android:textSize="10sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ma_hd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ten_hd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ma_hd" />
<TextView
android:id="#+id/ten_dt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ten_hd" />
<TextView
android:id="#+id/ten_nv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ten_dt" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
rounded_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#color/cardview_dark_background" />
<corners android:bottomRightRadius="30dp"
android:bottomLeftRadius="30dp"
android:topRightRadius="30dp"
android:topLeftRadius="30dp"/>
</shape>
I found error in your code.
You shouldn't use static members in ViewHolder.
So please replace ViewHolder code as following.
ContractAdapter.java
..............
private static class ViewHolder {
public TextView textViewContractName;
public TextView textViewCustomerName;
public TextView textViewEmployeeName;
public TextView textViewId;
public Button buttonStatus;
}
...............
If so, it will be working.

ListView doesn't show ImageButton with BaseAdapter

I want to display a name from my database with a delete button on the right. I have created a custom adapter with BaseAdapter. The ListView show me the right name but no ImageButton. Hope ypu can help me.
Here my Code:
Layout for each ListItem:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<TextView
android:id="#+id/PlayerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/PlayerDeleteImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="#android:color/white"
android:padding="20dp"
app:srcCompat="#drawable/ic_baseline_delete_24"
android:tint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout for my PlayerActivity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".Baum.PlayerActivity">
<EditText
android:id="#+id/PayerEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:hint="#string/AddPlayerHint"
app:layout_constraintEnd_toStartOf="#+id/PlayerFloatingActionButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/PlayerListView"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/PayerEditText" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:itemBackground="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu_navigation" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/PlayerFloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:clickable="true"
android:onClick="onClickFloatingActionButton"
android:tint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24"
tools:ignore="VectorDrawableCompat" />
</androidx.constraintlayout.widget.ConstraintLayout>
My Activity:
public class PlayerActivity extends Activity {
private ArrayList<String> players = new ArrayList<>();
DBHelper db = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//Initalize custom Players
loadPlayersInArrayList();
// Show all Players in the ListView
ListView listView = (ListView) findViewById(R.id.PlayerListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, players);
listView.setAdapter(arrayAdapter);
//All BottomNav stuff
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.player_menu);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.player_menu:
return true;
case R.id.home_menu:
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.deck_menu:
startActivity(new Intent(getApplicationContext(), DecksActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
}
public void onClickFloatingActionButton(View v){
EditText newPlayerName = findViewById(R.id.PayerEditText);
ArrayList<Player> dbPlayers = db.getAllPlayer();
boolean newPlayer = true;
for(Player p : dbPlayers){
if(newPlayerName.getText().toString().equals(p.getName())){
newPlayer = false;
new AlertDialog.Builder(this)
.setTitle("Information")
.setMessage("Dieser Name ist bereits vergeben")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
break;
}
}
if (newPlayer){
db.addPlayer(newPlayerName.getText().toString());
loadPlayersInArrayList();
}
}
public void loadPlayersInArrayList(){
if (players != null){
players.clear();
}
ArrayList<Player> dbPlayers = db.getAllPlayer();
for(Player p : dbPlayers){
players.add(p.getName());
}
}
}
Here is my Adapter:
public class PlayerAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> items;
public PlayerAdapter(Context context, ArrayList<String> items){
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.player_list_item, parent, false);
}
String currentItem = (String) getItem(position);
TextView deckName = (TextView) convertView.findViewById(R.id.PlayerTextView);
ImageButton playerDeleteButton = (ImageButton) convertView.findViewById(R.id.PlayerDeleteImageButton);
deckName.setText(currentItem);
return convertView;
}
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
Here a screenshot of my ListView in the app:
ListView in the app
Here a screenshot from the Layout for each Item:
Screenshot Layout
I guess android.R.layout.simple_list_item_1 expect only a simple text view in the layout file. (I might be wrong as well).
Still using Base Adapter and android.R.layout.simple_list_item_1 are expected to be in a simple spinner item. For any custom layout for list item use ArrayAdapter<type>. Code as follows-
PlayerAdapter.java
public class PlayerAdapter extends ArrayAdapter<String> {
List<String> playerNameList;
public PlayerAdapter(#NonNull Context context, #NonNull List<String> playerNameList) {
//#param context, layout of list item, textview id of list item and List<String>
super(context, R.layout.player_list_item, R.id.PlayerTextView,playerNameList);
this.playerNameList = playerNameList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView playerTextView = view.findViewById(R.id.PlayerTextView);
ImageView playerDeleteImageButton = view.findViewById(R.id.PlayerDeleteImageButton);
playerTextView.setText(playerNameList.get(position));
playerDeleteImageButton.setOnClickListener(v -> {
// apply on image click code here
});
return view;
}
}
I modified to list item as well to be a simple LinearLayout -
ListItem Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dp"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/PlayerTextView"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="20sp"
android:textStyle="bold"/>
<ImageView
android:id="#+id/PlayerDeleteImageButton"
android:src="#mipmap/ic_launcher_round"
android:layout_width="30dp"
android:layout_height="30dp"/>
</LinearLayout>
Setting PlayerAdpater
List<String> playerNameList = new ArrayList<>();
PlayerAdapter playerAdapter = new PlayerAdapter(this,playerNameList);
playerNameList.setAdapter(playerAdapter);
Hope this will help.
Happy Coding !

Unable to display fetch data from MYSQL database in custom gridview in android

In my app I use grid view to display data. grid view is in a fragment.I already retrieve data from mysql database in Log cat but that json data not display in custom grid.
activity_product_list.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DrawerActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/header2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PRODUCTS : -"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"/>
<GridView
android:id="#+id/productlist"
android:layout_below="#+id/header2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="2dp"
android:layout_marginTop="#dimen/activity_horizontal_margin">
</GridView>
</RelativeLayout>
ProductListFragment.java
public class ProductListFragment extends Fragment {
List<Product> productList;
GridView gridView;
CustomProductList customProductList;
int categoryid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_product_list, container,false);
gridView = (GridView) rootView.findViewById(R.id.productlist);
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
categoryid = ID.getCategoryid();
productList = new ArrayList<>();
loadProduct();
customProductList = new CustomProductList(getActivity(),productList);
gridView.setAdapter(customProductList);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void loadProduct() {
String PRODUCT_URL = "http://192.168.0.101/cart/product/get_all_product.php?vcategoryid="+categoryid;
StringRequest stringRequest= new StringRequest(Request.Method.GET, PRODUCT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("products");
for (int i = 0; i < array.length(); i++){
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
Product product = new Product();
product.setProductid(userJson.getInt("productid"));
product.setProductName(userJson.getString("productname"));
product.setProductDesc(userJson.getString("productdesc"));
product.setPrice(userJson.getString("productprice"));
productList.add(product);
Log.e("product",userJson+"");
}
customProductList.notifyDataSetChanged();
Log.e("product",customProductList+"");
//customCategoryList = new CustomCategoryList(getActivity(),categoryList);
//recyclerView.setAdapter(customCategoryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
custom_product_list.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/home_appliances"/>
<TextView
android:id="#+id/productName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Redmi"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="22sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RS."
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9999"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"
android:layout_marginLeft="10dp"/>
</LinearLayout>
CustomProductList.java
public class CustomProductList extends BaseAdapter {
private Context mCtx;
private List<Product> productList;
public CustomProductList(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mCtx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(mCtx);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.custom_product_list, null);
TextView productname = (TextView) gridView.findViewById(R.id.productName);
TextView price = (TextView) gridView.findViewById(R.id.price);
// getting data for the row
Product product = productList.get(position);
// set data
productname.setText(product.getProductName());
price.setText(product.getPrice());
} else {
gridView = (View) convertView;
}
return gridView;
}
}
This is my code.All data comes from database in logcat as json..But All not display in grid.Please help me.Tell me What is the problem.
Solution:
You forgot to get count the updated list, hence chenge the below code:
#Override
public int getCount() {
return 0;
}
to this:
#Override
public int getCount() {
return this.productList.size();
}
That's it. Hope it helps.

Android Custom ArrayAdapter Listview is not clickable with Async Task

I have been stuck on this problem for almost a day now and have tried numerous previous posts on Stack Overflow, online tutorials etc. but nothing seems to work in my case. I have tried setting focusable, focusable in touch and clickable to false for all textviews in each row list item, set android:descendantFocusability="blocksDescendants" in the Relative Layout for list_item_main.xml but nothing has worked. Any help will really be appreciated! Thanks The setup is as follows:
tab.xml (Layout for listview):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:clickable="true"
android:id="#+id/android:list"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</LinearLayout>
list_item_main.xml (Each row item):
<?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="wrap_content"
android:id="#+id/rLayout">
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="XYZ"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#808080"
android:layout_above="#+id/weight"
android:layout_alignLeft="#+id/Qty"
android:layout_alignStart="#+id/Qty"/>
<TextView
android:id="#+id/Qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="4"
android:text="150"
android:textSize="18sp"
android:textColor="#808080"
android:layout_marginLeft="39dp"
android:layout_marginStart="39dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="87dp"/>
<TextView
android:id="#+id/dateTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="4"
android:text="Available from: "
android:textSize="18sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Date"
android:layout_alignLeft="#+id/Qty"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" 0.000"
android:textStyle="bold"
android:textSize="24sp"
android:id="#+id/Rate"
android:textColor="#808080"
android:layout_alignTop="#+id/Name"
android:layout_toRightOf="#+id/Date"
android:layout_toEndOf="#+id/Date"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="14/08/2007"
android:textSize="18sp"
android:id="#+id/Date"
android:textColor="#808080"
android:layout_below="#+id/weight"
android:layout_toRightOf="#+id/dateTitle"
android:layout_toEndOf="#+id/dateTitle"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=" Kgs"
android:id="#+id/weight"
android:textSize="18sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Qty"
android:layout_alignRight="#+id/Name"
android:layout_alignEnd="#+id/Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="INR"
android:id="#+id/currency"
android:textStyle="bold"
android:textSize="24sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Rate"
android:layout_toRightOf="#+id/Rate"
android:layout_toEndOf="#+id/Rate"/>
DealAdapter:
public class DealAdapter extends ArrayAdapter<Offer2SaleTransaction> {
private List<Offer2SaleTransaction> activeDeals;
private Context context;
private static final Logger logger = Logger.getLogger(DealAdapter.class.getName());
public DealAdapter(List<Offer2SaleTransaction> activeDeals, Context ctx) {
super(ctx, R.layout.list_item_main, activeDeals);
this.activeDeals = activeDeals;
this.context = ctx;
}
public int getCount() {
if (activeDeals != null)
return activeDeals.size();
return 0;
}
public Offer2SaleTransaction getItem(int position) {
if (activeDeals != null)
return activeDeals.get(position);
return null;
}
public long getItemId(int position) {
if (activeDeals != null)
return activeDeals.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item_main, null);
}
Offer2SaleTransaction deal = activeDeals.get(position);
TextView textName = (TextView) v.findViewById(R.id.Name);
textName.setText(deal.getName());
TextView textQty = (TextView) v.findViewById(R.id.Qty);
textQty.setText(Float.toString(deal.getQty()));
// Hardcoded date as of now
TextView textDate = (TextView) v.findViewById(R.id.Date);
textDate.setText("01-01-1994");
logger.info("This is something I want to know " + deal.getSaleDate());
TextView textPrice = (TextView) v.findViewById(R.id.Rate);
textPrice.setText(Float.toString(deal.getRate()));
return v;
}
public List<Offer2SaleTransaction> getActiveDeals() {
return activeDeals;
}
public void setActiveDeals(List<Offer2SaleTransaction> activeDeals) {
this.activeDeals = activeDeals;
}}
Finally, the fragment to display the listview:
public class StatusFragment extends ListFragment implements OnItemClickListener{
DealAdapter adpt;
ListView lView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tab, container, false);
adpt = new DealAdapter(new ArrayList<Offer2SaleTransaction>(), getActivity());
lView = (ListView) view.findViewById(android.R.id.list);
lView.setAdapter(adpt);
lView.setOnItemClickListener(this);
// Exec async load task
new EndpointsStatusAsyncTask().execute(new Pair<Context, String>(getActivity(), "XXXXXX"));
return view;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getActivity(), "PLEASE WORK",Toast.LENGTH_LONG).show();
}
private class EndpointsStatusAsyncTask extends AsyncTask<Pair<Context, String>, Void, List<Offer2SaleTransaction>> {
private Offer2SaleTransactionApi myApiService = null;
private final Logger logger = Logger.getLogger(EndpointsStatusAsyncTask.class.getName());
private Context context;
private String TAG = "Background";
#Override
protected List<Offer2SaleTransaction> doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
Offer2SaleTransactionApi.Builder builder = new Offer2SaleTransactionApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("https:xxxx");
myApiService = builder.build();
}
context = params[0].first;
String userID = params[0].second;
try {
return myApiService.getOffer2SaleTransaction(userID).execute().getItems();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(List<Offer2SaleTransaction> result) {
if (result == null)
{
Toast.makeText(context, "It didn't work", Toast.LENGTH_LONG).show();
logger.info("Failure in connecting to execute onPostExecute");
}
else
{
super.onPostExecute(result);
adpt.setActiveDeals(result);
adpt.notifyDataSetChanged();
}
}
}}
since you are extending ListFragment, you have to override onListItemClick, and use it in place of onItemClick.
Remove implements OnItemClickListener
Remove lView.setOnItemClickListener(this);
Delete onItemClick
Then
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "PLEASE WORK",Toast.LENGTH_LONG).show();k(l, v, position, id);
}

Categories

Resources