Pass data recycler adapter to other activity using Firebase - android

Image :
I am using Firebase for video status android application, and using recycler view but Firebase daat will not pass first activity to another (second) activity, how I can solve this problem (error)
error Model.videolink' on a null object reference.
App Adepter
public class App_Adepter extends RecyclerView.Adapter<App_Adepter.ViewHolder> {
Model model;
private Context context;
private ArrayList<Model> uploads;
private ProgressDialog pDialog;
private MediaController mediaController;
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public VideoView videoView;
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.rImageView);
videoView = (VideoView) itemView.findViewById(R.id.test_video);
textView = (TextView) itemView.findViewById(R.id.text11);
}
}
public App_Adepter(Context context, ArrayList<Model> uploads) {
this.uploads = uploads;
this.context = context;
}
#Override
public App_Adepter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row, parent, false);
return new App_Adepter.ViewHolder(v);
}
#Override
public void onBindViewHolder(final App_Adepter.ViewHolder holder, final int position) {
final Model upload = uploads.get(position);
/*Video Click*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Full_video.class);
intent.putExtra("posss", model.image);
intent.putParcelableArrayListExtra("Category", uploads);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
final MediaController mediaController = new MediaController(context);
String uriPath = upload.getImage(); //update package name
Uri uri = Uri.parse(uriPath);
holder.textView.setText(upload.getVideolink());
Glide.with(context).load(upload.getImage()).into(holder.imageView);
holder.videoView.setVideoURI(uri);
holder.videoView.start();
holder.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return true;
}
});
holder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
/**** Media control coding ****///
holder.videoView.setMediaController(mediaController);
mediaController.setAnchorView(holder.videoView);
mp.setVolume(0, 0);
}
});
}
});
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return uploads.size();
}
}
Model Class
String image;
String videolink;
public Model() {
}
public static Creator<Model> getCREATOR() {
return CREATOR;
}
public Model(String image,String videolink) {
this.videolink = videolink;
this.image = image;
}
protected Model(Parcel in) {
image = in.readString();
videolink = in.readString();
}
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];
}
};
public String getVideolink() {
return videolink;
}
public void setVideolink(String videolink) {
this.videolink = videolink;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(image);
dest.writeString(videolink);
}
Other (Second) Activity
Bundle extra = getIntent().getExtras();
String value = extra.getString("posss");
videoView.setVideoURI(Uri.parse(value));
First Activity
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
progressDialog.dismiss();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Model upload = postSnapshot.getValue(Model.class);
app_models.add(upload);
}
adapter = new App_Adepter(App_screen.this, app_models);
recyclerView.setAdapter(adapter);
if (app_models.size() <= 0) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.GONE);
}
}

Try this code..
make interface into adapter class for click handel..
onItemClick onItemClick;
public void setOnItemClick(adapterDemo.onItemClick onItemClick) {
this.onItemClick = onItemClick;
}
interface onItemClick{
void onClickData(Model data);
}
then onBindView method changes..
#Override
public void onBindViewHolder(#NonNull adapterDemo.ViewHolder viewHolder, int i) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onClickData(upload);
}
});
}
after that in activity define adapter and bind into recyclerview.. make sure your adapter object not null..
adapterDemo.setOnItemClick(new adapterDemo.onItemClick() {
#Override
public void onClickData(Model data) {
// here get click object data..
Intent intent = new Intent(context, Full_video.class);
intent.putExtra("posss", model.image);
intent.putParcelableArrayListExtra("Category", uploads);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});

Related

how to remove all items from RecyclerView on toolbar icon delete in android

Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}

How do I get the selected position in a RecyclerView when clicked from from an adapter?

I am working on an app and i want it to scroll to a particular position i clicked from an adapter into another activity like the Instagram way of checking the smaller picture in the profile fragment and scrolling to the exact position in the other activity, that is from smaller picture to big picture.
MyAdapterCode
public class DisplayDuetAdapter extends RecyclerView.Adapter<DisplayDuetAdapter.ImageViewHolder> {
private Context mContext;
private List<DisplayDuet> mDisplayDuet;
public int position;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public DisplayDuetAdapter(Context context, List<DisplayDuet> displayDuet){
mContext = context;
mDisplayDuet = displayDuet;
}
#NonNull
#Override
public DisplayDuetAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.duet_display_item, viewGroup, false);
return new DisplayDuetAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final DisplayDuetAdapter.ImageViewHolder imageViewHolder, int i) {
final DisplayDuet displayDuet = mDisplayDuet.get(i);
// Glide.with(mContext).load(displayDuet.getOriginalpics()).into(imageViewHolder.original_pic);
Picasso.get().load(displayDuet.getOriginalpics()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.placeholder).into(imageViewHolder.original_pic, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(displayDuet.getOriginalpics()).placeholder(R.drawable.placeholder).into(imageViewHolder.original_pic);
}
});
// Glide.with(mContext).load(displayDuet.getPostimage()).into(imageViewHolder.post_pic);
Picasso.get().load(displayDuet.getPostimage()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.placeholder).into(imageViewHolder.post_pic, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(displayDuet.getPostimage()).placeholder(R.drawable.placeholder).into(imageViewHolder.post_pic);
}
});
imageViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Intent intent = new Intent(mContext, DuetDisplayActivity.class);
intent.putExtra("postid", displayDuet.getPostid());
intent.putExtra("publisherid", displayDuet.getPublisher());
intent.putExtra("postduetid", displayDuet.getPostduetid());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mDisplayDuet.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView post_pic, original_pic;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
post_pic = itemView.findViewById(R.id.duet_pic_one);
original_pic = itemView.findViewById(R.id.duet_pic_two);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view, getAdapterPosition());
}
}
}
And the other activity code:
public class DuetDisplayActivity extends AppCompatActivity {
private String postid, publisher, postduetid;
private ImageView duet_close;
int position = 2;
private RecyclerView duet_show_recyclerView;
private DuetShowAdapter postAdapter;
private List<DisplayDuet> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duet_display);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisher = intent.getStringExtra("publisherid");
postduetid = intent.getStringExtra("postduetid");
duet_close = findViewById(R.id.close);
duet_show_recyclerView = findViewById(R.id.duet_show_recyclerView);
duet_show_recyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
duet_show_recyclerView.setLayoutManager(mLayoutManager);
postList = new ArrayList<>();
postAdapter = new DuetShowAdapter(this, postList);
duet_show_recyclerView.findViewHolderForAdapterPosition(position);
duet_show_recyclerView.setAdapter(postAdapter);
SnapHelper startSnapHelper = new PagerSnapHelper();
duet_show_recyclerView.setOnFlingListener(null);
startSnapHelper.attachToRecyclerView(duet_show_recyclerView);
duet_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
readPost();
}
private void readPost(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("DuetPics").child(postid);
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postList.clear();
for (DataSnapshot getsnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : getsnapshot.getChildren()) {
DisplayDuet displayDuet = snapshot.getValue(DisplayDuet.class);
postList.add(displayDuet);
}
Collections.reverse(postList);
postAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
What I understand from your question is that you want to pass the clicked position from your DisplayDuetAdapter to your DuetDisplayActivity.
If that is the case then you can pass it by the intent.
so pass the pressed item position in the DisplayDuetAdapter like this:
imageViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Intent intent = new Intent(mContext, DuetDisplayActivity.class);
//pass position like this
intent.putExtra("position", i);
intent.putExtra("postid", displayDuet.getPostid());
intent.putExtra("publisherid", displayDuet.getPublisher());
intent.putExtra("postduetid", displayDuet.getPostduetid());
mContext.startActivity(intent);
}
});
And get the position in the DuetDisplayActivity like this:
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duet_display);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisher = intent.getStringExtra("publisherid");
postduetid = intent.getStringExtra("postduetid");
//get the passed position
position = intent.getIntExtra("position");
............
............
update:
do this:
//get the passed position
position = intent.getIntExtra("position",0);

How to get data from firestore when click on recyclerView

I have already retrieved data from firestore to RecyclerView, then I need to click my recyclerView and show the data that i click to new Activity. How to get the data?
This is the code for Main Activity
List<FoodModel>models;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_home);
db = FirebaseFirestore.getInstance();
getData();
}
public void getData(){
models = new ArrayList<>();
db.collection("Food").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()){
for (DocumentSnapshot docSnap: documentSnapshots.getDocuments()) {
FoodModel model = docSnap.toObject(FoodModel.class);
models.add(model);
foodAdapter = new FoodAdapter(models, getApplicationContext(), new FoodAdapter.OnFoodClick() {
#Override
public void OnClick(FoodModel food) {
Intent intent = new Intent(MainActivity.this, FoodActivity.class);
startActivity(intent);
}
});
recyclerView.setAdapter(foodAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
This is the Adapter
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder>{
LayoutInflater inflater;
List<FoodModel> foodModels;
OnFoodClick listener;
Context context;
public FoodAdapter(List<FoodModel> foodModels, Context context, OnFoodClick listener) {
this.foodModels = foodModels;
this.context = context;
this.listener = listener;
inflater = LayoutInflater.from(context);
}
#Override
public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.view_holder_food, null, false);
FoodViewHolder holder = new FoodViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(FoodViewHolder holder, int position) {
FoodModel model = foodModels.get(position);
holder.tvName.setText(model.getName());
}
#Override
public int getItemCount() {
return foodModels.size();
}
public void addItem(FoodModel food){
foodModels.add(food);
notifyDataSetChanged();
}
public class FoodViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
public FoodViewHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition();
listener.OnClick(foodModels.get(position));
}
});
}
}
public interface OnFoodClick{
public void OnClick(FoodModel food);
}
}
This is my second Activity. i want to show name, type and price from Firestore. when i click the recycler view, the data not show in the activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
firedb = FirebaseFirestore.getInstance();
tvName = findViewById(R.id.tv_food_name);
tvType = findViewById(R.id.tv_type);
tvPrice = findViewById(R.id.tv_price);
getFoodData();
}
private void getFoodData(){
firedb.collection("Food").document().get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()){
loadData(documentSnapshot.toObject(FoodModel.class));
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
private void loadData(FoodModel foodModel){
tvName.setText(foodModel.getFoodName());
tvType.setText(foodModel.getType());
tvPrice.setText(foodModel.getPrice());
}
}
This is the foodModel
public class FoodModel {
String foodName;
String type;
String price;
public FoodModel() {
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
make an interface to handle recycler view click event like this ..
define below code into adapter.
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
String data=mStringList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
then after in activity adapter bind into recycler view then call this method to get your click item on recycler view ..
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
Log.d("Click Value",str);
}
});

How to take textview data from recycler view to another activity?

I want to take textview data from recycler view to another activity.I want to take
workshop_name TextView to Otheractivity.
Here is my code.
MechSearchActivity.java
public class MechSearchActivity extends AppCompatActivity {
List<SearchResponse.WorkshopDataBean> workshopList;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_mec);
recyclerView = (RecyclerView) findViewById(R.id.rv_workshoplist);
callSearchApi();
onItemClick();
}
public void callSearchApi() {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SearchResponse> call = apiService.getSearchData( "workshop_name","image", "street", "locality", "city"); // single search for all the values
call.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, retrofit2.Response<SearchResponse> response) {
SearchResponse searchResponse = response.body();
workshopList = searchResponse.getWorkshopData();
MechanicRecyclerAdapter adapter = new MechanicRecyclerAdapter(MechSearchActivity.this, workshopList);
recyclerView.setAdapter(adapter);
LinearLayoutManager mGridLayoutManager = new LinearLayoutManager(MechSearchActivity.this); // (Context context, int spanCount)
recyclerView.setLayoutManager(mGridLayoutManager);
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private void onItemClick() {
final GestureDetector mGestureDetector = new GestureDetector(MechSearchActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
recyclerView_ws.addOnItemTouchListener(new
RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildPosition(child);
String workshop_name = workshopList.get(position).getWorkshop_name();
Intent intent = new Intent(MechSearchActivity.this, OtherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("workshop_name", workshop_name);
startActivity(intent);
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
}
MechRecyclerAdapter.java
public class MechanicRecyclerAdapter extends RecyclerView.Adapter<MechanicRecyclerAdapter.MyViewHolder> {
private static final String TAG = MechanicRecyclerAdapter.class.getSimpleName();
Context mContext;
private LayoutInflater inflater;
String vehicle_type;
List<SearchResponse.WorkshopDataBean> workshopList;
public MechanicRecyclerAdapter(Context context, List<SearchResponse.WorkshopDataBean> workshopList) {
inflater = LayoutInflater.from(context);
this.workshopList = workshopList;
mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_workshop, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SearchResponse.WorkshopDataBean current = workshopList.get(position);
String ws_name = workshopList.get(position).getWorkshop_name();
holder.tv_workshopname.setText(ws_name);
}
#Override
public int getItemCount() {
return workshopList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
SearchResponse.WorkshopDataBean current;
TextView tv_workshopname;
public MyViewHolder(View itemView) {
super(itemView);
tv_workshopname = (TextView) itemView.findViewById(workshop_name);
}
}
}
OtherActivity.java
public class OtherActivity extends AppCompatActivity {
TextView SingleWorkshopName;
String workshop_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otheractivity);
SingleWorkshopName=(TextView)findViewById(R.id.single_workshop_name);
Bundle extras = getIntent().getExtras();
workshop_name = extras.getString("workshop_name", null);
}
}
For that you need to create one interface in your MechanicRecyclerAdapter
public interface OnListItemClick {
void onItemClick(int position);
}
in onBindViewHolder() assign your click by using following code
viewHolder.main_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onListItemClick.onItemClick(position);
}
});
Implements this interface in you MechSearchActivity you will get onItemClick() method in your activity using position you will get proper name of row and pass to other activity using intent.putExtra("workshop_name", workshop_name);

RecyclerView Android Json

How do i set data in RecylerView using Retrofit.I have tried but i was not able to performed it successfully.
Here is my code:
JSON DATA is :
{
"model": [
{
"id": "1",
"brand_name": "Audi",
"brand_logo": "1495456122.",
},
{
"id": "3",
"brand_name": "BMW",
"brand_logo": "1495451144.",
}
]
}
BrandSelectActivity.java
public class BrandSelectActivity extends AppCompatActivity implements View.OnClickListener {
ProgressDialog pDialog;
Button btn_addVehicle;
BrandListRecyclerAdapter adapter;
RecyclerView recyclerView_brand;
public ImageView carBrandImg;
public TextView carBrandName;
private static String TAG = BrandSelectActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand_select);
carBrandImg = (ImageView)findViewById(R.id.carBrandImg);
carBrandName = (TextView)findViewById(R.id.carBrandName);
recyclerView_brand = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setCancelable(true);
pDialog.setMessage("Please Wait...");
pDialog.show();
ArrayList<BrandModel> brandModelArrayList = new ArrayList<BrandModel>();
BrandListRecyclerAdapter brandAdapter = new BrandListRecyclerAdapter(BrandSelectActivity.this, brandModelArrayList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView_brand.setLayoutManager(mLayoutManager);
recyclerView_brand.setAdapter(brandAdapter);
brandAdapter.setItemClickListener(new BrandListRecyclerAdapter.MyClickListerer() {
#Override
public void onItemClick(int position, View view) {
Intent sosIntent = new Intent(BrandSelectActivity.this, ModelSelectActivity.class);
startActivity(sosIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
callBrandSelect();
}
private void callBrandSelect() {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<BrandSelectResponse> call = apiService.saveBrand("1");
call.enqueue(new Callback<BrandSelectResponse>() {
#Override
public void onResponse(Call<BrandSelectResponse> call, retrofit2.Response<BrandSelectResponse> response) {
BrandSelectResponse br= response.body();
List<BrandSelectResponse.ModelBean> modelList = br.getModel();
modelList.size();
modelList.get(0).getBrand_logo();
modelList.get(0).getBrand_name();
pb.dismiss();
}
#Override
public void onFailure(Call<BrandSelectResponse>call, Throwable t) {
Toast.makeText(BrandSelectActivity.this,"Opps ..!!Failed to
connect to our server.. Try Again later..",Toast.LENGTH_SHORT).show();
Log.e(TAG, t.toString());
}
});
}
#Override
public void onClick(View v) {
}
}
BrandListRecyclerAdapter.java
public class BrandListRecyclerAdapter extends RecyclerView.Adapter<BrandListRecyclerAdapter.MyViewHolder> {
Context mcontext;
List<BrandSelectResponse> brandModelArrayList;
public LayoutInflater inflater;
public static MyClickListerer myClickListerer;
public BrandListRecyclerAdapter(Context context, ArrayList<BrandSelectResponse> brandModelArrayList) {
this.mcontext = context;
this.brandModelArrayList=brandModelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_brand, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
BrandSelectResponse current = brandModelArrayList.get(position);
holder.setData((BrandSelectResponse) brandModelArrayList,position);
holder.carBrandName.setText(current.getBrand_name());
holder.carBrandImg.setImageResource(current.getBrand_logo());
}
public interface MyClickListerer {
void onItemClick(int position, View view);
}
public void setItemClickListener(MyClickListerer myClickListerer) {
this.myClickListerer = myClickListerer;
}
#Override
public int getItemCount() {
return brandModelArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView carBrandImg;
public TextView carBrandName;
BrandSelectResponse brandModelArrayList;
LinearLayout current;
int position;
public MyViewHolder(View itemView) {
super(itemView);
carBrandImg = (ImageView) itemView.findViewById(R.id.carBrandImg);
carBrandName = (TextView) itemView.findViewById(R.id.carBrandName);
}
public void setData(BrandSelectResponse current, int position) {
carBrandName.setText(brandModelArrayList.getBrand_name());
carBrandImg.setImageResource(brandModelArrayList.getBrand_logo());
this.position = position;
this.brandModelArrayList = current;
}
#Override
public void onClick(View v) {
myClickListerer.onItemClick(getAdapterPosition(), v);
}
}
}
BrandSelectResponse.java
public class BrandSelectResponse implements Serializable{
private List<ModelBean> model;
public BrandSelectResponse(List<ModelBean> model) {
this.model = model;
}
public List<ModelBean> getModel() {
return model;
}
public void setModel(List<ModelBean> model) {
this.model = model;
}
public static class ModelBean {
private String id;
private String brand_name;
private String brand_logo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_logo() {
return brand_logo;
}
public void setBrand_logo(String brand_logo) {
this.brand_logo = brand_logo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
You give to adapter EMPTY list.
You never add data to brandModelArrayList.
Next time try to look at the logcat, what is the exception and which line is the problem.

Categories

Resources