how to load image in gridview using using qualcomn SNPE SDK? - java

I am follow this link tutorial [https://developer.qualcomm.com/software/snapdragon-neural-processing-engine-ai/getting-started and i am able to download all model image but my requirement is now i need how to display gallery image in grid view my code is for model overview fragment:
public class ModelOverviewFragment extends Fragment {
public static final String EXTRA_MODEL = "model";
enum MenuRuntimeGroup {
SelectCpuRuntime(NeuralNetwork.Runtime.CPU),
SelectGpuRuntime(NeuralNetwork.Runtime.GPU),
SelectDspRuntime(NeuralNetwork.Runtime.DSP);
public static int ID = 1;
public NeuralNetwork.Runtime runtime;
MenuRuntimeGroup(NeuralNetwork.Runtime runtime) {
this.runtime = runtime;
}
}
private GridView mImageGrid;
private ModelImagesAdapter mImageGridAdapter;
private ModelOverviewFragmentController mController;
private TextView mDimensionsText;
private TextView mModelNameText;
private Spinner mOutputLayersSpinners;
private TextView mClassificationText;
private TextView mModelVersionText;
public static ModelOverviewFragment create(final Model model) {
final ModelOverviewFragment fragment = new ModelOverviewFragment();
final Bundle arguments = new Bundle();
arguments.putParcelable(EXTRA_MODEL, model);
fragment.setArguments(arguments);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_model, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mImageGrid = (GridView) view.findViewById(R.id.model_image_grid);
mImageGridAdapter = new ModelImagesAdapter(getActivity());
mImageGrid.setAdapter(mImageGridAdapter);
mImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Bitmap bitmap = mImageGridAdapter.getItem(position);
mController.classify(bitmap);
}
});
mModelNameText = (TextView) view.findViewById(R.id.model_overview_name_text);
mModelVersionText = (TextView) view.findViewById(R.id.model_overview_version_text);
mDimensionsText = (TextView) view.findViewById(R.id.model_overview_dimensions_text);
mOutputLayersSpinners = (Spinner) view.findViewById(R.id.model_overview_layers_spinner);
mClassificationText = (TextView) view.findViewById(R.id.model_overview_classification_text);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
final Model model = getArguments().getParcelable(EXTRA_MODEL);
mController = new ModelOverviewFragmentController(
(Application) getActivity().getApplicationContext(), model);
}
#Override
public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
final SNPE.NeuralNetworkBuilder builder = new SNPE.NeuralNetworkBuilder(
(Application) (getActivity().getApplicationContext()));
for (MenuRuntimeGroup item : MenuRuntimeGroup.values()) {
if (builder.isRuntimeSupported(item.runtime)) {
menu.add(MenuRuntimeGroup.ID, item.ordinal(), 0, item.runtime.name());
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getGroupId() == MenuRuntimeGroup.ID) {
final MenuRuntimeGroup option = MenuRuntimeGroup.values()[item.getItemId()];
mController.setTargetRuntime(option.runtime);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
mController.attach(this);
}
#Override
public void onStop() {
mController.detach(this);
super.onStop();
}
public void addSampleBitmap(Bitmap bitmap) {
if (mImageGridAdapter.getPosition(bitmap) == -1) {
mImageGridAdapter.add(bitmap);
mImageGridAdapter.notifyDataSetChanged();
}
}
public void setNetworkDimensions(Map<String, int[]> inputDimensions) {
mDimensionsText.setText(Arrays.toString(inputDimensions.get("data")));
}
public void displayModelLoadFailed() {
mClassificationText.setVisibility(View.VISIBLE);
mClassificationText.setText(R.string.model_load_failed);
Toast.makeText(getActivity(), R.string.model_load_failed, Toast.LENGTH_SHORT).show();
}
public void setModelName(String modelName) {
mModelNameText.setText(modelName);
}
public void setModelVersion(String version) {
mModelVersionText.setText(version);
}
public void setOutputLayersNames(Set<String> outputLayersNames) {
mOutputLayersSpinners.setAdapter(new ArrayAdapter<>(
getActivity(), android.R.layout.simple_list_item_1,
new LinkedList<>(outputLayersNames)));
}
public void setClassificationResult(String[] classificationResult) {
if (classificationResult.length > 0) {
mClassificationText.setText(
String.format("%s: %s", classificationResult[0], classificationResult[1]));
}
mClassificationText.setVisibility(View.VISIBLE);
}
public void setLoadingVisible(boolean visible) {
mClassificationText.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
mClassificationText.setText(R.string.loading_network);
}
}
public void displayModelNotLoaded() {
Toast.makeText(getActivity(), R.string.model_not_loaded, Toast.LENGTH_SHORT).show();
}
public void displayClassificationFailed() {
Toast.makeText(getActivity(), R.string.classification_failed, Toast.LENGTH_SHORT).show();
}
private static class ModelImagesAdapter extends ArrayAdapter<Bitmap> {
public ModelImagesAdapter(Context context) {
super(context, R.layout.model_image_layout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).
inflate(R.layout.model_image_layout, parent, false);
} else {
view = convertView;
}
final ImageView imageView = ImageView.class.cast(view);
imageView.setImageBitmap(getItem(position));
return view;
}
}
}
for image loading code :
public class LoadImageTask extends AsyncTask<File, Void, Bitmap> {
private final ModelOverviewFragmentController mController;
private final File mImageFile;
public LoadImageTask(ModelOverviewFragmentController controller, final File imageFile) {
mController = controller;
mImageFile = imageFile;
}
#Override
protected Bitmap doInBackground(File... params) {
return BitmapFactory.decodeFile(mImageFile.getAbsolutePath());
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mController.onBitmapLoaded(mImageFile, bitmap);
}
}
/*public class LoadImageTask extends AsyncTask{
private final ModelOverviewFragmentController mController;
private File path;
public LoadImageTask(ModelOverviewFragmentController controller, File jpeg)
{
mController=controller;
path=jpeg;
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Log.d("ImagePath",bitmap.toString());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
mController.onBitmapLoaded(path,result);
}
}
for model :
public class Model implements Parcelable {
public static final Uri MODELS_URI = Uri.parse("content://snpe/models");
// public static final Uri MODELS_URI=Uri.parse("content://mtp://[usb:002,029]/Internal%20shared%20storage/DCIM");
public static final String INVALID_ID = "null";
public File file;
public String[] labels;
public File[] rawImages;
public File[] jpgImages;
public String name;
public File meanImage;
protected Model(Parcel in) {
name = in.readString();
file = new File(in.readString());
final String[] rawPaths = new String[in.readInt()];
in.readStringArray(rawPaths);
rawImages = fromPaths(rawPaths);
final String[] jpgPaths = new String[in.readInt()];
in.readStringArray(jpgPaths);
jpgImages = fromPaths(jpgPaths);
meanImage = new File(in.readString());
labels = new String[in.readInt()];
in.readStringArray(labels);
}
public Model() {}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(file.getAbsolutePath());
dest.writeInt(rawImages.length);
dest.writeStringArray(toPaths(rawImages));
dest.writeInt(jpgImages.length);
dest.writeStringArray(toPaths(jpgImages));
dest.writeString(meanImage.getAbsolutePath());
dest.writeInt(labels.length);
dest.writeStringArray(labels);
}
private File[] fromPaths(String[] paths) {
final File[] files = new File[paths.length];
for (int i = 0; i < paths.length; i++) {
files[i] = new File(paths[i]);
}
return files;
}
private String[] toPaths(File[] files) {
final String[] paths = new String[files.length];
for (int i = 0; i < files.length; i++) {
paths[i] = files[i].getAbsolutePath();
}
return paths;
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public Model createFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
#Override
public String toString() {
return name.toUpperCase();
}
}

To load SD card images in grid view, please make few changes in loadImageSamples method of ModelOverviewFragmentController.java. Currently, the images are picked from snpe folder inside internal storage of the device and are populated on Grid View. To get all the images from the gallery, create AsyncTask class to load images from the Gallery to the Grid View with the help of Content Provider.
Please use this link https://stackoverflow.com/a/10877404 for code reference to load images on grid view.
Hope this helps!
Thank You

Related

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

Idk why is it not working, Im trying to transfer data, i'm doing an app but when i run it i get an error, the Error is in the BlogActivity Class
"showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));"(java.lang.NullPointerException).
This is BlogActivity Class:
public class BlogActivity extends AppCompatActivity{
private static final String EXTRAS_BLOG = "EXTRAS_BLOG";
private TextView textTitle;
private TextView textDate;
private TextView textAuthor;
private TextView textRating;
private TextView textDescription;
private TextView textViews;
private RatingBar ratingBar;
private ImageView imageAvatar;
private ImageView imageMain;
private ImageView imageBack;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogpage);
imageMain = findViewById(R.id.yemenImg);
imageAvatar = findViewById(R.id.yemenAvatar);
imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent myInt = new Intent(getApplicationContext(),MainActivity.class);
startActivity(myInt);
}
},2);
}
});
textDate = findViewById(R.id.dateYemen);
textTitle = findViewById(R.id.textTitle);
textAuthor = findViewById(R.id.yemenAuthor);
textRating = findViewById(R.id.textRating);
textViews = findViewById(R.id.textViews);
textDescription = findViewById(R.id.textDescription);
ratingBar = findViewById(R.id.ratingBar);
progressBar = findViewById(R.id.progressBar);
showData(getIntent().getExtras().getParcelable(EXTRAS_BLOG));
}
/*private void loadData()
{
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
showData(blogList.get(0));
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
showErrorSnackbar();
}
});
}
});
}*/
private void showData(Blog blog)
{
progressBar.setVisibility(View.GONE);
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
textAuthor.setText(blog.getAuthor().getName());
textRating.setText(String.valueOf(blog.getRating()));
textViews.setText(String.format("(%d views)", blog.getViews()));
textDescription.setText(blog.getDescription());
textDescription.setText(Html.fromHtml(blog.getDescription(),Html.FROM_HTML_MODE_COMPACT));
ratingBar.setRating(blog.getRating());
ratingBar.setVisibility(View.VISIBLE);
imageBack.setImageResource(R.drawable.ic_baseline_arrow_back_24);
Glide.with(this)
.load(blog.getImage())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageMain);
Glide.with(this)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
/*private void showErrorSnackbar()
{
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
snackbar.dismiss();
});
snackbar.show();
}*/
public static void startBlogDetailsActivity(Activity activity, Blog blog) {
Intent intent = new Intent(activity, BlogActivity.class);
intent.putExtra(EXTRAS_BLOG, blog);
activity.startActivity(intent);
}
Blog Class:
public class Blog implements Parcelable {
private String id;
private Author author;
private String title;
private String date;
private String image;
private String description;
private int views;
private float rating;
protected Blog(Parcel in) {
id = in.readString();
title = in.readString();
date = in.readString();
image = in.readString();
description = in.readString();
views = in.readInt();
rating = in.readFloat();
author = in.readParcelable(Author.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(date);
dest.writeString(image);
dest.writeString(description);
dest.writeInt(views);
dest.writeFloat(rating);
dest.writeParcelable(author, 0);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Blog> CREATOR = new Creator<Blog>() {
#Override
public Blog createFromParcel(Parcel in) {
return new Blog(in);
}
#Override
public Blog[] newArray(int size) {
return new Blog[size];
}
};
public String getTitle() {
return title;
}
public String getDate() {
return date;
}
public String getImage() {
return image;
}
public String getDescription() {
return description;
}
public int getViews() {
return views;
}
public float getRating() {
return rating;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getId() {
return id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Blog blog = (Blog) o;
return views == blog.views &&
Float.compare(blog.rating, rating) == 0 &&
Objects.equals(id, blog.id) &&
Objects.equals(author, blog.author) &&
Objects.equals(title, blog.title) &&
Objects.equals(date, blog.date) &&
Objects.equals(image, blog.image) &&
Objects.equals(description, blog.description);
}
#Override
public int hashCode() {
return Objects.hash(id, author, title, date, image, description, views, rating);
}
This is Main Activity Class:
public class MainActivity extends AppCompatActivity {
private MainAdapter adapter;
private SwipeRefreshLayout refreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainAdapter(blog ->
BlogActivity.startBlogDetailsActivity(this, blog));
RecyclerView recyclerView = findViewById(R.id.recylerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
refreshLayout = findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(this::loadData);
loadData();
}
private void loadData()
{
refreshLayout.setRefreshing(true);
BlogHttpClient.INSTANCE.loadBlogArticles(new BlogArticlesCallback() {
#Override
public void onSuccess(final List<Blog> blogList) {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
adapter.submitList(blogList);
}
});
}
#Override
public void onError() {
runOnUiThread(new Runnable() {
#Override
public void run() {
refreshLayout.setRefreshing(false);
showErrorSnackbar();
}
});
}
});
}
private void showErrorSnackbar() {
View rootView = findViewById(android.R.id.content);
Snackbar snackbar = Snackbar.make(rootView,"Error during loading blog articles",
Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.parseColor("#e0af1f"));
snackbar.setAction("Retry", v -> {
loadData();
snackbar.dismiss();
});
snackbar.show();
}
This is MainAdapter Class:
public class MainAdapter extends ListAdapter<Blog, MainAdapter.MainViewHolder>{
public interface OnItemClickListener{
void onItemClicked(Blog blog);
}
private OnItemClickListener clickListener;
public MainAdapter(OnItemClickListener clickListener){
super(DIFF_CALLBACK);
this.clickListener = clickListener;
}
#NonNull
#Override
public MainAdapter.MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_listlayout,parent,false);
return new MainViewHolder(view, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MainAdapter.MainViewHolder holder, int position)
{
holder.bindTo(getItem(position));
}
static class MainViewHolder extends RecyclerView.ViewHolder
{
private TextView textTitle;
private TextView textDate;
private ImageView imageAvatar;
private Blog blog;
public MainViewHolder(#NonNull View itemView, OnItemClickListener listener)
{
super(itemView);
itemView.setOnClickListener(view -> listener.onItemClicked(blog));
textTitle = itemView.findViewById(R.id.textTitle);
textDate = itemView.findViewById(R.id.textDate);
imageAvatar = itemView.findViewById(R.id.imageAvatar);
}
void bindTo(Blog blog)
{
textTitle.setText(blog.getTitle());
textDate.setText(blog.getDate());
Glide.with(itemView)
.load(blog.getAuthor().getAvatar())
.transform(new CircleCrop())
.transition(DrawableTransitionOptions.withCrossFade())
.into(imageAvatar);
}
}
private static final DiffUtil.ItemCallback<Blog> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Blog>()
{
#Override
public boolean areItemsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.getId().equals(newItem.getId());
}
#Override
public boolean areContentsTheSame(#NonNull Blog oldItem, #NonNull Blog newItem)
{
return oldItem.equals(newItem);
}
};
You may set value to blog variable in MainViewHolder.
Add this line to your bindTo() method body:
this.blog = blog

Images on RecyclerView does not updated after Image url changed

I am sending Request on fragment to receive Store Item data from Server which contains urls of images like below
public class StoreFragment extends BaseFragment<FragmentStoreBinding, StoreViewModel> implements StoreNavigator {
#Inject
StoreViewModel viewModel;
#Inject
StoreAdapter storeAdapter;
#Inject
StoreVO storeVO;
public static final String TAG = StoreFragment.class.getSimpleName();
private FragmentStoreBinding binding;
public static StoreFragment newInstance() {
Bundle args = new Bundle();
StoreFragment fragment = new StoreFragment();
fragment.setArguments(args);
return fragment;
}
public static StoreFragment newInstance(StoreVO storeVO) {
Bundle args = new Bundle();
StoreFragment fragment = new StoreFragment();
args.putString(INTENT_EXTRA_STOREVO, new Gson().toJson(storeVO)); //put string, int, etc in bundle with a key value
fragment.setArguments(args);
return fragment;
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.fragment_store;
}
#Override
public StoreViewModel getViewModel() {
return viewModel;
}
#Override
public void goBack() {
getBaseActivity().onFragmentDetached(TAG);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel.setNavigator(this);
storeAdapter.setStoreFragment(this);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume(){
super.onResume();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding = getViewDataBinding();
if (getArguments().containsKey(INTENT_EXTRA_STOREVO)) {
storeVO = new Gson().fromJson(getArguments().getString(INTENT_EXTRA_STOREVO), StoreVO.class);
}
initView();
}
#Override
public void onPrefClicked(String prefSn, boolean sendRequest) {
storeVO.setPrefSn(prefSn);
storeVO.setSearchKeyCode1(prefSn);
switch (prefSn) {
case EAT_PREF_SN:
binding.eatCb.setChecked(true);
break;
case DRINK_PREF_SN:
binding.drinkCb.setChecked(true);
break;
case PLAY_PREF_SN:
binding.playCb.setChecked(true);
break;
case WATCH_PREF_SN:
binding.watchCb.setChecked(true);
break;
case WALK_PREF_SN:
binding.walkCb.setChecked(true);
break;
default:
binding.allCb.setChecked(true);
}
if(sendRequest){
//initStoreView();
viewModel.requestStoreList(storeVO);
}
}
private void initView() {
binding.storeRv.setLayoutManager(new GridLayoutManager(getActivity().getApplicationContext(), 2));
binding.storeRv.setItemAnimator(new DefaultItemAnimator());
binding.storeRv.setAdapter(storeAdapter);
initStoreView();
onPrefClicked(storeVO.getPrefSn(), false);
}
private void initStoreView(){
viewModel.requestStoreList(storeVO);
subscribeStoreListLiveData();
}
private void subscribeStoreListLiveData() {
viewModel.getStoreListLiveData().observe(this, storeList -> {
viewModel.addStoreList(storeList);
if (storeList != null) {
binding.totalCount.setText(String.valueOf(storeList.size()));
}
});
}
}
view model for this fragment is like below
public class StoreViewModel extends BaseViewModel<StoreNavigator> {
public final ObservableList<StoreVO> storeObservableList = new ObservableArrayList<>();
// MutableLiveData는 LifeCycle에 의존하여 메모리관리 등 여러 장점을 지님
private final MutableLiveData<List<StoreVO>> storeListLiveData;
public StoreViewModel(BaseApplication baseApplication) {
super(baseApplication);
storeListLiveData = new MutableLiveData<>();
}
public void requestStoreList(StoreVO storeVO) {
getCompositeDisposable().add(
getRetrofitService().selectStoreInfoList(storeVO)
.subscribeOn(getNetworkHelper().getSchedulerIo())
.observeOn(getNetworkHelper().getSchedulerUi())
.subscribe(storeListLiveData::setValue, throwable -> Dlog.e(throwable.getMessage())));
}
public MutableLiveData<List<StoreVO>> getStoreListLiveData() {
return storeListLiveData;
}
public void addStoreList(List<StoreVO> storeList) {
storeObservableList.clear();
storeObservableList.addAll(storeList);
}
public ObservableList<StoreVO> getStoreObservableList() {
return storeObservableList;
}
public void onFilterClick() {
getNavigator().goToSearchFilterActivity();
}
public void onPrefTypeClicked(String prefSn) {
getNavigator().onPrefClicked(prefSn, true);
}
}
and storeList was attached by adapter like below
public class StoreAdapter extends RecyclerView.Adapter<StoreAdapter.StoreViewHolder> {
private List<StoreVO> storeList;
private StoreFragment storeFragment;
public StoreAdapter() {
this.storeList = new ArrayList<>();
}
#NonNull
#Override
public StoreViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
StoreItemListBinding binding = StoreItemListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
return new StoreViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull StoreViewHolder holder, int index) {
final int position = index;
holder.bind(storeList.get(index));
holder.itemView.setOnClickListener(v ->
storeFragment.goToPlaceDetailActivity(storeList.get(position)));
}
#Override
public void onViewDetachedFromWindow(#NonNull StoreViewHolder holder) {
holder.viewDetached();
super.onViewDetachedFromWindow(holder);
}
#Override
public int getItemCount() {
return storeList.size();
}
// Override for duplicated bugs
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
// Override for duplicated bugs
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public List<StoreVO> getStoreList() {
return storeList;
}
public void setStoreList(List<StoreVO> storeList) {
this.storeList = storeList;
}
public void clearItems() {
storeList.clear();
}
public void addItems(List<StoreVO> storeList) {
this.storeList.addAll(storeList);
notifyDataSetChanged();
}
public StoreFragment getStoreFragment() {
return storeFragment;
}
public void setStoreFragment(StoreFragment storeFragment) {
this.storeFragment = storeFragment;
}
class StoreViewHolder extends RecyclerView.ViewHolder {
private StoreItemListBinding binding;
private ArrayList<String> urlList;
StoreViewHolder(StoreItemListBinding binding) {
super(binding.getRoot());
this.urlList = new ArrayList<>();
this.binding = binding;
initImageSlider();
}
public void bind(StoreVO storeVO) {
binding.priceTv.setText(String.valueOf(storeVO.getReprMenuPrice()));
binding.addrTv.setText(storeVO.getAreaDetailNm());
binding.nameTv.setSelected(true);
binding.nameTv.setText(storeVO.getStoreNm());
binding.scoreTv.setText(String.format(Locale.KOREA, "%.1f", storeVO.getStoreScore()));
addImageSlider(storeVO);
}
private void initImageSlider() {
binding.storeSlider.setIndicatorAnimation(IndicatorAnimations.FILL); //set indicator animation by using SliderLayout.Animations. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
binding.storeSlider.setScrollTimeInSec(3); //set scroll delay in seconds :
}
private void addImageSlider(StoreVO storeVO) {
generateUrlList(storeVO);
setSliderViews();
}
private void generateUrlList(StoreVO storeVO) {
urlList.clear();
if (storeVO.getStoreImageUrlList().size() == 0) {
String url = CommonUtils.createDefaultImageUrl();
urlList.add(url);
} else {
for (String imageUrl : storeVO.getStoreImageUrlList()) {
String url = CommonUtils.createStoreImageUrl(storeVO.getStoreSn(), imageUrl);
urlList.add(url);
}
}
}
private void setSliderViews() {
binding.storeSlider.clearSliderViews();
for (String url : urlList) {
DefaultSliderView sliderView = new DefaultSliderView(binding.getRoot().getContext().getApplicationContext());
sliderView.setImageUrl(url);
sliderView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
//sliderView.setOnSliderClickListener(view -> Dlog.e(url));
//at last add this view in your layout :
binding.storeSlider.addSliderView(sliderView);
}
}
private void viewDetached() {
urlList.clear();
binding.storeSlider.clearSliderViews();
}
}
}
After storeList updated, Text on items of Recylerview was changed but ImageSlider on item was not changed.
I checked that viewDetached() on StoreViewHolder was called but images remaind on previous store item
i was using image sliders in github: https://github.com/smarteist/android-image-slider
what should i do to updated images for imagesliders on recycler-view items???
To simplify my question,
i was using RecyclerView to show items which contains image slider. That image slider load images through URL. After receive new itemList(storeList) from server, itemList(storeList) for RecylerView and URLs in Item(Store) for ImageSlider was changed but not updated on ImageSlider.
Through debugging, i checked that new UrlList was generated and setSliderViews was called but remains previous image
How do i fix my code to update Images on RecylerView's items?

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

Android volley singleton and custom gridview adapter

I am using a custom gridview adapter to show images with volley singleton. But when I run it it returns the onErrorResponse. It looks like the adapter is not even set properly, is it something with where i set the adapter? I have tried setting it in onCreate but same error.
The adapter class looked fine so I think the problem is in MainActivity.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int THUMBNAIL_SIZE = 250;
private final String KEY = "IMAGE";
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
private static final String URLS[] = {
"http://10.0.2.2/Android%20A4_1/germany.png",
"http://10.0.2.2/Android%20A4_1/indonesia.png",
"http://10.0.2.2/Android%20A4_1/japan.png",
"http://10.0.2.2/Android%20A4_1/sarawak.png",
"http://10.0.2.2/Android%20A4_1/singapore.png",
"http://10.0.2.2/Android%20A4_1/switzerland.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i<URLS.length; i++) {
LoadingImages(URLS[i]);
}
}
private void LoadingImages(String url) {
ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap image = response.getBitmap();
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
bitmaps.add(thumbnail);
GridView gridView = (GridView)findViewById(R.id.grid_layout);
final ImageAdapter imageAdapter = new ImageAdapter(MainActivity.this, bitmaps);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra(KEY, URLS[i]);
startActivity(intent);
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.getMessage());
}
});
}
}
The Adapter class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Bitmap> bitmaps;
public ImageAdapter(Context context, ArrayList<Bitmap> bitmaps) {
this.mContext = context;
this.bitmaps = bitmaps;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.griditems, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
view.setTag(myViewHolder);
}
MyViewHolder myViewHolder = (MyViewHolder)view.getTag();
myViewHolder.img.setImageBitmap(bitmaps.get(i));
return view;
}
public class MyViewHolder {
public ImageView img;
public MyViewHolder(View view) {
img = view.findViewById(R.id.image1);
}
}
}
My Singleton:
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context context;
private MySingleton(Context context){
this.context = context;
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(6);
#Override
public Bitmap getBitmap(String url) {
Bitmap bmp = cache.get(url);
if (bmp == null) {
System.out.println("Not in cache");
} else {
System.out.println("In cache");
}
return bmp;
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
System.out.println("Put in cache");
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Main2Activity:
public class Main2Activity extends AppCompatActivity {
private ImageView imageView;
private final String KEY = "IMAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView)findViewById(R.id.imageView);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString(KEY);
LoadingImages(url);
}
private void LoadingImages(String url) {
final ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
imageView.setImageBitmap(bitmap);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
});
}
}
change This methods
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
To
#Override
public int getCount() {
return bitmaps.size;
}
#Override
public Object getItem(int i) {
return bitmaps.get(i);
}
#Override
public long getItemId(int i) {
return i;
}

How To make RecyclerView handle onclicklistener [duplicate]

This question already has answers here:
RecyclerView onClick
(49 answers)
Closed 7 years ago.
Has anyone using RecyclerView found a way to set an onClickListener to items in the RecyclerView?
this my code:
Pasal_Bab.java
public class Pasal_Bab extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerViewEmptySupport rv;
private List<PasalBabModel> mPBH;
private PasalBabAdapter adapter;
private static ArrayList<PasalBabModel> people;
#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.activity_pasal, container, false);
rv = (RecyclerViewEmptySupport) view.findViewById(R.id.rv_pasal);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rv.setLayoutManager(layoutManager);
rv.setEmptyView(view.findViewById(R.id.empty));
rv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
String[] locales = Locale.getISOCountries();
mPBH = new ArrayList<>();
for (String countryCode : locales) {
Locale obj = new Locale("Pasalxyz", countryCode);
mPBH.add(new PasalBabModel(obj.getDisplayCountry(), obj.getISO3Country()));
}
adapter = new PasalBabAdapter(mPBH);
rv.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
adapter.setFilter(mPBH);
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<PasalBabModel> filteredModelList = filter(mPBH, newText);
adapter.animateTo(filteredModelList);
adapter.setFilter(filteredModelList);
rv.scrollToPosition(0);
return false;
}
private List<PasalBabModel> filter(List<PasalBabModel> models, String query) {
query = query.toLowerCase();
final List<PasalBabModel> filteredModelList = new ArrayList<>();
for (PasalBabModel model : models) {
final String text = model.getpasalbab_p().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
PasalBabAdapter.java
public class PasalBabAdapter extends RecyclerView.Adapter<PasalBabVH> {
private List<PasalBabModel> mPasalBabModel;
public PasalBabAdapter(List<PasalBabModel> mPasalBabModel) {
this.mPasalBabModel = mPasalBabModel;
}
#Override
public void onBindViewHolder(PasalBabVH PasalBabVH, int i) {
final PasalBabModel model = mPasalBabModel.get(i);
PasalBabVH.bind(model);
}
#Override
public PasalBabVH onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.pasalbab_row, viewGroup, false);
return new PasalBabVH(view);
}
public void setFilter(List<PasalBabModel> PasalBabModels) {
mPasalBabModel = new ArrayList<>();
mPasalBabModel.addAll(PasalBabModels);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mPasalBabModel.size();
}
public void animateTo(List<PasalBabModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<PasalBabModel> newModels) {
for (int i = mPasalBabModel.size() - 1; i >= 0; i--) {
final PasalBabModel model = mPasalBabModel.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<PasalBabModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final PasalBabModel model = newModels.get(i);
if (!mPasalBabModel.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<PasalBabModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final PasalBabModel model = newModels.get(toPosition);
final int fromPosition = mPasalBabModel.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public PasalBabModel removeItem(int position) {
final PasalBabModel model = mPasalBabModel.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, PasalBabModel model) {
mPasalBabModel.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final PasalBabModel model = mPasalBabModel.remove(fromPosition);
mPasalBabModel.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
}
PasalBabVH.java
public class PasalBabVH extends RecyclerView.ViewHolder {
public TextView p_TextView;
public TextView b_TextView;
public PasalBabVH(View itemView) {
super(itemView);
p_TextView = (TextView) itemView.findViewById(R.id.uud_pasal);
b_TextView = (TextView) itemView.findViewById(R.id.uud_bab);
}
public void bind(PasalBabModel mx) {
p_TextView.setText(mx.getpasalbab_p());
b_TextView.setText(mx.getpasalbab_b());
}
}
PasalBabModel.java
public class PasalBabModel {
String pasalbab_p;
String pasalbab_b;
public PasalBabModel(String pasalbab_p, String pasalbab_b) {
this.pasalbab_p = pasalbab_p;
this.pasalbab_b = pasalbab_b;
}
public String getpasalbab_p() {
return pasalbab_p;
}
public String getpasalbab_b() {
return pasalbab_b;
}
}
please helpme...i'm a beginner :)
Create the adapter like so:
public class CustomAdapter extends RecyclerView.Adapter<Custom.ViewHolder> {
private List<SomeObject> mDataSet;
public OnItemClickListener mItemClickListener;
private Context mContext;
public CustomAdapter(Context context, List<SomeObject> myDataset, OnItemClickListener mItemClickListener) {
this.mDataSet = myDataset;
this.mItemClickListener = mItemClickListener;
this.mContext = context;
}
public void updateData(List<SomeObject> mDataSet) {
this.mDataSet = mDataSet;
notifyDataSetChanged();
}
public void removeItem(int position) {
mDataSet.remove(position);
notifyItemRemoved(position);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final SomeObject obj = mDataSet.get(position);
holder.name.setText(obj.getName());
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView name;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.naam);
v.setOnClickListener(this);
v.setOnLongClickListener(this);
}
#Override
public void onClick(View v) {
// If not long clicked, pass last variable as false.
mItemClickListener.onItemClick(v, getLayoutPosition(), false, mDataSet);
}
#Override
public boolean onLongClick(View v) {
// If long clicked, passed last variable as true.
mItemClickListener.onItemClick(v, getLayoutPosition(), true, mDataSet);
return true;
}
}
public interface OnItemClickListener {
void onItemClick(View view, int position, boolean isLongClick, List<SomeObject> mFilteredList);
}
}
And set the adapter like this:
mAdapter = new CustomAdapter(getActivity(), dataSet, new CustomAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position, boolean isLongClick, List<SomeObject> mDataSet) {
if (isLongClick) {
//Long click
SomeObject obj = mDataSet.get(position);
} else {
//Normal click
SomeObject obj = mDataSet.get(position);
}
}
});
Use interfaces to handle onClicks.
Put this in the adapter:
public interface OnItemClickListener {
void onClickItem(View view, int position);
}
public void SetOnItemClickListener(OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
and then in view holder do this:
public class PasalBabVH extends RecyclerView.ViewHolder {
public TextView p_TextView;
public TextView b_TextView;
public PasalBabVH(View itemView) {
super(itemView);
p_TextView = (TextView) itemView.findViewById(R.id.uud_pasal);
b_TextView = (TextView) itemView.findViewById(R.id.uud_bab);
p_TextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
}
}
});
b_TextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
}
}
});
}
public void bind(PasalBabModel mx) {
p_TextView.setText(mx.getpasalbab_p());
b_TextView.setText(mx.getpasalbab_b());
}
}
In fragment do this:
adapter.SetOnItemClickListener(new PasalBabAdapter.OnItemClickListener() {
#Override
public void onClickItem(View view, int position) {
}});

Categories

Resources