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?
Related
This is the code for the nested recycler view.
If I add data using the push() method, i get the Nested RecycleView with Firebase this error:
Expected a List while deserializing, but got a class java.util.HashMap
AlertDialog dialog;
IFirebaseLoadListener iFirebaseLoadListener;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myData= FirebaseDatabase.getInstance().getReference("MyData");
dialog= new SpotsDialog.Builder().setContext(this).build();
iFirebaseLoadListener = this;
// view
my_recycler_view= (RecyclerView)findViewById(R.id.my_recycler_view);
my_recycler_view.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
load data
getFirebaseData();
}
private void getFirebaseData() {
dialog.show();
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<itemGroup> itemGroups= new ArrayList<>();
for(DataSnapshot groupSnapshot: dataSnapshot.getChildren())
{
itemGroup itemGroup= new itemGroup();
///
Firebase instance code
///
itemGroup.setHeaderTitle(groupSnapshot.child("headerTitle").getValue(true).toString());
GenericTypeIndicator<ArrayList<itemData>> genericTypeIndicator= new GenericTypeIndicator<ArrayList<itemData>>(){} ;
itemGroup.setListItem(groupSnapshot.child("listItem").child(key).getValue(genericTypeIndicator));
itemGroups.add(itemGroup);
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<itemGroup> itemGroupList) {
MyItemGroupAdapter adapter = new MyItemGroupAdapter(this,itemGroupList);
my_recycler_view.setAdapter(adapter);
dialog.dismiss();
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
public class itemData {
private String name ,image;
public itemData() {
}
public itemData(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
public class itemGroup {
private String headerTitle;
private ArrayList<itemData> listItem;
public itemGroup() {
}
public itemGroup(String headerTitle, ArrayList<itemData> listItem) {
this.headerTitle = headerTitle;
this.listItem = listItem;
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public ArrayList<itemData> getListItem() {
return listItem;
}
public void setListItem(ArrayList<itemData> listItem) {
this.listItem = listItem;
}
}
public class MyItemAdapter extends RecyclerView.Adapter<MyItemAdapter.MyViewHolder> {
private Context context;
private List<itemData> itemDataList;
public MyItemAdapter(Context context, List<itemData> itemDataList) {
this.context = context;
this.itemDataList = itemDataList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView =
LayoutInflater.from(context).inflate(R.layout.layout_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.txt_item_titles.setText(itemDataList.get(i).getName());
Picasso.get().load(itemDataList.get(i).getImage()).into(myViewHolder.img_item);
myViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int i) {
Toast.makeText(context, ""+ itemDataList.get(i).getName(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (itemDataList != null ? itemDataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
TextView txt_item_titles;
ImageView img_item;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public MyViewHolder (View itemView ){
super(itemView);
txt_item_titles= (TextView)itemView.findViewById(R.id.tvTitle);
img_item= (ImageView) itemView.findViewById(R.id.itemImage);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
iItemClickListener.onItemClickListener(v,getAdapterPosition());
}
}
}
public class MyItemGroupAdapter extends
RecyclerView.Adapter<MyItemGroupAdapter.MyViewHolder> {
private Context context;
private List<itemGroup> dataList;
public MyItemGroupAdapter(Context context, List<itemGroup> dataList) {
this.context = context;
this.dataList = dataList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView =
LayoutInflater.from(context).inflate(R.layout.layout_group,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.item_title.setText(dataList.get(i).getHeaderTitle());
List<itemData> itemData = dataList.get(i).getListItem();
MyItemAdapter itemListAdapter=new MyItemAdapter(context,itemData);
myViewHolder.recycler_view_item_list.setHasFixedSize(true);
myViewHolder.recycler_view_item_list.setLayoutManager(new
LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
myViewHolder.recycler_view_item_list.setAdapter(itemListAdapter);
myViewHolder.recycler_view_item_list.setNestedScrollingEnabled(false);
// btn more
myViewHolder.btn_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Button More "+ myViewHolder.item_title.getText(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (dataList != null ? dataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView item_title ;
RecyclerView recycler_view_item_list;
Button btn_more;
public MyViewHolder (View itemView ){
super (itemView);
item_title= (TextView) itemView.findViewById(R.id.itemTitle);
btn_more= (Button)itemView.findViewById(R.id.btMore);
recycler_view_item_list=
(RecyclerView)itemView.findViewById(R.id.recycler_view_list);
}
}
}
This happens when you try to have a structure like this in the database:
"list": {
"-Nasdueqriyew": "First value",
"-Nberqiy39esd": "Second value",
"-Nc3hadsiuhad": "Third value"
}
And then try to map it to a List or array in your Java class.
The JSON structure is not a list, because it was pairs of keys and values, which in Java translates to:
Map<String, Object>
So most likely, the List<itemData> in your code needs to be a Map<String, itemData>.
I am learning Room DataBase!!
I Know How to Insert and Retrieve Data from Room DataBase to Recycler View!! But In Delete Operation I am getting error of "No Adapter attached Skipped Layout!"
What I want when anyone click on delete button on recycler view . The Task should be deleted
That's why I also Used delete method in Interface and add Interface in Recycler View Adapter which give call back to MainActivity so that we delete and update the recycler view
All of my codes are given below
Here is my Entity Class named as Task
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "task_name")
private String task_name;
#ColumnInfo
private String task_desc;
#ColumnInfo
private String comment;
#ColumnInfo
private String task_comp_date;
#ColumnInfo
private String activate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public String getTask_desc() {
return task_desc;
}
public void setTask_desc(String task_desc) {
this.task_desc = task_desc;
}
public String getTask_comp_date() {
return task_comp_date;
}
public void setTask_comp_date(String task_comp_date) {
this.task_comp_date = task_comp_date;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getActivate() {
return activate;
}
public void setActivate(String activate) {
this.activate = activate;
}
}
My Data Accession Object named as TaskDao
#Dao
public interface TaskDao {
#Query("SELECT * FROM task")
List<Task> getAll();
#Insert
void insert(Task task);
#Delete
void delete(Task task);
#Update
void update(Task task);
}
My DataBase
#Database(entities = {Task.class},version = 1)
public abstract class AppDataBase extends RoomDatabase {
public abstract TaskDao taskDao();
}
My DataBaseClient named as DatabaseClient
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstace;
private AppDataBase appDataBase;
public DatabaseClient(Context context) {
this.context = context;
appDataBase = Room.databaseBuilder(context,AppDataBase.class,"MyDailyTask").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstace == null)
{
mInstace = new DatabaseClient(context);
}
return mInstace;
}
public AppDataBase getAppDataBase()
{
return appDataBase;
}
}
My RecyclerView Adapter
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.MyViewHolder> {
private Context context;
private List<Task> taskList;
public interface OnDeleteClickListener
{
void OnDeleteClickListener(Task task);
}
private OnDeleteClickListener onDeleteClickListener;
public TaskAdapter(Context context, List<Task> taskList) {
this.context = context;
this.taskList = taskList;
}
public void setOnDeleteClickListener(OnDeleteClickListener onDeleteClickListener) {
this.onDeleteClickListener = onDeleteClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(context).inflate(R.layout.view_task_list,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.setData(taskList.get(position).getTask_name(),taskList.get(position).getTask_desc(),taskList.get(position).getComment(),taskList.get(position).getTask_comp_date(),position);
}
#Override
public int getItemCount() {
return taskList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView t1,t2,t3,t4,t5;
private ImageView view;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
t1= itemView.findViewById(R.id.tvCommnt);
t2=itemView.findViewById(R.id.tvDesc);
t3=itemView.findViewById(R.id.tvName);
t4= itemView.findViewById(R.id.tvStart);
t5 = itemView.findViewById(R.id.tvEnd);
view =itemView.findViewById(R.id.tvdele);
}
public void setData(String t01, String t02, String t03, String t05, final int position)
{
t1.setText("Task Comment "+t03);
t2.setText("Task Description "+t02);
t3.setText("Task Name "+ t01);
t4.setText("Start ");
t5.setText("Ënd "+t05);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onDeleteClickListener!=null)
{
onDeleteClickListener.OnDeleteClickListener(taskList.get(position));
taskList.remove(position);
notifyDataSetChanged();
}
}
});
}
}
}
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.ivAdd);
recyclerView = findViewById(R.id.rvTask);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddTaskActivity.class));
}
});
new newTask().execute();
}
class newTask extends AsyncTask<Void,Void, List<Task>> implements TaskAdapter.OnDeleteClickListener {
List<Task> tasks;
#Override
protected List<Task> doInBackground(Void... voids) {
tasks = DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().getAll();
return tasks;
}
#Override
protected void onPostExecute(List<Task> tasks) {
super.onPostExecute(tasks);
TaskAdapter taskAdapter = new TaskAdapter(MainActivity.this,tasks);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(taskAdapter);
taskAdapter.setOnDeleteClickListener(this);
}
#Override
public void OnDeleteClickListener(final Task task) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().delete(task);
}
},1000);
}
}
welcome in stack
you interface is declared but not assign so your will throw null pointer when click on item inside your list, but good work your check null before fire method interface
first add setter for OnDeleteClickListener inside your adapter
public void setOnDeleteClickListener(OnDeleteClickListener listener){
this.onDeleteClickListener=listener;
}
and also add code that remove item from you list when user click item
so inside setData method update this code
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onDeleteClickListener != null) {
onDeleteClickListener.OnDeleteClickListener(taskList.get(position));
//remove item from list and then notify adapter data is changed
taskList.remove(position);
notifyDataSetChanged();
}
}
});
finally to Triggers onDeleteClickListener inside your AsyncTask
update your code here
#Override
protected void onPostExecute(List < Task > tasks) {
super.onPostExecute(tasks);
TaskAdapter taskAdapter = new TaskAdapter(MainActivity.this, tasks, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(taskAdapter);
//pass this that refer to my interface
taskAdapter.setOnDeleteClickListener(this);
}
inside your OnDelete just use this code to run in another thread
AsyncTask.execute(new Runnable() {
#Override
public void run() {
DatabaseClient.getInstance(getApplicationContext()).getAppDataBase().taskDao().delete(task);
}
});
Advice : Don't name your variable or arguments like String
t01,String t02..etc ,choice name for like what this variable jop
like String taskComment,String taskName ..etc
i hope this help you
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;
}
}
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
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) {
}});