Get selected item text from RecycleView when button clicked - android

I just want to create a list that will show currently selected item text when I click "Selanjutnya" button, but I don't know how to do that.
So when I click "Selanjutnya", it will show 22, 23. Currently, I use Big Nerd Ranch multi-select to make multi-selection work.
implementation 'com.bignerdranch.android:recyclerview-multiselect:+'
And here is my Codes.
Adapter
public class KetuaAbsenAdapter extends RecyclerView.Adapter<KetuaAbsenAdapter.ViewHolder> {
private List<KetuaAbsenList> listItems;
private Context context;
private MultiSelector mMultiSelector = new MultiSelector();
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
return new ViewHolder(v);
}
public KetuaAbsenAdapter(List<KetuaAbsenList> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final KetuaAbsenList listItem = listItems.get(position);
holder.textViewMuridno.setText(listItem.getMuridno());
holder.textViewMuridnama.setText(listItem.getMuridnama());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends SwappingHolder implements View.OnClickListener {
public TextView textViewMuridno;
public TextView textViewMuridnama;
public TextView textViewMuridkelas;
public LinearLayout list_item_linear;
public ViewHolder(View itemView) {
super(itemView, mMultiSelector);
textViewMuridno = (TextView) itemView.findViewById(R.id.muridno);
textViewMuridnama = (TextView) itemView.findViewById(R.id.muridnama);
textViewMuridkelas = (TextView) itemView.findViewById(R.id.muridkelas);
list_item_linear = (LinearLayout) itemView.findViewById(R.id.list_item_linear);
list_item_linear.setOnClickListener(this);
itemView.setOnClickListener(this);
mMultiSelector.setSelectable(true);
}
#Override
public void onClick(View v) {
if (mMultiSelector.tapSelection(this)) {
Toast.makeText(context, "terpilih", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "tidak terpilih", Toast.LENGTH_LONG).show();
}
}
}
}
List Class
public class KetuaDaftarAbsen extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<KetuaAbsenList> listItems;
EditText YangTidakHadir;
Button KetuaLanjut;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ketua_daftar_absen);
YangTidakHadir = (EditText)findViewById(R.id.YangTidakHadir);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-message"));
}
public void loadRecyclerViewData(){
final String url = "https://gameblong.com/raset/daftar_absen.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
String status = jsonObject.getString("status");
if(status.equals("sukses")){
JSONArray array = jsonObject.getJSONArray("semua");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
KetuaAbsenList item = new KetuaAbsenList(
o.getString("murid_no"),
o.getString("murid_nama"),
o.getString("murid_kelas")
);
listItems.add(item);
}
} else {
}
adapter = new KetuaAbsenAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String muno = intent.getStringExtra("muridnomor");
KetuaLanjut = (Button)findViewById(R.id.KetuaLanjut);
KetuaLanjut.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, muno, Toast.LENGTH_LONG).show();
}
});
}
};
}
I can use mMultiSelector.getSelectedPositions(); on my Adapter, but only this only gives current selected position (like 0, 1),

You can create an Interface that you add to your adapter and a listener for it.
public interface OnAdapterItemClicked {
// you can name it what ever you need add pass more parameters
void itemClicked(String text);
}
then in your adapter, you initialise it and add the listener on the click event,
private OnAdapterItemClicked mListener = null;
...
#Override
public void onBindViewHolder(#NonNull YourAdapter.ViewHolder holder,
int position) {
...
holder.YourBtn.setOnClickListener(....{
mListener.itemClicked("string you need to pass")
});
...
}
...
public void setOnItemClickListener(OnAdapterItemClicked listener) {
this.mListener = listener;
}
finally in you activity/fragment you add a listener on the recyclerview
rv.setOnItemClickListener(new OnAdapterItemClicked () {
#Override
public void itemClicked(String text) {
Log.d(TAG, "itemClicked: "+text);
}
});

In your adapter, you can add onClickListener like this
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your logic goes here
}
});
return new ViewHolder(v);
}

Related

How to dismiss PopupWindow containing recyclerview by clicking an item in the recyclerview

I have a PopupWindow which contains a RecyclerView filled with items. I want to dismiss the PopupWindow after selecting an item in the recycleview.
I know it has to be implemented with a interface, but not quite sure on how to do it in the code. Right now the items are displaying in the popupwindow and I could get the items printed in toast. It will be helpful if anybody could look to my code and guide me.
Activity.java
public class SetupActivity extends AppCompatActivity {
private ImageView imageVProfileSmall;
private RequestQueue requestQueue2;
private RecyclerView mallRecyclerView;
private MallAdapter mallRecyclerAdapter;
List<ModelMall> newMallModels = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
initViews();
EditText popupButton = findViewById(R.id.editTextMall);
popupButton.setInputType(InputType.TYPE_NULL);
popupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopup(v);
}
});
}
private void initViews() {
imageVProfileSmall = findViewById(R.id.profileImg);
}
private void GET_MALL_WEB_CALL() {
String HTTP_SERVER_URL = "http://GetMall";
JsonArrayRequest jsArrRequest = new JsonArrayRequest
(Request.Method.GET, HTTP_SERVER_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
GET_MALL_PARSE(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.i("ERROR", "Event Web call Error");
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Authorization", "Bearer " + getFromSP("etAt"));
return params;
}
};
jsArrRequest.setRetryPolicy(new DefaultRetryPolicy(
240000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
if (requestQueue2 == null) {
requestQueue2 = Volley.newRequestQueue(this);
requestQueue2.add(jsArrRequest);
} else {
requestQueue2.add(jsArrRequest);
}
}
public void clear() {
int size = newMallModels.size();
newMallModels.clear();
Log.i("LOL", String.valueOf(size));
}
public void GET_MALL_PARSE(JSONArray array) {
clear();
for (int i = 0; i < array.length(); i++) {
ModelMall GetMallDataModel = new ModelMall();
Log.i("SUCCESS", "Event web call success");
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetMallDataModel.setMallId(json.getString("$id"));//
GetMallDataModel.setMallName(json.getString("Resourcetype_en"));//
newMallModels.add(GetMallDataModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (array.length() != 0) {
String strArrayLen = String.valueOf(array.length());
mallRecyclerAdapter.updateModels(newMallModels);
}
}
public void showPopup(View view){
//Create a View object yourself through inflater
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(view.getContext().LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.layout_mall_recycler, null);
//Specify the length and width through constants
int width = LinearLayout.LayoutParams.MATCH_PARENT;
int height = LinearLayout.LayoutParams.MATCH_PARENT;
//Make Inactive Items Outside Of PopupWindow
boolean focusable = true;
//Create a window with our parameters
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
//Set the location of the window on the screen
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
//Initialize the elements of our window
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mallRecyclerView = popupView.findViewById(R.id.recyclerView);
mallRecyclerView.setLayoutManager(layoutManager);
mallRecyclerAdapter = new MallAdapter(this);
mallRecyclerView.setAdapter(mallRecyclerAdapter);
GET_MALL_WEB_CALL();
//Handler for clicking on the inactive zone of the window
popupView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//Close the window when clicked
popupWindow.dismiss();
return true;
}
});
}
private void saveInSp(String key, String value) {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
private String getFromSP(String key) {
SharedPreferences preferences = this.getSharedPreferences("PROJECT_NAME", Context.MODE_PRIVATE);
return preferences.getString(key, "");
}
#Override
protected void onResume() {
super.onResume();
}
}
Adapter.java
public class MallAdapter extends RecyclerView.Adapter<MallAdapter.ViewHolder> {
private Context context;
private final List<ModelMall> mallDataModels;
public MallAdapter(Context context) {
super();
this.context = context;
this.mallDataModels = new ArrayList<ModelMall>();
}
public void updateModels(List<ModelMall> newModels) {
mallDataModels.clear();
mallDataModels.addAll(newModels);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final ModelMall dataAdapter = mallDataModels.get(position);
viewHolder.tVMallName.setText(dataAdapter.getMallName());
saveInSp("SelectedMallName", String.valueOf(dataAdapter.getMallId()));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), dataAdapter.getMallName(), Toast.LENGTH_SHORT).show();
saveInSp("selectedMall", dataAdapter.getMallName());
}
});
}
#Override
public int getItemCount() {
return mallDataModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView tVMallName;
public ViewHolder(View itemView) {
super(itemView);
tVMallName = itemView.findViewById(R.id.textMallName);
}
}
}
Adapter
public class MallAdapter extends RecyclerView.Adapter<MallAdapter.ViewHolder> {
private Context context;
private final List<ModelMall> mallDataModels;
private PopupWindowCloseListener popupWindowCloseListener;
public MallAdapter(Context context,PopupWindowCloseListener popupWindowCloseListener) {
super();
this.context = context;
this.mallDataModels = new ArrayList<ModelMall>();
this.popupWindowCloseListener =popupWindowCloseListener
}
public void updateModels(List<ModelMall> newModels) {
mallDataModels.clear();
mallDataModels.addAll(newModels);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final ModelMall dataAdapter = mallDataModels.get(position);
viewHolder.tVMallName.setText(dataAdapter.getMallName());
saveInSp("SelectedMallName", String.valueOf(dataAdapter.getMallId()));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindowCloseListener.closeWindow();
Toast.makeText(v.getContext(), dataAdapter.getMallName(), Toast.LENGTH_SHORT).show();
saveInSp("selectedMall", dataAdapter.getMallName());
}
});
}
#Override
public int getItemCount() {
return mallDataModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView tVMallName;
public ViewHolder(View itemView) {
super(itemView);
tVMallName = itemView.findViewById(R.id.textMallName);
}
}
interface PopupWindowCloseListener{
void closeWindow();
}
}
class implements listener
public class SetupActivity extends AppCompatActivity implements PopupWindowCloseListener
make popupWindow as global variable
PopupWindow popupWindow ;
popupWindow= new PopupWindow(popupView, width, height, focusable)
set adapter
mallRecyclerAdapter = new MallAdapter(this, this)
override method close the popup
public void closeWindow() {
popupWindow.dismiss();
}

Why adnroidx recycler-view click not working when click it's item?

I'm trying to implement RecyclerView onclick listener, but it is not working. I've tried a lot, and try to implement other way too, but not working at all.
My Main Class:
public class MainMenuDashboard extends AppCompatActivity{
private RecyclerView recyclerMenu;
private RecyclerViewMenuAdapter menuAdapter;
private Call<CategoryModel> categoryModelCall;
private TokenManager tokenManagerMainMenu;
private ApiService serviceMainMenu;
List<CategoryModel.Subset> menuList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_dashboard);
tokenManagerMainMenu = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
serviceMainMenu = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManagerMainMenu);
recyclerMenu = findViewById(R.id.recyclerMenu);
menuList = new ArrayList<>();
GridLayoutManager layoutManager = new GridLayoutManager(MainMenuDashboard.this, 2, GridLayoutManager.VERTICAL, false);
recyclerMenu.setLayoutManager(layoutManager);
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
menuAdapter.notifyDataSetChanged();
mainMenuDashBoardToolbar = findViewById(R.id.mainMenuDashBoardToolbar);
setSupportActionBar(mainMenuDashBoardToolbar);
menuContent();
}
private void menuContent() {
categoryModelCall = serviceMainMenu.menuContent(incomingRoleId, true);
categoryModelCall.enqueue(new Callback<CategoryModel>() {
#Override
public void onResponse(#NotNull Call<CategoryModel> call, #NotNull Response<CategoryModel> response) {
if (response.isSuccessful() && response.body() != null && response.code() != 400) {
//findViewById(R.id.shimmerCategory).setVisibility(View.GONE);
CategoryModel categoryModel = response.body();
menuList = categoryModel.getSubset();
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
//menuAdapter.notifyDataSetChanged();
menuAdapter.setOnItemClickListener(new RecyclerViewMenuAdapter.ClickListenerMenu() {
#Override
public void onClick(int position) {
Toast.makeText(MainMenuDashboard.this, "Position "+position+" Clicked", Toast.LENGTH_SHORT).show();
menuAdapter.notifyDataSetChanged();
}
});
menuAdapter.notifyDataSetChanged();
}else {
if (response.code() == 401) {
Intent i = new Intent(MainMenuDashboard.this, MainActivity.class);
i.putExtra("USER_SESSION", true);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
tokenManagerMainMenu.deleteToken();
startActivity(i);
finish();
}
}
}
#Override
public void onFailure(#NotNull Call<CategoryModel> call, #NotNull Throwable t) {
}
});
}
}
My Adapter:
public class RecyclerViewMenuAdapter extends RecyclerView.Adapter<RecyclerViewMenuAdapter.RecyclerViewHolder> {
private static final String TAG = "NotesRecyclerAdapter";
private List<CategoryModel.Subset> subsetsCategories;
private ClickListenerMenu mClickListener;
private Context context;
public RecyclerViewMenuAdapter(List<CategoryModel.Subset> subsetsCategories) {
this.subsetsCategories = subsetsCategories;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_main_menu_category, parent, false);
return new RecyclerViewHolder(view, mClickListener);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewHolder viewHolder, final int position) {
String menuCategoryImage = subsetsCategories.get(position).getIcon();
Picasso.get().load(menuCategoryImage).placeholder(R.drawable.admin).into(viewHolder.menuThumb);
String menuCategoryName = subsetsCategories.get(position).getName();
viewHolder.menuName.setText(menuCategoryName);
//Item click
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
mClickListener.onClick(position);
//Toast.makeText(context, "Position "+position+" Clicked", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return subsetsCategories.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
ImageView menuThumb;
TextView menuName;
private ClickListenerMenu mListener;
//ClickListenerMenu clickListenerMenu;
public RecyclerViewHolder(View view, ClickListenerMenu clickListenerMenu) {
super(view);
menuThumb = view.findViewById(R.id.menuThumb);
menuName = view.findViewById(R.id.menuName);
mListener = clickListenerMenu;
}
}
public void setOnItemClickListener(ClickListenerMenu clickListener) {
mClickListener = clickListener;
}
public interface ClickListenerMenu {
void onClick(int position);
}
}
I still can't find where I did wrong!! Any insight will be very appreciated
Thank You
Add item click listener in your adapter.
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder viewHolder, int position) {
String menuCategoryImage = subsetsCategories.get(position).getIcon();
Picasso.get().load(menuCategoryImage).placeholder(R.drawable.admin).into(viewHolder.menuThumb);
String menuCategoryName = subsetsCategories.get(position).getName();
viewHolder.menuName.setText(menuCategoryName);
//Item click
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Do something
}
});
}
Initialise your recycler view outside and put this line menuAdapter.notifyDataSetChanged(); where you add data in your list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_dashboard);
tokenManagerMainMenu = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
serviceMainMenu = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManagerMainMenu);
recyclerMenu = findViewById(R.id.recyclerMenu);
menuList = new List<CategoryModel.Subset>();
GridLayoutManager layoutManager = new GridLayoutManager(MainMenuDashboard.this, 2, GridLayoutManager.VERTICAL, false);
recyclerMenu.setLayoutManager(layoutManager);
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
menuAdapter.notifyDataSetChanged();
menuContent();
}
I hope this can help you!
Add these line in the onBindViewHolder() method:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//remove this lines
//mClickListener.onClick(position);
//notifyDataSetChanged();
//add this
context.startActivity(new Intent(context,SecondActivity.class))
}
});
and in your MainMenuDashboard class, initialize your Adapter like this:
menuAdapter = new RecyclerViewMenuAdapter(this,menuList);
also change your Adapter constructor like this:
public RecyclerViewMenuAdapter(Context context,List<CategoryModel.Subset> subsetsCategories) {
this.subsetsCategories = subsetsCategories;
this.context = context;
}
```

android - recyclerview cannot click and get position

I have tried some code to can click recyclerview item and get position, but I can't click the recyclerview item.. the data I get from url. So I wan't switch activity with get the item user click..
how I can fix that?
this code for adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public NetworkImageView networkImageView;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item);
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1);
}
}
}
and this code for mainactivity
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://androidblog.esy.es/ImageJsonData.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
getdataadapter
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
}
You need to set onClickListener to your item view. You can do by following below steps:
Set onCLickListener to root view of your list item.
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
Add below code in onCreateViewHolder:
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
You can add listener while onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
Thanks.
Put a listener on your recycler item view and then in onclick, start intent to open new activity. Pass the data object you want to pass with the intent.
//make sure your model class GetDataAdapter implements Parcelable
holder.itemView.setOnclickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, ActivityToOpen.class);
intent.putExtra("key",Your Object to pass);// getDataAdapter1 in your case
context.startActivity(intent);
}
});
then in your Startted activity receive your object like this
YourObject obj = getIntent().getParcelableExtra("key");
//Your case
GetDataAdapter obj = getIntent().getParcelableExtra("key");

RecyclerView dosent show any elements following is my code

Fragment_bookmovie2.java
public class Fragment_bookmovie2 extends android.support.v4.app.Fragment implements View.OnClickListener {
private static final String TAG ="Fragment_bookmovie2" ;
ArrayList<String> moviename= new ArrayList<>();
ArrayList<String> movieyear= new ArrayList<>();
ArrayList<String> moviebanner= new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
Movie_listAdapter2 adapter ;
LinearLayout progress;
RelativeLayout ll;
public Fragment_bookmovie2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.e(TAG,"reched on create");
// first step - retrieve object
Backendless.Persistence.of(Booking.class).find(new AsyncCallback<BackendlessCollection<Booking>>() {
#Override
public void handleResponse(BackendlessCollection<Booking> response) {
for(Booking booking : response.getData()) {
if(!moviename.contains(booking.getMovie().get(0).getMovie_Name())) {
moviename.add(booking.getMovie().get(0).getMovie_Name());
movieyear.add(booking.getMovie().get(0).getYear());
moviebanner.add("https://api.backendless.com/" + BackendSetting.APPLICATION_ID + "/" + BackendSetting.VERSION + "/files/mypics/" + booking.getMovie().get(0).getImage());
}
}
adapter.notifyDataSetChanged();
ll.removeView(progress);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
moviename.add("haha");
movieyear.add("hello");
moviebanner.add("http://www.w3schools.com/css/trolltunga.jpg");
// Inflate the layout for this fragment
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_bookmovie2, container, false);
progress = (LinearLayout) ll.findViewById(R.id.progress_bookingFrag);
recyclerView = (RecyclerView) ll.findViewById(R.id.recycle_movielist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new Movie_listAdapter2(getActivity(),moviename,movieyear,moviebanner);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return ll;
}
#Override
public void onClick(View view) {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onButtonClickListnerProceed(Integer pos) {
Intent booking_screen_redirect = new Intent(getActivity(), BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(pos));
this.onPause();
startActivity(booking_screen_redirect);
getActivity().overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}*/
}
Movie_listAdapter2.java
public class Movie_listAdapter2 extends RecyclerView.Adapter<Movie_listAdapter2.Movie_cards>{
final static String TAG="Movie_listAdapter2";
Context context_external;
ArrayList<String> moviename=new ArrayList<>();
ArrayList<String> movieyear=new ArrayList<>();
ArrayList<String> banner=new ArrayList<>();
public Movie_listAdapter2(Context context,ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
//set the context and the format of the layout inside the list item
//i.e R.layout.movie_list_adapter
//also the resource i.e the item names in an ArrayList
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
this.context_external=context;
Log.e(TAG,"size = "+movieyear.size()+" "+moviename.size());
}
public static class Movie_cards extends RecyclerView.ViewHolder {
CardView cv;
TextView movie_name;
TextView movie_year;
Button proceed;
ImageView movie_banner;
public Movie_cards(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.movie_list_card);
movie_name = (TextView)itemView.findViewById(R.id.tv_card_moviename);
movie_year = (TextView)itemView.findViewById(R.id.tv_card_movieyear);
movie_banner = (ImageView)itemView.findViewById(R.id.card_moviebanner);
proceed = (Button) itemView.findViewById(R.id.b_card_proceed);
}
}
#Override
public Movie_cards onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_card, parent, false);
Movie_cards pvh = new Movie_cards(v);
return pvh;
}
public void updateData(ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final Movie_cards holder, final int position) {
holder.movie_name.setText(moviename.get(position));
holder.movie_year.setText(movieyear.get(position));
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.networkPolicy(NetworkPolicy.OFFLINE)
.error(R.drawable.placeholder)
.fit()
.into(holder.movie_banner, new Callback() {
#Override
public void onSuccess() {
//i.e image was loaded from cache
}
#Override
public void onError() {
//image was downloaded as it wasn't available in cache
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.warning)
.fit()
.into(holder.movie_banner);
}
});
holder.proceed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent booking_screen_redirect = new Intent(context_external, BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(position));
context_external.startActivity(booking_screen_redirect);
//overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
});
}
#Override
public int getItemCount() {
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
the fragment displays empty and no items appear even though i have added the data to arraylists and passed to the adapter. please help . thanks in advance
Problem is in below code you are returning 0 that's why its not showing any item
#Override
public int getItemCount() {
return 0;
}
You should return your list's size here either moviename.size(); or movieyear.size()

Android Recycler View

I am using RecyclerView to display my products, problem is when if I select the first products and scroll down to the end of list I see different products selected and when i scroll back to top of list the first item is not selected.
My Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
String u = "http://192.185.52.231/~sabby070/hyype/";
Context context1;
private java.util.List<ProductDetails> List;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, parent, false);
return new MyViewHolder(itemView);
}
public RecyclerAdapter(List<ProductDetails> DataList, FragmentActivity activity) {
this.List = DataList;
context1 = activity;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Likecount;
public ImageView Image;
public ImageView Imagelike, ImageUnlike;
public MyViewHolder(View view) {
super(view);
Likecount = (TextView) view.findViewById(R.id.textView_itemPrice);
Image = (ImageView) view.findViewById(R.id.imageView_imgtosold);
Imagelike = (ImageView)view.findViewById(R.id.Like_Button);
ImageUnlike = (ImageView)view.findViewById(R.id.UnLike_Button);
}
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder, final int position) {
final ProductDetails detail = List.get(position);
holder.Likecount.setText(detail.getLikeCount());
Glide.with(context1).load(u+detail.getImage()).override(600, 200).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.Image);
holder.Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context1, ""+position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context1, Buy_Product.class);
intent.putExtra("Product Name",detail.getLikeCount());
intent.putExtra("Product Image",detail.getImage());
context1.startActivity(intent);
}
});
holder.Imagelike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.Imagelike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.GONE);
holder.ImageUnlike.setVisibility(View.VISIBLE);
}
}
});
holder.ImageUnlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.ImageUnlike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.VISIBLE);
holder.ImageUnlike.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return List.size();
}
}
My class
public class Men_Fragment extends Fragment {
static String URL = "http://192.185.52.231/~sabby070/hyype/index.php?action=timeline&user_id=53&post_category=timeline";
private List<ProductDetails> DataList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerAdapter rAdapter;
String img;
String a;
Boolean list[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_men_, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.men_recycler_view);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
for (int i = 0; i < response.length(); i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
a = obj.getString("like_count");
img = obj.getString("video_thumb");
final ProductDetails details = new ProductDetails(a, img);
DataList.add(details);
rAdapter = new RecyclerAdapter(DataList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(rAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return view;
}
}
You have to take List(with boolean) and store selected values in that list and then use those values in onBindView()
In your ProductDetails class add a field boolean selected;
In your onClick() add List.get(position).setSelected(!List.get(position).isSelected()); to check/uncheck as needed.
Finaly in your onBindViewHolder(...) add
if(List.get(position).isSelected()){
holder.Imagelike.setVisibility(View.VISIBLE);
}else{
holder.ImageUnlike.setVisibility(View.GONE);
}

Categories

Resources