RecyclerView OnClick to take to another Fragment - java

I am stuck with this error for a long time now, I am new to JAVA.
I want to click an item on the RecyclerView (currently on a fragment) that got populated from Firebase. Once I click on it, it should take me to the next fragment by parcing some data and also the position of the item.
Here is my adapter, CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
public CustomAdapter(ArrayList<Userpost> data) {
this.data = data;
}
public interface OnItemClickListener{
void onItemClick(Userpost userpost, int activityNumber);
}
private ArrayList<Userpost> data;
private static final int ACTIVITY_NUM = 4;
private OnItemClickListener listener;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textViewName;
TextView textViewVersion;
SquareImageView imageView;
private final Context context;
public View mCardView;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.imageView = (SquareImageView) itemView.findViewById(R.id.imageView);
this.mCardView = itemView.findViewById(R.id.card_view);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "Position is " +getAdapterPosition(),Toast.LENGTH_SHORT).show();
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
Log.d(TAG, "MyViewHolder: setting up adapter for profile fragment");
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(itemView);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int Position) {
Log.d(TAG, "onBindViewHolder: setting up adapter for profile fragment");
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
final ImageView imageView = holder.imageView;
textViewName.setText(data.get(Position).getPheading());
textViewVersion.setText(data.get(Position).getDescriptionpost());
Picasso.with(holder.imageView.getContext()).load(data.get(Position).getImage_path()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Recycle Click" + Position, Toast.LENGTH_SHORT).show();
listener.onItemClick(data.get(Position), ACTIVITY_NUM);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
Here's fragment, ProfileFragment.java
public class ProfileFragment extends Fragment {
private static final String TAG = "ProfileFragment";
private static final int ACTIVITY_NUM = 4;
//firebase stuff
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
// Recycler View Widgets
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<Userpost> data;
private static ArrayList<Integer> removedItems;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
gridView = (GridView) view.findViewById(R.id.gridView);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
cardView = (CardView) view.findViewById(R.id.card_view);
toolbar = (Toolbar) view.findViewById(R.id.profileToolBar);
bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
mFirebaseMethods = new FirebaseMethods(getActivity());
//Recycler View class
super.onCreate(savedInstanceState);
data = new ArrayList<Userpost>();
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
updateArrayList();
private void updateArrayList() {
Log.d(TAG, "updateArrayList: setting up for profile fragment");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_posts))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded: explore fragment");
data.add(dataSnapshot.getValue(Userpost.class));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Userpost model = dataSnapshot.getValue(Userpost.class);
final int index = getItemIndex(model);
data.set(index, model);
adapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private int getItemIndex(Userpost user) {
Log.d(TAG, "getItemIndex: setting up for profile fragment");
int index = -1;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).image_path.equals(user.image_path)) {
index = i;
break;
}
}
return index;
}
Userpost.java is the model here.
And here is the logcat:
java.lang.NullPointerException: Attempt to invoke interface method 'void sahhaj.com.myapp.CustomAdapter$OnItemClickListener.onItemClick(myap.com.myapp.models.Userpost, int)' on a null object reference
at sahhaj.com.sahhajapp.CustomAdapter$1.onClick(CustomAdapter.java:112)
at android.view.View.performClick(View.java:5721)
at android.view.View$PerformClick.run(View.java:22620)

Your OnItemClickListener listener attribute is never set, so it is Null.
Check where you initialize it, if ever.

Change your RecyclerView array adapter class constructor like below.
public CustomAdapter(ArrayList<Userpost> data, OnItemClickListener listener) {
this.data = data;
this.listener = listener;
}
And in your Fragment change the RecyclerView array adapter object initializing like below.
adapter = new CustomAdapter(data, new CustomAdapter.OnItemClickListener() {
#Override
public void onItemClick(Userpost userpost, int activityNumber) {
// do whatever you want to do
}
});
And that's it. Now run the code you'll get your desired output.

**Call in Get Api **
implementation "com.android.support:cardview-v7:28.0.0"
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
<uses-permission android:name="android.permission.INTERNET" />
android:usesCleartextTraffic="true"
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/customRecyclerView"
android:layout_height="match_parent"
/>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/coverImage"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="#+id/title"
android:textSize="15dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
public interface ApiInterface
{
#GET("/photos")
Call<List<RetroPhoto>> getAllPhotos();
}
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestApiClient {
private static Retrofit retrofit;
private static final String BASE_URL = "https://jsonplaceholder.typicode.com";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class RetroPhoto {
#SerializedName("albumId")
private Integer albumId;
#SerializedName("id")
private Integer id;
#SerializedName("title")
private String title;
#SerializedName("url")
private String url;
#SerializedName("thumbnailUrl")
private String thumbnailUrl;
public RetroPhoto(Integer albumId, Integer id, String title, String url, String thumbnailUrl) {
this.albumId = albumId;
this.id = id;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
public Integer getAlbumId() {
return albumId;
}
public void setAlbumId(Integer albumId) {
this.albumId = albumId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
private CustomAdapter adapter;
private RecyclerView recyclerView;
ProgressDialog progressDoalog;
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMessage("Loading....");
progressDoalog.show();
/*Create handle for the RetrofitInstance interface*/
ApiInterface service = RestApiClient.getRetrofitInstance().create(ApiInterface.class);
Call<List<RetroPhoto>> call = service.getAllPhotos();
call.enqueue(new Callback<List<RetroPhoto>>() {
#Override
public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
progressDoalog.dismiss();
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<RetroPhoto> photoList) {
recyclerView = findViewById(R.id.customRecyclerView);
adapter = new CustomAdapter(this, photoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
private List<RetroPhoto> dataList;
private Context context;
public CustomAdapter(Context context,List<RetroPhoto> dataList){
this.context = context;
this.dataList = dataList;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
public final View mView;
TextView txtTitle;
private ImageView coverImage;
CustomViewHolder(View itemView) {
super(itemView);
mView = itemView;
txtTitle = mView.findViewById(R.id.title);
coverImage = mView.findViewById(R.id.coverImage);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.custom_row, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.txtTitle.setText(dataList.get(position).getTitle());
Picasso.get().load(dataList.get(position).getThumbnailUrl()).into(holder.coverImage);
// Picasso.Builder builder = new Picasso.Builder(context);
// builder.downloader(new OkHttp3Downloader(context));
// builder.build().load(dataList.get(position).getThumbnailUrl())
// .placeholder((R.drawable.ic_launcher_background))
// .error(R.drawable.ic_launcher_background)
// .into(holder.coverImage);
}
#Override
public int getItemCount() {
return dataList.size();
}
}

Related

recyclerView missing error in Android Studio

I'm a beginner programmer and I'm trying to receive data from the server using node.js and display the list on Android Studio but I keep having the following error:
E/RecyclerView: No adapter attached; skipping layout
D/HistoryActivity: HistoryResponse{result=[com.sooryong.loginexample.data.HistoryData#3303f3c, com.sooryong.loginexample.data.HistoryData#33764c5]}
D/AndroidRuntime: Shutting down VM
As you can see, I can't recall my list properly as well and I don't know how to fix it. Here are my codes:
public interface ServiceApi {
#POST("/user/login")
Call<LoginResponse> userLogin(#Body LoginData data);
#POST("/user/join")
Call<JoinResponse> userJoin(#Body JoinData data);
#GET("/test/history")
Call<HistoryResponse> getData();
}
HistoryData.java
public class HistoryData {
#SerializedName("eventID")
private int eventID;
#SerializedName("eventType")
private String eventType;
#SerializedName("eventDate")
private String eventDate;
#SerializedName("userID")
private int userID;
#SerializedName("sensorID")
private String sensorID;
public HistoryData(int eventID, String eventType, String eventDate, int userID, String sensorID) {
super();
this.eventID = eventID;
this.eventType = eventType;
this.eventDate = eventDate;
this.userID = userID;
this.sensorID = sensorID;
}
public int getEventID() {
return eventID;
}
public String getEventType() {
return eventType;
}
public String getEventDate() { return eventDate; }
public int getUserID() {
return userID;
}
public String getSensorID() { return sensorID; }
}
HistoryResponse.java
public class HistoryResponse {
#SerializedName("code")
public String code;
#SerializedName("message")
public String message;
#SerializedName("result")
public List<HistoryData> result;
#Override
public String toString() {
return "HistoryResponse{" + "result=" + result +'}';
}
}
HistoryActivity.java
public class HistoryActivity extends AppCompatActivity {
HistoryResponse dataList;
List<HistoryData> dataInfo;
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
dataInfo = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
ServiceApi apiInterface = RetrofitClient.getClient().create(ServiceApi.class);
Call<HistoryResponse> call = apiInterface.getData();
call.enqueue(new Callback<HistoryResponse>() {
#Override
public void onResponse(Call<HistoryResponse> call, Response<HistoryResponse> response) {
dataList = response.body();
Log.d("Response", dataList.toString());
dataInfo = dataList.result;
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), dataInfo);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public void onFailure(Call<HistoryResponse> call, Throwable t) {
Log.d("Response", t.getMessage());
}
});
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{
private Context c;
private List<HistoryData> dataList;
public RecyclerAdapter(Context c, List<HistoryData> dataList) {
this.c = c;
this.dataList = dataList;
}
#NonNull
#Override
public RecyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(c).inflate(R.layout.recycler_view, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.MyViewHolder holder, int position) {
holder.id.setText(dataList.get(position).getSensorID());
holder.type.setText("" + dataList.get(position).getEventType());
holder.date.setText("" + dataList.get(position).getEventDate());
}
#Override
public int getItemCount() {
return (dataList == null) ? 0 : dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView type;
TextView date;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id = (TextView)itemView.findViewById(R.id.sensorID);
type = (TextView)itemView.findViewById(R.id.eventType);
date = (TextView)itemView.findViewById(R.id.eventDate);
}
}
}
I don't think the data is being initialized properly inside the RecyclerAdapter class. Is it because I couldn't load the data properly from the server?
I ever face the same issue similiar to this.
What I've done was: initialize the adapter once only the activity created:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view);
dataInfo = new ArrayList<>();
initAdapter();
....
}
private void initAdapter() {
//The adapter should create once in onCreate
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext, LinearLayoutManager.VERTICAL, false);
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), dataInfo);
recyclerView.setAdapter(recyclerAdapter);
}
Then when in callback result: you can clear the previous data before reload to the adapter:
call.enqueue(new Callback<HistoryResponse>() {
#Override
public void onResponse(Call<HistoryResponse> call, Response<HistoryResponse> response) {
dataList = response.body();
dataInfo.clear(); // <- here we clear all previous data before reload result to the adapter.
dataInfo = dataList.result;
recyclerAdapter.notifyDataSetChanged()
#Override
public void onFailure(Call<HistoryResponse> call, Throwable t) {
Log.d("Response", t.getMessage());
}
});
Hope this help.

Having problem to fetching file from firestore recycle view [duplicate]

This question already has an answer here:
Firebase Android ListView not being displayed
(1 answer)
Closed 1 year ago.
I am an android developer beginner, I am having a problem fetch files from firestore recycle view in the main activity but I can fetch files from fragments.
This is my main activity
public class FoodInfoActivity extends AppCompatActivity {
RecyclerView recyclerView1,recyclerView2;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef;
private NoteAdapter adapter;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_info);
fAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
}
private void setUpRecyclerView() {
notebookRef = db.collection("FoodInside");
Query query = notebookRef;
FirestoreRecyclerOptions<FoodAdapter> options = new FirestoreRecyclerOptions.Builder<FoodAdapter>()
.setQuery(query, FoodAdapter.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.fi);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
This is my Note adapter where i use model class to fetch file
public class NoteAdapter extends FirestoreRecyclerAdapter<FoodAdapter, NoteAdapter.NoteHolder> {
public NoteAdapter(#NonNull FirestoreRecyclerOptions<FoodAdapter> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull FoodAdapter foodAdapter) {
holder.textViewTitle.setText(foodAdapter.getRestaurant());
holder.textViewDescription.setText(foodAdapter.getItem());
holder.textViewPriority.setText(String.valueOf(foodAdapter.getPrice()));
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_recycle_layout,
parent, false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textView95a);
textViewDescription = itemView.findViewById(R.id.textView123a);
textViewPriority = itemView.findViewById(R.id.textView124a);
}
}
}
This is my adapter class ,
public class FoodAdapter {
String Restaurant;
String Item;
String Price;
String item_id;
public FoodAdapter() {
}
public FoodAdapter(String restaurant, String item, String price,String item_id) {
Restaurant = restaurant;
Item = item;
Price = price;
this.item_id = item_id;
}
public String getRestaurant() {
return Restaurant;
}
public void setRestaurant(String restaurant) {
Restaurant = restaurant;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
}
Why it is not working in main activity but work fragment. I am just afraid. and tired...working on the project. so need solution of this problem
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Add this line to main activity.

How can I hide an ImageView on my RecyclerView for certain items based on a particular condition?

I have a RecyclerView with an ImageView being a part of the items. I want to hide the ImageView from an item in the RecyclerView if a certain condition is met. How can I do that? I am attaching the image of how I want it to look like.
I am just defining the ImageViews in my xml layout file, so I cannot figure out how to actually remove it based on a certain condition in my android activity. I am attaching the code for the adapter class and my activity as well.
Here is the code for my adapter class
Adapter Class
public class ReportAdapter extends RecyclerView.Adapter<ReportAdapter.ReportViewHolder> {
private ArrayList<ReportItem> reportlist;
private OnItemClickListener mListener;
private Context mContext;
public ReportAdapter(ArrayList<ReportItem> reportlist, Context context) {
this.reportlist = reportlist;
this.mContext = context;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ReportViewHolder extends RecyclerView.ViewHolder {
public TextView departureDate;
public TextView flightNumber;
public View relativelayout;
public ReportViewHolder(#NonNull View itemView, OnItemClickListener listener, Context context) {
super(itemView);
departureDate = itemView.findViewById(R.id.departureDaterecyclerview);
flightNumber = itemView.findViewById(R.id.flightnumberrecyclerview);
relativelayout = itemView.findViewById(R.id.relativeLayoutReports);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
#NonNull
#Override
public ReportViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.report_listing_item, parent, false);
ReportViewHolder rvh= new ReportViewHolder(v,mListener,mContext);
return rvh;
}
#SuppressLint("ResourceAsColor")
#Override
public void onBindViewHolder(#NonNull ReportViewHolder holder, int position) {
ReportItem currentItem = reportlist.get(position);
if(position%2==0){
holder.relativelayout.setBackgroundColor(mContext.getResources().getColor(R.color.reportlistingteal));
} else {
holder.relativelayout.setBackgroundColor(mContext.getResources().getColor(R.color.reportlistinglightteal));
}
holder.departureDate.setText((currentItem.getDepartureDate()));
holder.flightNumber.setText(currentItem.getFlightNumber());
}
Here is the code for my activity file
Activity file
public class ReportListingActivity extends AppCompatActivity {
private Button uploadAllBtn;
private EditText searchFlights;
private RecyclerView mRecyclerView;
private ReportAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
ArrayList<ReportItem> reportitems = new ArrayList<>();
private FlightViewModel flightViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_listing);
uploadAllBtn = findViewById(R.id.uploadAllReports);
searchFlights = findViewById(R.id.searchFlightText);
mRecyclerView = findViewById(R.id.recyclerView);
flightViewModel = new ViewModelProvider(this).get(FlightViewModel.class);
flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
#Override
public void onChanged(List<Flight> flight_list) {
if (flight_list.size() == 0) return;
String flightno = flight_list.get(0).getFlightNumber();
String flightdate = flight_list.get(0).getDate();
String[] flight_details = new String[2];
flight_details[0]= flightno;
flight_details[1] = flightdate;
Log.v("pp", flight_details[0]);
for(int i = 0; i <flight_list.size();i++){
String flightnumber = flight_list.get(i).getFlightNumber();
String departuredate = flight_list.get(i).getDate();
reportitems.add(new ReportItem(flightnumber,departuredate));
}
mRecyclerView.getAdapter().notifyDataSetChanged();
flightViewModel.getAllFlights().removeObservers(ReportListingActivity.this);
}
});
mLayoutManager = new LinearLayoutManager(ReportListingActivity.this);
mAdapter = new ReportAdapter(reportitems, ReportListingActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
Report Item
public class ReportItem {
private String departureDate;
private String flightNumber;
public ReportItem(String departureDate, String flightNumber) {
this.departureDate = departureDate;
this.flightNumber = flightNumber;
}
public String getDepartureDate() {
return departureDate;
}
public String getFlightNumber() {
return flightNumber;
}
}
Add a boolean flag to your ReportItem class for each RecyclerView item. You will need to specify which rows show or hide this field when each item is created:
public class ReportItem {
private String departureDate;
private String flightNumber;
private Boolean showMailIcon;
public ReportItem(String departureDate, String flightNumber, Boolean showMailIcon) {
this.departureDate = departureDate;
this.flightNumber = flightNumber;
this.showMailIcon = showMailIcon
}
public String getDepartureDate() {
return departureDate;
}
public String getFlightNumber() {
return flightNumber;
}
public String getShowMailIcon() {
return showMailIcon;
}
}
Then update the onBindViewHolder() method override to use this flag to show/hide the ImageView:
#Override
public void onBindViewHolder(#NonNull ReportViewHolder holder, int position) {
ReportItem currentItem = reportlist.get(position);
if (currentItem.getShowMailIcon() == true) {
holder.mailIcon.setVisibility(View.VISIBLE);
} else {
holder.mailIcon.setVisibility(View.GONE);
}
//.......
}

How to implement onClick in FirestoreRecyclerAdapter to open a new Fragment?

I am trying to implement OnClick in my recyclerview,but i failed miserably with all the searches how to solve this problem.
I want by clicking on my cardview to go to another activity/even better fragment with another expandable lists,but i can't even do this for now.
Any help is highly appreciated
MainActivity code
package com.oleg.firestoretest;
public static final String TAG = "FireLog";
private CollectionReference noteBookRef;
private FirebaseFirestore mFirestore;
private NoteAdapter adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirestore = FirebaseFirestore.getInstance();
noteBookRef = mFirestore.collection("Notebook");
setupRecyclerView();
}
private void setupRecyclerView() {
Query query = noteBookRef.orderBy("priority", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query,Note.class)
.build();
adapter = new NoteAdapter(options);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
public Note() {
}
public Note(String title, String content, int priority) {
this.title = title;
this.content = content;
this.priority = priority;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
public int getPriority() {
return priority;
}
}
public class NoteAdapter extends FirestoreRecyclerAdapter<Note, NoteAdapter.NoteHolder> {
private Context mContext;
public NoteAdapter(#NonNull FirestoreRecyclerOptions<Note> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder noteHolder, int i, #NonNull Note note) {
noteHolder.title.setText(note.getTitle());
noteHolder.content.setText(note.getContent());
noteHolder.priority.setText(String.valueOf(note.getPriority()));
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item,
parent, false);
return new NoteHolder(v);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView title;
TextView content;
TextView priority;
public NoteHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_text);
content = itemView.findViewById(R.id.content_text);
priority = itemView.findViewById(R.id.priority_text);
}
}
}
Here the Code u need:
class NoteHolder extends RecyclerView.ViewHolder {
TextView title;
TextView content;
TextView priority;
CardView cardView;
public NoteHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_text);
content = itemView.findViewById(R.id.content_text);
priority = itemView.findViewById(R.id.priority_text);
cardView = itemView.findViewById(R.id.cardView);
}
private void bind(){
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, SecoundActivity.class);
startActivity(intent);
}
});
}
}
Fixed it with this code!!!
public NoteHolder(#NonNull final View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);
title = itemView.findViewById(R.id.title_text);
content = itemView.findViewById(R.id.content_text);
priority = itemView.findViewById(R.id.priority_text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemView.getContext().startActivity(new Intent(itemView.getContext(),Empty.class));
}
});
}

how to set a path param using retrofit

how to get ID position in call retrofit
GET https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key=<>
i need to get position id send to server in loadCast function
and in MovieService that's retrofit call i need send postion id befor credits
i don't know how to do that if any one can help me thanks so much for that <3
//this my call retrofit server
public interface MovieService {
#GET("popular?" + Common.API_KEY + "&language=en-US")
Call<MoviesList> getPopular(#Query("api_key") String api_key);
#GET( ListMovieAdapter.SELECTED_MOVIE +"/credits?" + Common.API_KEY +
"&language=en-US")
Call<MovieCast> getCast(
#Query("api_key") String api_key);
----------------------------------------------------------------
package com.example.android.movie;
/**
* Created by yuyu on 12-Nov-18.
*/
public class MovieDetails extends YouTubeBaseActivity {
Result selectedMovie;
private ArrayList<Cast> cast;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView mRecyclerView;
private CastMovieAdapter castMovieAdapter;
private TextView name;
private ImageView imageMovie;
private TextView date;
private TextView rating;
private ArrayList<Result> results;
MovieService mService;
private static final String YT_API_KEY = "###";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_details);
selectedMovie =
getIntent().getParcelableExtra(ListMovieAdapter.SELECTED_MOVIE);
mRecyclerView = (RecyclerView) findViewById(R.id.cast_recycler);
mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
cast = new ArrayList<>();
castMovieAdapter = new CastMovieAdapter(cast, MovieDetails.this);
mRecyclerView.setAdapter(castMovieAdapter);
results = new ArrayList<>();
mService = Common.getMovieService();
loadTriler();
loadMovies();
loadCast();
}
this function to load movie
private void loadMovies() {
mService.getPopular(Common.API_KEY).enqueue(new Callback<MoviesList>()
{
#Override
public void onResponse(Call<MoviesList> call, Response<MoviesList>
response) {
results.clear();
results.addAll(response.body().getResults());
name = (TextView) findViewById(R.id.name_movie);
rating = (TextView) findViewById(R.id.rating);
date = (TextView) findViewById(R.id.date_det);
imageMovie = (ImageView) findViewById(R.id.imageView);
date.setText(selectedMovie.getReleaseDate());
name.setText(selectedMovie.getTitle());
rating.setText(String.valueOf(selectedMovie.getVoteAverage()));
final String image = Common.IMAGE_LOAD +
selectedMovie.getPosterPath();
Picasso.with(MovieDetails.this)
.load(image)
.into(imageMovie);
}
#Override
public void onFailure(Call<MoviesList> call, Throwable t) {
Log.d("===LoadMovies", "onResponse: " + t);
}
});
}
//i have proplem here in send ID postion
private void loadCast() {
mService.getCast(
ListMovieAdapter.SELECTED_MOVIE+Common.API_KEY).enqueue(new
Callback<MovieCast>() {
#Override
public void onResponse(Call<MovieCast> call, final
Response<MovieCast> response) {
cast.clear();
cast.addAll(response.body().getCast());
mRecyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onFailure(Call<MovieCast> call, Throwable t) {
}
});
}
}
package com.example.android.movie.Adapter;
/**
* Created by yuyu on 11-Nov-18.
*/
public class ListMovieAdapter extends
RecyclerView.Adapter<ListMovieAdapter.MyViewHolder> {
private ArrayList<Result> mMovies;
private Context context;
public static final String SELECTED_MOVIE = "selected_movie";
private int lastPosition = -1;
public ListMovieAdapter(ArrayList<Result> mMovies, Context context) {
this.mMovies = mMovies;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_views, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//Animation Scroll
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.down_from_top);
holder.itemView.startAnimation(animation);
lastPosition = position;
holder.nameMovie.setText(mMovies.get(position).getTitle());
final String image = Common.IMAGE_LOAD +
mMovies.get(position).getPosterPath();
Picasso.with(context)
.load(image)
.into(holder.imageMovie);
holder.rating.setText(String.valueOf(
mMovies.get(position).getVoteAverage()));
holder.dateMovie.setText(mMovies.get(position).getReleaseDate());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context, MovieDetails.class);
Result result = mMovies.get(position);
intent.putExtra(SELECTED_MOVIE, result);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mMovies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView imageMovie;
TextView nameMovie;
TextView rating;
TextView dateMovie;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
this.imageMovie = (ImageView)
itemView.findViewById(R.id.image_movie);
this.nameMovie = (TextView) itemView.findViewById(R.id.name_movie);
this.rating = (TextView) itemView.findViewById(R.id.rating);
this.dateMovie = (TextView) itemView.findViewById(R.id.date);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
}
From the Retrofit documentation:
URL MANIPULATION A request URL can be updated dynamically using
replacement blocks and parameters on the method. A replacement block
is an alphanumeric string surrounded by { and }. A corresponding
parameter must be annotated with #Path using the same string.
#GET("group/{id}/users")
Call<List<User>> groupList(#Path("id") int groupId);
https://square.github.io/retrofit/

Categories