Android : custom adapter showing data multiple times - java

I am building a test application with kinvey as a backend.I download the kinvey entities from the backend and add them to my adapter.The adapter behaves wrongly the first data entity is accessed three times.
The code for adapter is below
public class ImageAdapter extends BaseAdapter {
private static final String TAG = ImageAdapter.class.getSimpleName();
private static ImageFetcher mImageFetcher;
private ArrayList<ImageEntity> mImageEntities;
private Context mContext;
private LayoutInflater mLayoutInflater;
public ImageAdapter(Context context, ArrayList<ImageEntity> imageEntities) {
mContext = context;
mImageEntities = imageEntities;
mLayoutInflater = LayoutInflater.from(context);
mImageFetcher = new ImageFetcher(context);
}
#Override
public int getCount() {
return mImageEntities.size();
}
#Override
public Object getItem(int position) {
return mImageEntities.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView != null) {
viewHolder = (ViewHolder) convertView.getTag();
} else {
convertView = mLayoutInflater.inflate(R.layout.grid_item_layout, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
ImageEntity imageEntity = mImageEntities.get(position);
Log.d(TAG, imageEntity.getId());
viewHolder.textView.setText(imageEntity.getId());
viewHolder.imageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_launcher));
mImageFetcher.loadImage(viewHolder.imageView, imageEntity.getId());
return convertView;
}
static class ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.id_simple_image);
textView = (TextView) v.findViewById(R.id.textview);
}
}
}
The code for the Activity is
public class ImageActivity extends ActionBarActivity {
private static final int CAPTURE_IMAGE_REQUEST_CODE = 11;
private static final int MEDiA_TYPE_IMAGE = 1;
private static final int PICK_IMAGE = 2;
private static final String TAG = ImageActivity.class.getSimpleName();
private Client mKinveyClient;
private EntitySource mEntitySource;
private Uri mFileUri;
private GridView mGridView;
private ImageAdapter mImageAdapter;
private ArrayList<ImageEntity> mImageEntities;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
mEntitySource = EntitySource.getEntitySource(this);
mKinveyClient = TestApplication.getClientInstance();
mGridView = (GridView) findViewById(R.id.gridview);
mImageEntities = new ArrayList<>();
if (!mKinveyClient.user().isUserLoggedIn()) {
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
mImageAdapter = new ImageAdapter(this, mImageEntities);
mGridView.setAdapter(mImageAdapter);
}
private void updateData() {
AsyncAppData<ImageEntity> events = mKinveyClient.appData("events", ImageEntity.class);
events.get(new KinveyListCallback<ImageEntity>() {
#Override
public void onSuccess(ImageEntity[] imageEntities) {
mImageEntities.addAll(Arrays.asList(imageEntities));
for (ImageEntity imageEntity : imageEntities) {
System.out.println(imageEntity.getId());
}
mImageAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Throwable throwable) {
Log.d(TAG, "Fail " + throwable.getMessage());
}
});
}
Log: shows three entities are downloaded but in adapter the first entity is accessed three times.Please help
12-22 18:43:39.742: V/Kinvey - Client(16995): adding new instance of AppData, new collection name
12-22 18:43:40.628: I/System.out(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.628: I/System.out(16995): 5497cedfe21a6f05030016b8
12-22 18:43:40.629: I/System.out(16995): 5498062bc0f22386510111b6
12-22 18:43:40.635: D/ImageAdapter(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.640: D/ImageAdapter(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.641: D/ImageAdapter(16995): 5497cdc4b76664a0030358a2
12-22 18:43:40.643: D/ImageAdapter(16995): 5497cedfe21a6f05030016b8

You are adding to the array every time you get results back in updateData. You need to reset the collection each time, so call clear first:
mImageEntities.clear();
mImageEntities.addAll(Arrays.asList(imageEntities));

Related

get and set global variables from CustomListViewAdapter

Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}

How to pass onClickHandler as parameter while setting adapter for a RecyclerView in a Fragment?

I made an Adapter for my recyclerView. This adapter works when I use on any xxxActivity.java but when I try to use is on a Fragment Its hows error. Doesn't let me Pass the onClickHandler() that I created in Adapter.
I am Setting Adapter Like this -
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, mClickHandler)); //ClickListener doesn't work :'(
Another try was like --
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, getmClickHandler()));
Here, I implemented getClickHandler() in the Fragment--
public FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler getmClickHandler() {
return mClickHandler;
} //Still doesn't work :'(
and the Adapter Part--
Constructor like this-
public FixedPlaceListAdapter(Context mContext, List<PlaceBean>
placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
I tried to do this ... but still doesn't work--
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler.mClickhandler));
here is my full adapter code-
public class FixedPlaceListAdapter extends RecyclerView.Adapter<FixedPlaceListAdapter.FixedPlaceListAdapterViewHolder> {
private final FixedPlaceListAdapterOnclickHandler mClickHandler;
Context mContext;
List<PlaceBean> placeBeanList;
public FixedPlaceListAdapter(Context mContext, List<PlaceBean> placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
public void setData(List<PlaceBean> placeBeanList) {
this.placeBeanList = placeBeanList;
notifyDataSetChanged();
}
#Override
public FixedPlaceListAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.top_list_single, parent, false);
return new FixedPlaceListAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(FixedPlaceListAdapterViewHolder holder, int position) {
PlaceBean pb = placeBeanList.get(position);
holder.nameTextView.setText(pb.getName());
holder.addressTextView.setText(pb.getVicinity());
holder.rating.setRating(pb.getRating());
if (pb.getPhotoref() != null) {
String imageUrl = UrlsUtil.getSinglePhotoUrlString(mContext, pb.getPhotoref(), "350", "300");
Picasso.with(mContext)
.load(imageUrl)
.into(holder.thumbnailImage);
}
}
#Override
public int getItemCount() {
return placeBeanList.size();
}
public interface FixedPlaceListAdapterOnclickHandler {
void onClick(String id);
}
public class FixedPlaceListAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
RatingBar rating;
ImageView thumbnailImage;
public FixedPlaceListAdapterViewHolder(View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.place_name_now_in_list);
addressTextView = (TextView) itemView.findViewById(R.id.address_in_list);
rating = (RatingBar) itemView.findViewById(R.id.rating_single_place_in_list);
thumbnailImage = (ImageView) itemView.findViewById(R.id.place_image_thumb);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String placeID = placeBeanList.get(getAdapterPosition()).getPlaceref();
mClickHandler.onClick(placeID);
}
}
}
Need Help!
public class CategoryNewsListAdapter extends RecyclerView.Adapter<CategoryNewsListAdapter.ViewHolder> {
private List<CategoryNews> actors = new ArrayList<>();
private Context mContext;
private Queue<List<CategoryNews>> pendingUpdates =
new ArrayDeque<>();
**public interface NewsItemClickListener {
void onNewsItemClick(int pos, CategoryNews categoryNews, ImageView shareImageView);
}**
**NewsItemClickListener newsItemClickListener;**
public CategoryNewsListAdapter(List<CategoryNews> personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.particular_cat_news_list_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("BusinessSubCategoryListAdapter", "Bindviewholder without payload");
final CategoryNews newsCategory = actors.get(position);
holder.news_title.setText(newsCategory.getPostTitle());
holder.news_date.setText(newsCategory.getPostDate());
holder.news_category.setText(newsCategory.getCategoryName());
holder.news_description.setText(newsCategory.getPostContent());
// GlideApp
// .with(mContext).load(newsCategory.getPostImage())
// .placeholder(R.mipmap.ic_launcher) // can also be a drawable
// .error(R.drawable.placeholder_image) // will be displayed if the image cannot be loaded
// .crossFade()
// .into(holder.news_image);
Picasso.with(mContext).load(newsCategory.getPostImage()).placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image).into(holder.news_image);
**holder.itemView.setOnClickListener(v -> {
newsItemClickListener.onNewsItemClick(position, newsCategory, holder.news_image);
});**
}
#Override
public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
// if empty, do full binding;
onBindViewHolder(holder, position);
return;
}
Bundle bundle = (Bundle) payloads.get(0);
String newTitle = bundle.getString("NAME_CHANGE");
if (newTitle != null) {
// add some animation if you want
final CategoryNews actor = actors.get(position);
holder.news_title.setText(actor.getPostTitle());
holder.news_date.setText(actor.getPostDate());
holder.news_category.setText(actor.getCategoryName());
holder.news_description.setText(actor.getPostContent());
}
}
public void addItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(curSize, newItems.size());
}
public void updtateItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(0,newItems.size()- getItemCount()-1);
}
#Override
public int getItemCount() {
return actors.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView news_title, news_date, news_category, news_description;
private ImageView news_image;
public ViewHolder(View itemView) {
super(itemView);
news_title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_category = (TextView) itemView.findViewById(R.id.news_category);
news_description = (TextView) itemView.findViewById(R.id.news_description);
news_image = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
And In your activity
implements NewsItemClickListener
create object NewsItemClickListener newsItemClickListner;
inside oncreate newsItemClickListner=this; (you mush have implemented 1)
pass that object to recyclerview.
In adapter it is received by this
public CategoryNewsListAdapter(List personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
In your activity
CategoryNewsListAdapter categoryNewsListAdapter= new CategoryNewsListAdapter(list,this,newsItemClickListner)
After doing all this your overriden method will be called when you click in item of recycler view where you have set onclick listner
Okay .. The Problem is Fixed now ...
I was passing the wrong value or maybe the method of passing the ClickHandler was wrong.
The Solution of the Problem :
I Created another Class for ClickHandler-
public class PlaceCardClickHandler implements
FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler,
PlaceListAdapter.PlaceListAdapterOnclickHandler {
Context mContext;
public PlaceCardClickHandler(Context mContext) {
this.mContext = mContext;
}
#Override
public void onClick(String id) {
Intent intentToStartDetail = new Intent(mContext, PlaceDetailActivity.class);
intentToStartDetail.putExtra("id", id);
mContext.startActivity(intentToStartDetail);
}
}
and the change in the Fragment was like this- (Just passed a object from the ClickHandler class)
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, new PlaceCardClickHandler(getContext())));

Handle click events of both Recyclerview and CardView in same time

I have requirement to create nested recyclerView like
RecyclerView Contains-> CardView contains-> RecyclerView.
If I click on card I'm getting child position only but I also need parent card position. How can I handle click events of both Recyclerview and CardView at same time?
MainActivity.java:
public class MainActivity extends Activity {
LinearLayout linView;
private RecyclerView main_view;
RootAdapter adapter2;
private RelativeLayout mRelativeLayout;
private Context mContext;
private Activity mActivity;
int pos = 0;
int main_pos;
private static RecyclerView.Adapter adapter;
private static RecyclerView.Adapter adapterCo;
private RecyclerView.LayoutManager layoutManager;
private static ArrayList<DataModelMain> dataMain;
private static ArrayList<DataModel_CO> dataCo;
static View.OnClickListener myOnClickListener;
static View.OnClickListener onClickListener;
private static ArrayList<Integer> removedItems;
TestMain mainData = new TestMain();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prof = (ImageView) findViewById(R.id.profile);
main_view = (RecyclerView) findViewById(R.id.recycler_main);
mRelativeLayout = (RelativeLayout) findViewById(R.id.partners);
cont = (TextView) findViewById(R.id.mobile);
iconType = (ImageView) findViewById(R.id.icon_type);
linView = (LinearLayout) findViewById(R.id.layout_view);
// Get the application context
mContext = getApplicationContext();
// Get the activity
mActivity = MainActivity.this;
myOnClickListener = new MyOnClickListener(this);
onClickListener = new OnClickListener(this);
main_view.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL,
false
) {
};
main_view.setLayoutManager(layoutManager);
main_view.setItemAnimator(new DefaultItemAnimator());
dataMain = new ArrayList<DataModelMain>();
getMainData();
setMainView();
}
}
private void getMainData() {
for (int i = 0; i < mainData.passengers.length; i++) {
dataMain.add(new DataModelMain(
mainData.type[i],
mainData.passengers[i],
mainData.p_name[i],
mainData.p_contact[i],
mainData.p_flight[i],
mainData.p_pnr[i],
mainData.air[i],
mainData.p_time[i]
));
}
adapter2 = new RootAdapter(this, dataMain);
main_view.setAdapter(adapter2);
}
private class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
showIcons(v);
}
private void showIcons(View v) {
pos = main_view.getChildPosition(v);
setMainView();
}
}
private class OnClickListener implements View.OnClickListener {
private final Context context1;
private OnClickListener(Context context0) {
this.context1 = context0;
}
#Override
public void onClick(View v) {
showIcons(v);
}
private void showIcons(View v) {
pos = main_view.getChildPosition(v);
Log.e("CLICKED","pos: "+pos);
}
}
private class RootAdapter extends RecyclerView.Adapter<RootAdapter.RootViewHolder> {
private final LayoutInflater inflater;
String[] _items = new String[]{"GROUP 1", "GROUP 2", "GROUP 3", "GROUP 4"};
private ArrayList<DataModelMain> dataSet;
public RootAdapter(Context context,ArrayList<DataModelMain> data) {
inflater = LayoutInflater.from(context);
this.dataSet = data;
}
#Override
public RootViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.card_main, viewGroup, false);
RootViewHolder rvi = new RootViewHolder(view);
view.setOnClickListener(MainActivity.onClickListener);
return rvi;
}
#Override
public void onBindViewHolder(RootViewHolder rootViewHolder, int i) {
rootViewHolder.recyclerViewChild.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
rootViewHolder.recyclerViewChild.setAdapter(new ChildAdapter(inflater,dataSet));
}
#Override
public int getItemCount() {
return _items.length;
}
class RootViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerViewChild;
public RootViewHolder(View itemView) {
super(itemView);
recyclerViewChild = (RecyclerView) itemView.findViewById(R.id.recycler_partners);
}
}
}
private class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {
private LayoutInflater _inflater;
private ArrayList<DataModelMain> dataSet;
public ChildAdapter(LayoutInflater inflater,ArrayList<DataModelMain> data) {
_inflater = inflater;
this.dataSet = data;
}
#Override
public ChildViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = _inflater.inflate(R.layout.card_partner, viewGroup, false);
ChildViewHolder rvi = new ChildViewHolder(view);
view.setOnClickListener(MainActivity.myOnClickListener);
return rvi;
}
#Override
public void onBindViewHolder(ChildViewHolder holder, int listPosition) {
TextView name = holder.tvName;
TextView cont = holder.tvCont;
TextView flight = holder.tvFlight;
TextView pnr = holder.tvPNR;
TextView time = holder.tvTime;
ImageView type = holder.im_type;
ImageView pic = holder.im_pic;
ImageView logo = holder.im_logo;
CardView cardView = holder.card;
name.setText(dataSet.get(listPosition).getName());
cont.setText(dataSet.get(listPosition).getContact());
flight.setText(dataSet.get(listPosition).getFlight());
pnr.setText(dataSet.get(listPosition).getPnr());
time.setText(dataSet.get(listPosition).getTime());
type.setImageResource(dataSet.get(listPosition).getType());
pic.setImageResource(dataSet.get(listPosition).getImage());
logo.setImageResource(dataSet.get(listPosition).getLogo());
switch (dataSet.get(listPosition).getType()){
case R.mipmap.gov:
cardView.setCardBackgroundColor(Color.parseColor("#FAFAD2"));
break;
case R.mipmap.vip:
cardView.setCardBackgroundColor(Color.parseColor("#CDFFCD"));
break;
case R.mipmap.jail:
cardView.setCardBackgroundColor(Color.parseColor("#FFE4E1"));
break;
case R.mipmap.ban:
cardView.setCardBackgroundColor(Color.parseColor("#DCDCDC"));
break;
}
}
#Override
public int getItemCount() {
return dataSet.size();
}
public class ChildViewHolder extends RecyclerView.ViewHolder {
ImageView im_type,im_pic,im_logo;
TextView tvName,tvCont,tvFlight,tvPNR,tvTime;
CardView card;
public ChildViewHolder(View itemView) {
super(itemView);
this.card = (CardView) itemView.findViewById(R.id.card_view);
this.im_type = (ImageView) itemView.findViewById(R.id.p_type);
this.im_pic = (ImageView) itemView.findViewById(R.id.p_profile);
this.im_logo = (ImageView) itemView.findViewById(R.id.p_air_lines);
this.tvName = (TextView) itemView.findViewById(R.id.p_name);
this.tvCont = (TextView) itemView.findViewById(R.id.p_mob);
this.tvFlight = (TextView) itemView.findViewById(R.id.p_flight);
this.tvPNR = (TextView) itemView.findViewById(R.id.p_pnr);
this.tvTime = (TextView) itemView.findViewById(R.id.p_timer);
}
}
}
}
How about making the root/parent cardView clickable??
Give an id to the cardView item of the parent recyclerView. Place it in your ViewHolderClass and then assign a onCLickListener to the cardView in BindViewHolder like this:
rootViewHolder.rootCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// keep an track of the selected position of the cardView and store it in a global/local variable
}
});
you can track the adapter position of the selected cardView using
rootViewHolder.getAdapterPosition()
Note: rootViewHolder is written as per your ViewHolder class
I hope this helps !!

How to refresh viewpager after delete operation

In my app ,i used view pager to show my image gallery .
after deleteing any image from my gallery , view pager should get updated.
My Activity
public class FullScreenViewActivityForSelfImage extends Activity{
#SuppressWarnings("unused")
private Utils utils;
private FullScreenImageAdapterForSelfImage adapter;
private static ViewPager viewPager;
DatabaseHelper db;
ArrayList<Image> aryimages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
db=new DatabaseHelper(this);
viewPager = (ViewPager) findViewById(R.id.pager);
aryimages= db.getimages();
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapterForSelfImage(FullScreenViewActivityForSelfImage.this,
aryimages,this);
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
public static ViewPager getAdapter() {
return viewPager;
}
}
My Adapter Class
public class FullScreenImageAdapterForSelfImage extends PagerAdapter
{
private Activity _activity;
private ArrayList<Image> _imagePaths;
ArrayList<Image> aryimages;
public ImageListAdapter ImageListAdapter;
private LayoutInflater inflater;
private Context context;
int columnWidth,width,cellWidth,padding,height;
DatabaseHelper db;
int i;
String id,name;
// constructor
public FullScreenImageAdapterForSelfImage(Activity activity,
ArrayList<Image> aryimages,Context context) {
this._activity = activity;
this._imagePaths = aryimages;
this.context = context;
db= new DatabaseHelper(_activity);
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
My Adapter where delete service is called
btndel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("You are about to delete all images of this product continue");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
name = _imagePaths.get(position).Image_name.toString();
String imei=db.SelectImeiNo();
id=db.getidbyname(name);
System.out.println("selected imei = "+imei);
System.out.println("selected id = "+id);
dialog.cancel();
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, context , "Deleting Image...");
wst.execute(new String[] { Service_url });
}
});
In Adapter i tried to refresh
public void handleResponse(String response) {
System.out.println("handle REsponse...got result..."+response);
if(response.equalsIgnoreCase("0"))
{
System.out.println("!!!!!!!!!!Server Busy try again latter!!!!!!!!!!!!!!!!");
Toast.makeText(context.getApplicationContext(), "Server Busy try again latter", Toast.LENGTH_LONG).show();
}
else if(response.equalsIgnoreCase("1"))
{
System.out.println("!!!!!!!!!!!!Image deleted!!!!!!!!!!!!!!!!!!!");
Toast.makeText(context.getApplicationContext(), "Image deleted", Toast.LENGTH_LONG).show();
db.deleteImageSelected(id);
_imagePaths.remove(i);
ImageListAdapter.notifyDataSetChanged();
}
}
Image Adapter
public class ImageListAdapter extends BaseAdapter {
//private Context context;
private ArrayList<Image> Img;
private LayoutInflater inflater = null;
public ImageListAdapter(Context context, ArrayList<Image> Image) {
// this.context = context;
this.Img = Image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Img.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#SuppressWarnings("unused")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
view = inflater.inflate(R.layout.imageshow, null);
} else {
view = convertView;
}
ImageView iv= (ImageView) view.findViewById(R.id.imageshowView1);
TextView name= (TextView) view.findViewById(R.id.Imageshownametv);
TextView id= (TextView) view.findViewById(R.id.Imageshowidtv);
TextView desc= (TextView) view.findViewById(R.id.Imageshowimagedesc);
id.setText(Img.get(position).Image_id);
byte[] I= Img.get(position).image;
System.out.println("Byte array of the image "+I);
Bitmap bp=BitmapFactory.decodeByteArray(I, 0, I.length);
iv.setImageBitmap(bp);
return view;
}
}
But it is not done
so please help me..

why is notifyDataSetChanged() not working in my code?

Why is my code not working? I have already tried using notifyDataSetChanged(), or using invalid() for my listview, or using .setAdapter() again for my adapter, but its still not working please help me.
public class ListDel extends Activity{
ListView mylist_del;
ListViewAdapter listViewAdapter_del;
TypedArray images_del;
ImageView bin_image;
private static String[] names, ages;
storageListImplementation lists = new storageListImplementation();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.del_layout);
names = lists.getNames();
ages = lists.getAges();
images_del = getResources().obtainTypedArray(R.array.icons);
bin_image = (ImageView)findViewById(R.id.del_image_icon);
listViewAdapter_del = new ListViewAdapter(this);
mylist_del = (ListView)findViewById(R.id.listview_delete);
mylist_del.setAdapter(listViewAdapter_del);
}
private class ListViewAdapter extends BaseAdapter{
private LayoutInflater mInflater;
public ListViewAdapter(Context context){
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return names.length;
}
public Object getItem(int pos) {
return pos;
}
public long getItemId(int position) {
return position;
}
private OnClickListener binClick(ImageView img, final int position, String name) {
return new View.OnClickListener(){
public void onClick(View v) {
lists.del(names[position]);
mylist_del.invalidate();
//mylist_del.setAdapter(listViewAdapter_del);
listViewAdapter_del.notifyDataSetInvalidated();
listViewAdapter_del.notifyDataSetChanged();
//newlistviewadap();
//mylist_del.setAdapter(new ListViewAdapter(this));
//listViewAdapter_del.notifyDataSetChanged();
//String addSuccessful = "You have successfully deleted "+names[position]+" and his/her information in you database";
//Toast.makeText(getApplicationContext(), addSuccessful, Toast.LENGTH_LONG).show();
//ListDel.this.finish();
}
};
}
public void newlistviewadap(){
mylist_del.setAdapter(listViewAdapter_del);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder textView;
if(convertView==null){
convertView = mInflater.inflate(R.layout.del_listview_row, null);
textView = new ViewHolder();
textView.text = (TextView) convertView.findViewById(R.id.del_values_row);
textView.age = (TextView) convertView.findViewById(R.id.del_age_row);
textView.image = (ImageView) convertView.findViewById(R.id.del_image);
textView.delbutton = (ImageView) convertView.findViewById(R.id.del_image_icon);
convertView.setTag(textView);
}else{
textView = (ViewHolder) convertView.getTag();
}
textView.text.setText(names[position]);
textView.age.setText(ages[position]);
textView.image.setImageDrawable(images_del.getDrawable(position));
textView.delbutton.setOnClickListener(binClick( textView.delbutton, position, names[position]));
return convertView;
}
}
static class ViewHolder{
TextView text;
TextView age;
ImageView image;
ImageView delbutton;
}
}
Try removing
listViewAdapter_del.notifyDataSetInvalidated();
Once you've called it, mylist_del will not retrieve more data from listViewAdapter_del, so only keep the code below and try again:
lists.del(names[position]);
listViewAdapter_del.notifyDataSetChanged();

Categories