ListView is updating weirdly - android

The following is my layout for a custom row in a listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/layoutTop"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Well Hello Motherfucker"
android:id="#+id/geventProfileName"
android:textSize="20sp"
android:paddingLeft="50dp"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/layoutBottom"
android:layout_width="match_parent"
android:layout_height="300dp"
android:alpha="1"
android:layout_below="#+id/layoutTop"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/no_picture"
android:id="#+id/geventEventPhoto"
android:layout_gravity="top|left"
android:alpha="1"/>
<TextView
android:layout_width="350dp"
android:layout_height="wrap_content"
android:text="asfda"
android:layout_gravity="center|left"
android:textSize="35sp"
android:textColor="#FFF"
android:textAllCaps="true"
android:id="#+id/geventTitle"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read More"
android:textColor="#color/black"
android:id="#+id/geventReadMoreButton"
android:background="#drawable/readtab"
android:paddingTop="10dp"
android:paddingLeft="20dp"
android:layout_gravity="bottom|right"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:id="#+id/geventDescription"
android:text=""
android:textColor="#color/black"
android:layout_gravity="top|left"/>
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/geventDetails"
android:text=""
android:textSize="20sp"
android:textColor="#FFF"
android:layout_gravity="bottom|left"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/layoutBottom"
android:orientation="horizontal"
android:background="#9E9E9E"
android:padding="5dp"
android:layout_marginTop="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100"
android:id="#+id/numberOfLikesGEvent"
android:textColor="#color/black"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/numberOfLikesGEvent"
android:id="#+id/likeTextViewGEvent"
android:layout_marginLeft="10dp"
android:textColor="#color/black"
android:text="Like"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/dislikeTextViewGEvent"
android:layout_marginRight="10dp"
android:id="#+id/numberOfDislikesGEvent"
android:textColor="#color/black"
android:text="200"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dislikeTextViewGEvent"
android:text="Dislike"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="0dp"
android:textColor="#color/black"/>
</RelativeLayout>
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/photo"
app:civ_border_width="2dp"
app:civ_border_color="#FFF"/>
And this is my CustomAdapter
public class CustomAdapter extends ArrayAdapter<GEvent> {
boolean hasLiked;
boolean hasDisliked;
FirebaseUser fbUser;
ArrayList<String> uids;
ArrayList<String> dUids;
GEvent currentEvent;
private TextView likeTextView;
private TextView numberOfLikes;
private TextView dislikeTextView;
private TextView numberOfDislikes;
private TextView readMoreButton;
private TextView eventDetails;
private TextView titleGevent;
private ImageView eventPhoto;
private TextView profileName;
private TextView descriptionGevent;
private String description;
private String titleForGEvent;
private String detailsGEvent;
private boolean hasLoaded=true;
private de.hdodenhof.circleimageview.CircleImageView circleImageView;
private Context mContext;
private boolean wantsToReadMore=false;
String profilePhotoLink;
PopupWindow pw;
public CustomAdapter(Context context, GEvent[] resource) {
super(context, R.layout.custom_row , resource);
this.mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final View customView = inflater.inflate(R.layout.example,parent,false);
final GEvent gEvent = getItem(position);
currentEvent = gEvent;
firebaseAuth = FirebaseAuth.getInstance();
uid = firebaseAuth.getCurrentUser().getUid();
titleGevent = (TextView) customView.findViewById(R.id.geventTitle);
descriptionGevent = (TextView) customView.findViewById(R.id.geventDescription);
profileName = (TextView) customView.findViewById(R.id.geventProfileName);
likeTextView = (TextView) customView.findViewById(R.id.likeTextViewGEvent);
numberOfLikes = (TextView) customView.findViewById(R.id.numberOfLikesGEvent);
numberOfDislikes =(TextView) customView.findViewById(R.id.numberOfDislikesGEvent);
dislikeTextView = (TextView) customView.findViewById(R.id.dislikeTextViewGEvent);
readMoreButton = (TextView) customView.findViewById(R.id.geventReadMoreButton);
eventPhoto = (ImageView) customView.findViewById(R.id.geventEventPhoto);
eventDetails = (TextView)customView.findViewById(R.id.geventDetails);
circleImageView = (CircleImageView) customView.findViewById(R.id.profile_image);
description = gEvent.getDescription();
detailsGEvent = gEvent.getgEventDate()+"\n"+gEvent.getgEventTime()+"\n"+gEvent.getVenue1()+"\n"+gEvent.getVenue2()+"\n"+gEvent.getContactEmail()+"\n"+gEvent.getContactPhoneNumber();
titleForGEvent = gEvent.getTitle();
if(gEvent.isHasPhoto()){
hasLoaded= false;
readMoreButton.setText("Loading");
}
readMoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasLoaded) {
Log.i("CA","Entered hasLoaded Function");
readMoreFunction();
}
else
Toast.makeText(mContext,"Loading....",Toast.LENGTH_LONG).show();
}
});
titleGevent.setText(gEvent.getTitle());
String uuid = gEvent.getUuid();
Boolean hasPhoto = gEvent.isHasPhoto();
profileName.setText(gEvent.getProfileUsername());
if(hasPhoto) {
final long ONE_MEGABYTE = 1024 * 1024 * 5;
pathRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
Bitmap picturel = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView imageView = (ImageView) customView.findViewById(R.id.geventEventPhoto);
Drawable d = new BitmapDrawable(mContext.getResources(),picturel);
imageView.setBackground(d);
Log.i("CA","Entered hasRetrieved Photo and update hasLoaded");
readMoreButton.setText("Read More");
hasLoaded=true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.i("Error","Couldn't Download");
}
});
}
return customView;
}
public void readMoreFunction(){
Log.i("CA","Entered readMoreFunction Function");
if(wantsToReadMore){ //wants to read less now
Log.i("CA","Entered Read Less Function");
eventPhoto.setAlpha(1f);
descriptionGevent.setText("");
eventDetails.setText("");
readMoreButton.setText("Read More");
titleGevent.setText(titleForGEvent);
wantsToReadMore=false;
}
else{ //Wants to read more
Log.i("CA","Entered Read More Function");
eventPhoto.setAlpha(0.5f);
descriptionGevent.setText(description);
eventDetails.setText(detailsGEvent);
titleGevent.setText("");
readMoreButton.setText("Read Less");
wantsToReadMore=true;
}
So my problem is that whenever I am calling this CustomAdapter, when only one list Item is there it works perfectly, however whenever there are multiple list items, the adapter starts behaving strangely. For instance, whenever there are 2 items, If i press the " Read More " button for the first item, it triggers for the second item, even though in the logs it shows that data on which it is working is the first item itself.
If there are more than 2 items , then the above pattern is observed , i.e, whenever I click the "Read More" button of a given item, it triggers for the next item in the listview. Sometimes it is just stuck on "Loading " even after the image has loaded or the "Read More" button doesn't even respond.
I have been banging my head for the past two days , looking for the bug. Hope you guys can help me.Thanks in Advance.
PS:- The "Load More" Button is out of place, excuse me for that.

Inside GEvent class create a boolean field,
class GEvent {
private boolean readMoreClicked;
public boolean isReadMoreClicked(){
return readMoreClicked;
}
public void setReadMoreClicked(boolean readMoreClicked){
this.readMoreClicked = readMoreClicked;
}
}
Inside getView,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
....
if(gEvent.isReadMoreClicked()) {
Log.i("CA","Entered More Less Function");
...
} else {
Log.i("CA","Entered Less More Function");
...
}
readMoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasLoaded) {
Log.i("CA","Entered hasLoaded Function");
// user has clicked Read More. Save the state
gEvent.setReadMoreClicked(!gEvent.isReadMoreClicked());
notifyDataSetChanged();
} else {
Toast.makeText(mContext,"Loading....",Toast.LENGTH_LONG).show();
}
}
});
...
}
It may need some editing. But I hope you get the idea. :)

Related

List view inside Fragment is not getting populated

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

Dynamically inserting list items to listview in android

Friends i'm new to android and learning on my own. I was creating invoice manager app for learning. Here products are added by the admin and that is working fine. User has only permission to create invoice. When user arrives into create_invoice activity he has set of frame layouts in which one is for adding items. When user presses the frame layout he is made to see another activity where he can find all set of list items along with the product price in List view which admin has added. Now when user presses an item he is again brought back to create_invoice activity and a alert box appears which asks the qty required. When user enters the qty and clicks OK button, for the first the list item is displayed properly as i require. But when i add second item, 1st item gets replaced. So now my problem is how can i resolve this problem.. Guys please help me. Codes you people find may be very silly but i'm still learning. Thanks in advance.
Create_invoice activity
//data from activity invoice add_item
product_name = intent.getStringExtra("product_name");
product_price = intent.getDoubleExtra("product_price",0);
//product_qty = intent.getIntExtra("product_qty",0);
product_code = intent.getIntExtra("product_code",0);
if(product_name!= null && product_price!= 0 && product_code!= 0)
{
try {
builder = new AlertDialog.Builder(this);
builder.setTitle("Product Qty");
layoutInflater = LayoutInflater.from(Create_invoice.this);
view = layoutInflater.inflate(R.layout.dialoglayout_invoice,null);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
EditText etxt_dialog_qty=(EditText)view.findViewById(R.id.
etxt_dialog_qty);
int qty = Integer. parseInt (etxt_dialog_qty.getText().
toString().trim());
invoice_product_list products = new invoice_product_list
(product_name, product_price, qty, product_code);
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.add(products);
customAdapterInvoice.notifyDataSetChanged();
//listview in create_invoice activity
listView_additem = (ListView)
findViewById(R.id.listview_additem);
listView_additem.setAdapter(customAdapterInvoice);
alertDialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
catch (Exception e)
{
System.out.print(e);
}
}
customAdapter
public class custom_adapter_invoice extends ArrayAdapter
<invoice_product_list> {
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view =
layoutInflater.inflate(R.layout.custom_row_invoice_item,parent,false);
invoice_product_list products = getItem(position);
TextView txt_product_name =
(TextView)view.findViewById(R.id.txt_product_name);
TextView txt_product_price =
(TextView)view.findViewById(R.id.txt_product_price);
TextView txt_product_qty =
(TextView)view.findViewById(R.id.txt_product_qty);
TextView txt_product_code =
(TextView)view.findViewById(R.id.txt_product_code);
txt_product_name.setText(products.getProduct_name());
txt_product_price.setText(String.valueOf(products.getProduct_price()));
txt_product_qty.setText(String.valueOf(products.getProduct_qty()));
txt_product_code.setText(String.valueOf(products.getProduct_code()));
return view;
}
create invoice activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tournonstop.m.invoicemanager.Create_invoice"
tools:showIn="#layout/activity_create_invoice">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/darker_gray">
<include layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_company">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/company_name"
android:id="#+id/txt_company_name"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_date"
android:id="#+id/txt_invoice_date"
android:layout_gravity="right"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_no"
android:id="#+id/textView3"
android:layout_marginLeft="15dp"
android:layout_marginTop="45dp"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_client"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/to"
android:id="#+id/txt_to"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_client_address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:hint="#string/client_hint"/>
</FrameLayout>
----listview to add items-----
<FrameLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_add_item"
android:clickable="true">
<ListView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/listview_additem"
android:divider="#040404" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_sub_total">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total_label"
android:id="#+id/txt_sub_total_label"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total"
android:id="#+id/txt_sub_total"
android:layout_gravity="right"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textStyle="bold"
android:hint="#string/total_hint" />
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/invoice_btn"
android:textStyle="bold"
android:background="#color/colorPrimaryDark"
android:textColor="#android:color/white"
android:clickable="true"
android:id="#+id/btn_invoice_save" />
</LinearLayout>
< /android.support.v4.widget.DrawerLayout>
invoice product list(getters and setters)
package com.tournonstop.m.invoicemanager;
public class invoice_product_list {
private String product_name;
private double product_price;
private int product_qty;
private int product_code;
public invoice_product_list(){
}
public invoice_product_list(String product_name,double
product_price,int product_qty,int product_code){
this.product_name = product_name;
this.product_price = product_price;
this.product_qty = product_qty;
this.product_code = product_code;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public double getProduct_price() {
return product_price;
}
public void setProduct_price(double product_price) {
this.product_price = product_price;
}
public int getProduct_qty() {
return product_qty;
}
public void setProduct_qty(int product_qty) {
this.product_qty = product_qty;
}
}
Add item to your list that you're using in adapter and (after verifying adapter is not null ) call method notifyDataSetChanged () on adapter object.
create_invoice activity
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.addProduct(products)
custom Adapter
public class custom_adapter_invoice extends ArrayAdapter <invoice_product_list>
{
ArrayList<invoice_product_list> productList = new ArrayList<>();
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
this.productList =product_details
}
public void addProduct(Product products
productList.add(products);
notifyDataSetChanged();
}
......
}
No,it does not change anything. If you want the latest method of working then I would prefer RecyclerView to custom list adapter. this link is very good for recyclerview
recyclerview demo series link

how to hide view appear on top of previous selected row on click of another row inside GridView in android

I have a Fragment with custom Adapter extending BaseAdapter that manages a GridView.
I want to show images on each row of the GridView and onClick of each cell, I want to open a translucent view on top of that particular image which will show image details.
Problem is that when I click on the image, a translucent view opened on top of the image but when I click on next image then a translucent view opened on previous images is not hiding,it still appears over the first images..
See the following code
My Fragment
public class ProductFragment extends Fragment {
String ss = null;
GridView gridView;
ArrayList<ProductParameterBO> productlist;
GridViewCustomAdapter gridViewCustomAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState!=null){
View rootView = inflater.inflate(R.layout.empty_catalog_item,null);
TextView configure = (TextView)rootView.findViewById(R.id.text_conf);
configure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),SplitViewActivity.class);
intent.putExtra("firstTab","1stTabs");
startActivity(intent);
}
});
TextView text_here = (TextView)rootView.findViewById(R.id.text_here);
text_here.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), EditUploadActivity.class);
startActivity(intent);
}
});
return rootView;
} else {
View rootView = inflater.inflate(R.layout.fragment_product,null);
gridView =(GridView)rootView.findViewById(R.id.gridView);
productlist = new ArrayList<ProductParameterBO>();
productlist.add(new ProductParameterBO("Type","Numeric","yes","yes"));
productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
gridViewCustomAdapter = new GridViewCustomAdapter(getActivity(),productlist);
gridView.setAdapter(gridViewCustomAdapter);
gridViewCustomAdapter.notifyDataSetChanged();
return rootView;
}
// return inflater.inflate(R.layout.fragment_product,null);
}
}
My Adater
public class GridViewCustomAdapter extends BaseAdapter {
private List<ProductParameterBO> availList;
private LayoutInflater inflater;
Context context;
public GridViewCustomAdapter(Context ctx,List<ProductParameterBO> list){
this.context = ctx;
this.availList = list;
}
#Override
public int getCount() {
return availList.size();
}
#Override
public Object getItem(int position) {
return availList.get(position);
}
#Override
public long getItemId(int position) {
ProductParameterBO c = availList.get(position);
// long id = c.getTimeId();
return 0;
}
#Override
public View getView(int position,View convertView,final ViewGroup parent) {
View row = convertView;
final TeeTimeHolder holder;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_row,parent,false);
holder = new TeeTimeHolder();
holder.myImage =(ImageView)row.findViewById(R.id.imageView10);
holder.name =(TextView)row.findViewById(R.id.textView47);
holder.edit =(TextView)row.findViewById(R.id.textView49);
holder.rl =(RelativeLayout)row.findViewById(R.id.img_ovrly);
row.setTag(holder);
} else {
holder =(TeeTimeHolder)row.getTag();
}
holder.name.setText(availList.get(position).getParameterName());
holder.myImage.setImageResource(R.drawable.toi);
holder.rl.setVisibility(View.GONE);
holder.myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rows = null;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rows = inflater.inflate(R.layout.image_overlay,parent,false);
// holder.rl = (RelativeLayout)rows.findViewById(R.id.img_ovrly);
holder.rl.setVisibility(View.VISIBLE);
}
});
return row;
}
static class TeeTimeHolder {
ImageView myImage;
TextView name,edit;
RelativeLayout rl;
//TextView descriptions;
/* TextView coursefee;
TextView viewdetils;*/
}
}
My XML layout grid_row.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="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView10"
android:src="#drawable/toi"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image Name"
android:id="#+id/textView47"
android:layout_below="#+id/imageView10"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:id="#+id/textView49"
android:layout_below="#+id/textView47"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/img_ovrly"
android:background="#color/opacity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/mail"
android:layout_marginTop="10dp"
android:id="#+id/image_i"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title :"
android:id="#+id/text_ttle"
android:layout_below="#+id/image_i"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_ttle"
android:text="hmmmm"
android:layout_below="#+id/image_i"
android:layout_marginTop="20dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dimensions :"
android:id="#+id/text_dimen"
android:layout_below="#+id/text_ttle"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_dimen"
android:text="32*23"
android:layout_below="#+id/text_ttle"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price :"
android:id="#+id/text_prce"
android:layout_below="#+id/text_dimen"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_prce"
android:text="32*23"
android:layout_below="#+id/text_dimen"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color :"
android:id="#+id/text_clr"
android:layout_below="#+id/text_prce"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_clr"
android:text="red,white"
android:layout_below="#+id/text_prce"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Min. Quantity :"
android:id="#+id/text_minq"
android:layout_below="#+id/text_clr"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_minq"
android:text="1000"
android:layout_below="#+id/text_clr"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type :"
android:id="#+id/text_typ"
android:layout_below="#+id/text_minq"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_typ"
android:text="creamic"
android:layout_below="#+id/text_minq"
android:layout_marginTop="10dp"
android:textColor="#6ec6c5"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/img_flp"
android:background="#drawable/flip"
android:layout_below="#+id/text_typ"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</RelativeLayout>
Am I missing something? kindly help me to resolve this issue. I want a screen something like that. Am I doing right to open tranlucent screen on top of image and how to hide or make visivility gone on click of other images inside my Adater class.Any help would be appreciated in advanced
You can do one of two things.
1. Use a flag
NOTE this code is untested.
You can create an encapsulated flag in your ProductParameterBO object to determine the visibility of your overlay view. Something like the following
boolean mInformationViewVisible = false;
public void setInformationViewVisible(boolean visible) {
mInformationViewVisible = visible;
}
public boolean isInformationViewVisible() {
return mInformationViewVisible;
}
Then use that in your getView method to set the visibility of the view.
#Override
public View getView(int position,View convertView,final ViewGroup parent) {
...
holder.myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int itemPosition = 0; itemPosition < availList.size(); itemPosition++) {
if(itemPosition != position){
availList.get(itemPosition)
.setInformationViewVisible(false);
}
availList.get(itemPosition).setInformationViewVisible(true);
}
});
if (currentItem.isInformationViewVisible()) {
holder.rl.setVisibility(View.VISIBLE);
} else {
holder.rl.setVisibility(View.GONE);
}
...
}
2. Switch to RecyclerView
The second and better option is to switch to RecyclerView. This view is specifically built for individual interaction with items in your Adapter. It gives you more power over the View in terms of animations and removal/adittion of items to the adapter. You can read more on it here and here.
It is very likely that the app in the image you attached is using RecyclerView to manage their content. The code to manage the selected info view will be very similar in RecyclerView to what I posted for the ListView, the only difference would be that you would pass the OnClickListener to the RecyclerView.ViewHolder and set it to the info view in there in stead of in the getView() method. I highly recommend using this approach as it will benefit you in the future of your app.
In ProductParameterBO, you can keep a boolean member variable, and in getView() and if one image is clicked, you can set the boolean variables from that list as false, except the one you clicked. If the variable is true, it will display the image details, and if the variable is false, you can set the visibillty of the translucent view as Invisible of that particular position.
#Override
public View getView(int position,View convertView,final ViewGroup parent) {
View row = convertView;
final TeeTimeHolder holder;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_row,parent,false);
holder = new TeeTimeHolder();
holder.myImage =(ImageView)row.findViewById(R.id.imageView10);
holder.name =(TextView)row.findViewById(R.id.textView47);
holder.edit =(TextView)row.findViewById(R.id.textView49);
holder.rl =(RelativeLayout)row.findViewById(R.id.img_ovrly);
row.setTag(holder);
}
else {
holder =(TeeTimeHolder)row.getTag();
}
holder.name.setText(availList.get(position).getParameterName());
holder.myImage.setImageResource(R.drawable.toi);
holder.rl.setVisibility(View.GONE);
holder.myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rows = null;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rows = inflater.inflate(R.layout.image_overlay,parent,false);
// holder.rl = (RelativeLayout)rows.findViewById(R.id.img_ovrly);
// holder.rl.setVisibility(View.VISIBLE);
for(int i=0;i<availList.size();i++){
if(i!=position){
availList.get(i).flag=false;
}
}
availList.get(position).flag=true;
}
});
if(availList.get(i).flag){
holder.rl.setVisibility(View.VISIBLE);
}else{
holder.rl.setVisibility(View.INVISIBLE);
}
return row;
}

Removing a cardview item inside a recycler view if it is null

I have a recycler view in which I populate a cardview consists of an image and two text fields. It works fine. What i want to know is there some way to remove an image from cardview if it is null (and not showing the blank space for image)and just show the text fields for that specific item in recycler view.
I am parsing a JSON service containing images and text. But some of the images are missing while parsing data and I want to remove that image space while displaying data.
Below is my Cardview.xml i am using inside Recyclerview adapter.
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Relative"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#android:color/black"
android:clickable="true"
android:contextClickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:longClickable="true"
android:textColor="#android:color/white" />
<TextView
android:id="#+id/heading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:background="#android:color/black"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/white"
android:textIsSelectable="true"
android:textSize="30dp"
android:textStyle="bold" />
<View
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_below="#+id/heading"
android:background="#CCC" />
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/view"
android:background="#000000"
android:clickable="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textIsSelectable="true"
/>
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_below="#+id/date"
android:background="#CCC" />
<TextView
android:id="#+id/brief"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/view1"
android:background="#000000"
android:clickable="true"
android:contextClickable="true"
android:elegantTextHeight="true"
android:hyphenationFrequency="full"
android:linksClickable="true"
android:text="Large Text"
android:textAlignment="viewStart"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textColorHighlight="#ffffff"
android:textStyle="italic" />
<View
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_below="#+id/brief"
android:background="#CCC" />
</RelativeLayout>
</android.support.v7.widget.CardView>
The RecyclerViewAdapter class is :
private LayoutInflater inflater;
Context context;
List<Data> dataArray;
private int lastPosition = -1;
public RecyclerViewAdapter(Context context) {
//this.dataArray = dataArray;
this.context = context;
inflater = LayoutInflater.from(context);
}
public void setDataArray(List<Data> dataArray) {
this.dataArray = dataArray;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, null);
View view = inflater.inflate(R.layout.cardview, parent, false);
CustomViewHolder holder = new CustomViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Data current = dataArray.get(position);
holder.textView1.setText(current.heading);
holder.textView2.setText(current.date);
holder.textView3.setText(current.brief);
// Using picasso to fetch image as the user scrolls down ... No need to store
// all the images during start up.
Uri uri = Uri.parse(current.getLImage());
//System.out.println("URIiii issss::::"+uri);
Picasso.with(context).load(uri).into(holder.image);
// Animation
setAnimation(holder.relativeLayout, position);
}
#Override
public int getItemCount() {
return dataArray.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
RelativeLayout relativeLayout;
TextView textView1, textView2, textView3;
public CustomViewHolder(View itemView) {
super(itemView);
textView1 = (TextView) itemView.findViewById(R.id.heading);
textView2 = (TextView) itemView.findViewById(R.id.date);
textView3 = (TextView) itemView.findViewById(R.id.brief);
image = (ImageView) itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View v) {
}
}
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition || position < lastPosition) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
}
What i really want is to remove the imageview item inside carview if it is null. I am relatively new to android, so any guideline would be highly appreciated.
Try with this.
If your Image URI is null.
if(uri == null){
Picasso.with(this.context).cancelRequest(holder.image);
holder.image.setVisibility(View.GONE);
}
Hope this helps you.
check two things for this,
first check your limage is null or not, if it is null than hide your image view.
one another thing is check image is already exists on your server url. if not exists on server hide your image view.
you can try below code for that,
if(current.getLImage() == null || !imageExists(**yourImageUrl**)){
Picasso.with(this.context).cancelRequest(holder.image);
holder.image.setVisibility(View.GONE);
}
public static boolean imageExists(String URLName){
HttpClient client= new DefaultHttpClient();
HttpHead headMethod = new HttpHead(urlToImage);
HttpResponse response = client.execute(headMethod);
if(response.getStatusLine().getStatusCode== HttpStatus.SC_NOT_FOUND) {
return false;
} else {
return true;
}
}

Row layout not inflated in Android

I have a problem. I started a few weeks ago learning Android. I am trying to create an adapter for a list. But the lists doesn't show up AT ALL. Any ideas why? The items are objects type Verb. Here is my code:
///my main activity///
public class Verbs extends Activity {
private ListView listViewVerbs;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verbs);
//instantiate Verb
Verb[] VerbData=new Verb[3];
VerbData[0] = new Verb("machen","mache","machen","mache","machen","mache","machen");
VerbData[1] = new Verb("machen","mache","machen","mache","machen","mache","machen");
VerbData[2] = new Verb("machen","mache","machen","mache","machen","mache","machen");
//pass data to adapter
VerbAdapter adapter = new VerbAdapter(this,R.layout.row_verbs,VerbData);
listViewVerbs = (ListView)findViewById(R.id.list);
listViewVerbs.setAdapter(adapter);
listViewVerbs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String wasClicked = view.findViewById(R.id.nameVerb).toString();
Toast.makeText(Verbs.this,
"You clicked: " + wasClicked, Toast.LENGTH_LONG)
.show();
}
});
}
}
//class for an item of the list
public class Verb {
public String verbname;
public String fpersg;
public String fperspl;
public String sperssg;
public String sperspl;
public String tperssg;
public String tperspl;
//constructor
public Verb(String s, String s1, String s2, String s3, String s4, String s5,String s6){
this.verbname = s;
this.fpersg = s1;
this.fperspl = s2;
this.sperssg = s3;
this.sperspl = s4;
this.tperssg = s5;
this.tperspl = s6;
}
//setters
public void setVbName(String vbName){
this.verbname = vbName;
}
public void setFpersg(String fpersg){
this.fpersg = fpersg;
}
public void setFperpl(String fperpl){
this.fperspl = fperpl;
}
public void setSpersg(String spersg){
this.sperssg = spersg;
}
public void setSperspl(String sperpl){
this.sperspl = sperpl;
}
public void setTpersg(String tpersg){
this.tperssg = tpersg;
}
public void setTperpl(String tperpl){
this.tperspl = tperpl;
}
//getters
public String getVerbname(){
return this.verbname;
}
public String getFpersg(){
return this.fpersg;
}
public String getFperpl(){
return this.fperspl;
}
public String getSpersg(){
return this.sperssg;
}
public String getSperpl(){
return this.sperspl;
}
public String getTpersg(){
return this.tperssg;
}
public String getTperspl(){
return this.tperspl;
}
}
//the adapter
public class VerbAdapter extends ArrayAdapter<Verb>{
Context mContext;
int layoutResourceId;
Verb data[] = null;
public VerbAdapter(Context mContext, int layoutResourceId, Verb[] data){
super(mContext, layoutResourceId, data);
this.mContext = mContext;
this.layoutResourceId =layoutResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if (convertView == null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId,parent, false);
}
TextView textView0 = (TextView) convertView.findViewById(R.id.nameVerb);
TextView textView1 = (TextView) convertView.findViewById(R.id.firstpersonsg);
TextView textView2 = (TextView) convertView.findViewById(R.id.firstpersonpl);
TextView textView3 = (TextView) convertView.findViewById(R.id.secondpersonsg);
TextView textView4 = (TextView) convertView.findViewById(R.id.secondpersonpl);
TextView textView5 = (TextView) convertView.findViewById(R.id.thirdpersonsg);
TextView textView6 = (TextView) convertView.findViewById(R.id.thirdpersonpl);
Verb verb = data[position];
textView0.setText(verb.verbname);
textView1.setText(verb.fpersg);
textView2.setText(verb.fperspl);
textView3.setText(verb.sperssg);
textView4.setText(verb.sperspl);
textView5.setText(verb.tperssg);
textView6.setText(verb.tperspl);
return convertView;
}
}
------and two XML files named activity_verbs where the list is declared and row_verbs where the layout of each item is declared-----
row_verbs.xml ------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/nameVerb"
android:text="#string/nameVerb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7663d5"
android:textColor="#f8f8f8"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="0dp"
android:textStyle="bold" />
<TextView
android:id="#+id/firstpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/firstsg"
android:layout_below="#+id/nameVerb"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#cacaca"
android:textColor="#7663d5" />
<TextView
android:id="#+id/firstpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/firstpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/nameVerb"
android:layout_toRightOf="#+id/firstpersonsg"/>
<TextView
android:id="#+id/secondpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/secondsg"
android:layout_below="#+id/firstpersonsg"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#FFCACACA"
android:textColor="#7663d5" />
<TextView
android:id="#+id/secondpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/secondpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/firstpersonpl"
android:layout_toRightOf="#+id/secondpersonsg"/>
<TextView
android:id="#+id/thirdpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/thirdsg"
android:layout_below="#+id/secondpersonsg"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#FFCACACA"
android:textColor="#7663d5" />
<TextView
android:id="#+id/thirdpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/thirdpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/secondpersonpl"
android:layout_toRightOf="#+id/thirdpersonsg"/>
</RelativeLayout>
and the other one activity_verbs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="${relativePackage}.${activityClass}"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textSize="20sp"
android:padding="10dp"
android:background="#7663d5"
android:textColor="#f8f8f8"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lessonId"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#292929"
android:textColor="#f0f0f0"
android:padding="10dp"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/lessonId"/>
</RelativeLayout>
I copied your code with only one change:
I removed
tools:context="${relativePackage}.${activityClass}"
from activity_verbs and it works like a charm for me:
I uploaded my test-project with your code to DropBox, feel free to download it:
https://www.dropbox.com/s/8fcdab3rmx8zb57/ElaPinkSO.zip?dl=0
P.S. Very well structured question, good job!

Categories

Resources