I made a RecyclerView with CardViews that retrieve two TextViews from the Cloud Firestore and whenever I click on the card, I want it, based on the pdfUrl stored in my Firestore database, that an activity be opened with the pdf or donwload the pdf to the phone. But I don't know how to achieve that.
Here's my firestore structure
My code:
public class RecylerViewTestsActivity extends AppCompatActivity {
RecyclerView recyclerView;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private FirestoreRecyclerAdapter<uploadTests, TestesViewHolder> adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyler_view_tests);
RecyclerView recyclerView = findViewById(R.id.recyclerViewTests);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("FilterPDFUploads");
FirestoreRecyclerOptions<uploadTests> options = new FirestoreRecyclerOptions.Builder<uploadTests>()
.setQuery(query, uploadTests.class)
.build();
adapter = new FirestoreRecyclerAdapter<uploadTests,TestesViewHolder >(options) {
#Override
protected void onBindViewHolder(#NonNull TestesViewHolder holder, int position, #NonNull uploadTests model) {
holder.setTestesDesc(model.getDescription());
holder.setTestesName(model.getUsername());
}
#NonNull
#Override
public TestesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pdf_tests_items, parent, false);
return new TestesViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
//////////////////////////VIEW HOLDER////////////////////////////////////////////
private class TestesViewHolder extends RecyclerView.ViewHolder {
private View view;
private CardView itemsCard;
TestesViewHolder(final View itemView) {
super(itemView);
view = itemView;
}
void setTestesDesc (String descri) {
TextView desc = view.findViewById(R.id.teste_description);
desc.setText(descri);
}
void setTestesName (String username) {
TextView user = view.findViewById(R.id.name_id);
user.setText(username);
}
void setPdfUrl(final String url){
}
}
//////////////////////////VIEW HOLDER////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
whenever I click on the card, I want it, based on the pdfUrl stored in my firestore database, that an activity be opened with the pdf or donwload the pdf to the phone
To solve this, you should use setOnClickListener() on your TestesViewHolder object. Inside the click listener, please add the following lines of code:
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
Where url is the actual url that is stored in your database. That's it!
Related
so i write a code for searching some range of data in my realtime firebase and when i did that, the data that shown up its not only in range, but all data that i have in firebase is out to my cardview(fragment)
this is my main code that work for searching data
public class SearchListView extends AppCompatActivity {
private RecyclerView recView;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_search_list_view);
String tanggalawal = getIntent ( ).getStringExtra ("tanggalawal");
String tanggalakhir = getIntent ( ).getStringExtra ("tanggalakhir");
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference pendingRef = db.child("Users").child("Pending");
Query queryByKey = pendingRef.orderByKey()
.startAt("*" + tanggalawal)
.endAt("*"+ tanggalakhir + "\uf8ff");
recView = (RecyclerView)findViewById (R.id.recview);
recView.setLayoutManager (new LinearLayoutManager (this));
FirebaseRecyclerOptions<Model> options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(queryByKey, Model.class)
.build();
adapter = new MyAdapter (options);
recView.setAdapter (adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
and my firebase look like this
Firebase Database
and this is my adapter code
public class MyAdapter extends FirebaseRecyclerAdapter <Model,MyAdapter.myViewHolder>{
public MyAdapter(#NonNull FirebaseRecyclerOptions<Model> options) {
super (options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder myViewHolder, int i, #NonNull Model model) {
myViewHolder.currentDate.setText (model.getCurrentDate ());
myViewHolder.fullName.setText (model.getFullName ());
myViewHolder.currentDateandTime.setText (model.getCurrentDateandTime ());
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from (parent.getContext ()).inflate (R.layout.item,parent,false);
return new myViewHolder (view);
}
class myViewHolder extends RecyclerView.ViewHolder{
TextView currentDate, fullName, currentDateandTime;
public myViewHolder(#NonNull View itemView) {
super (itemView);
currentDate = (TextView)itemView.findViewById (R.id.tvTanggalPengajuan);
fullName = (TextView)itemView.findViewById (R.id.tvNama);
currentDateandTime = (TextView)itemView.findViewById (R.id.tvNomorkontrak);
}
}
public interface OnNoteListener{
void OnNoteListener(int position);
}
}
i've following this method using "*" that look like this, but still failed
Search firebase realtime database base on 6 digit in front of the child data, i want to query data between two numbers (dates)
I am working on mobile app which is for books.
I have recyclerview that has all categories - Romance, History etc.This RV is taking the data from Firebase.
What I want to do is following:
When the user clicks on Romance for example, a new activity needs to be opened. In that activity I want to have one RV loading the data-set with all books from that type.
Then, If the user opens History I want that data-set to be loaded into the same RV.
I want to avoid code repeating and what I am asking is - can I have 1 class with If statements that can handle the user choice and load the data-sets into one RV?
Would you be able to tell me how, if its possible?
Thank you !
Edit: Here is my code. What I did so far is Adapter, GetAndSet class, 2 Activities. To show categories into one RV I use 1 adapter and 1 GetAndSet class,1 XML file. I created 2 separate classes for romance and Comedy and inside them I do the connection to firebase.
Adapter:
public class CategoriesAdapter extends RecyclerView.Adapter {
Context mContext;
List<Categories> mData;
public CategoriesAdapter(Context mContext, List<Categories> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View row = LayoutInflater.from( mContext ).inflate( R.layout.row_attractions, parent, false );
return new MyViewHolder( row );
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.DesName.setText( mData.get( position ).getName() );
Glide.with( mContext ).load( mData.get( position ).getImage() ).into( holder.DesImage );
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView DesName;
ImageView DesImage;
public MyViewHolder(#NonNull View itemView) {
super( itemView );
itemView.setClickable( true );
mContext = itemView.getContext();
DesName = itemView.findViewById( R.id.DesName );
DesImage = itemView.findViewById( R.id.DesImage );
DesImage.setOnClickListener( this );
}
#Override
public void onClick(View v) {
final Intent intent;
Toast.makeText(itemView.getContext(),"Test",Toast.LENGTH_LONG ).show();
switch (getAdapterPosition()) {
case 0:
intent = new Intent( mContext, Romance.class );
break;
case 1:
intent = new Intent( mContext, Comedy.class );
break;
// case 2:
// intent = new Intent( mContext, RegentsPark.class );
// break;
default:
intent = new Intent( mContext, Home.class );
break;
}
mContext.startActivity( intent );
}
}
}
Romance class (Same as Comedy class,except the line with Firebase where I reffer to the dataset:
public class Romance extends AppCompatActivity {
RecyclerView categoriesRecyclerView ;
CategoriesAdapter categoriesAdapter ;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference ;
List<Categories> categoriesList;
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_romance);
categoriesRecyclerView = findViewById(R.id.BookRV);
categoriesRecyclerView.setLayoutManager(new LinearLayoutManager(Romance.this));
categoriesRecyclerView.setHasFixedSize(true);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("ListParks");
// mUserDatabase = FirebaseDatabase.getInstance().getReference("Categories");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(Romance.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getName(), model.getImage());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userName, String userImage){
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
user_name.setText(userName);
Glide.with(ctx).load(userImage).into(user_image);
}
}
#Override
protected void onStart() {
super.onStart();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
categoriesList = new ArrayList<>();
for (DataSnapshot catsnap: dataSnapshot.getChildren()) {
Categories post = catsnap.getValue(Categories.class);
categoriesList.add(post) ;
}
//set Adapter
categoriesAdapter = new CategoriesAdapter(Romance.this,categoriesList);
categoriesRecyclerView.setAdapter(categoriesAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Can I avoid creating different classes for each type of books?
If you want to know what category the user selected on the first RecyclerView:
Pass the category name/identifier to the activity you want to open when user clicks on the RecyclerView item. And then from the second activity get your data-set object according to the category you got from the previous activity and pass it to the adapter.
You can make a custom RecyclerView.Adapter.
Here is a good example:
Android Developers Documentation Example
When the adapter is initiated, you pass the data-set. This is the constructor of your custom RecyclerView.Adapter class:
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
So every time you create the activity which is listing the books, you can create new RecyclerView.Adapter instance passing your data-set.
Put this somewhere in your onCreate method of the activity:
MyAdapter myAdapter = new MyAdapter(myDataset);
recyclerView.setAdapter(myAdapter);
When your activity is created, your RecyclerView will be loaded with the new data-set you provided the RecyclerView.Adapter with.
P.S.
If you are actually resuming the activity and have never destroyed it and want to change the adapter of already existing RecyclerView and refresh new items, you can do this in your onResume method
MyAdapter myAdapter = new MyAdapter(myDataset);
recyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
Another way would be, again, if you are resuming (not creating) the activity and really don't want to create new Adapter and set it every time the activity resumes, then you will have to edit manually the data-set object you passed earlier to your custom adapter and call:
myAdapter.notifyDataSetChanged();
By saying edit I don't mean reassigning the variable! If you reassign the variable with another object, the adapter will loose the reference to that object and it will not work.
I am creating a new android application that retrieves one image,two texts that have been uploaded to firebase using different or say admin app,and the uploaded image and text views will be retrieved into one single card view as shown in image. which is in a recyclerview,now,i want it to be like any other blog app.So that when the user click on that card view,the imageview,the heading,the matter all these views will be arranged in a default layout as shown in image below.I mean like setting the image view to the image been retrieved from firebase and both text views to the texts retrieved from firebase.So that when ever any user clicks any blog post that retrieved from firebase,it should open that default layout and all the views will go to their places declared.how can i achieve this?. The code that i used to retrieve and show the content in a cardview is as below.As i am new to stackoverflow,i dont have enough reputation to add images.please go through the image links below.
image one
https://ibb.co/kJtvNTm
https://ibb.co/KXB8fdj
This is for my own educational purpose,i am new in developing android applications and firebase.I tried retrieving them but it doesn't do will to put them in their place
PostRecyclerActivity.java
private RecyclerView mRecyclerView;
private PostImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private List<PostUpload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_image_recycler);
mRecyclerView = findViewById(R.id.post_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.post_progress_circle);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("posts");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PostUpload upload = postSnapshot.getValue(PostUpload.class);
mUploads.add(upload);
}
mAdapter = new PostImageAdapter(PostImageRecyclerActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PostImageRecyclerActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
}
PostImageAdapter.java
public class PostImageAdapter extends RecyclerView.Adapter<PostImageAdapter.ImageViewHolder> {
private Context mContext;
private List<PostUpload> mUploads;
public PostImageAdapter(Context context, List<PostUpload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.post_card, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
PostUpload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getHeading());
Picasso.get()
.load(uploadCurrent.getmImageUrl())
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.post_image_view_upload);
}
}
}
PostUpload.java
public class PostUpload {
private String mHeading;
private String mMatter;
private String mImageUrl;
public PostUpload() {
}
public PostUpload(String heading, String matter, String imageUrl) {
if (heading.trim().equals("")) {
heading = "No Name";
}
mHeading = heading;
mMatter = matter;
mImageUrl = imageUrl;
}
public String getHeading(){
return mHeading;
}
public void setHeading(String name){
mHeading=name;
}
public String getMatter(){
return mMatter;
}
public void setMatter(String name){
mMatter=name;
}
public String getmImageUrl(){
return mImageUrl;
}
public void setImageUrl(String imageUrl){
mImageUrl=imageUrl;
}
}
I expect the output after clicking the blog-post should be having the image and heading set in their places as shown in image two and and a matter is retrieved from firebase and set into the other text view as shown in image two.
When you are getting the data from Firebase, you are storing it at your mUploads array of type PostUpload the data that you want to show into those CardViews
Here
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PostUpload upload = postSnapshot.getValue(PostUpload.class);
mUploads.add(upload);
}
mAdapter = new PostImageAdapter(PostImageRecyclerActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PostImageRecyclerActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
When you hit mRecyclerView.setAdapter(mAdapter); you already have filled the array and show the info to the user.
After that you can use the getItem() from the adapter.
You just need to override that method inside your PostImageAdapter
public PostUpload getItem(int position) {
return mUploads.get(position);
}
Once you have this method, you can access any item from the array filled from Firebase in your PostRecyclerActivity.java
So, after you click an item in your RecyclerView, you can get the position and get the object info from that position
Here are many good ways to implement the click of each row of the recyclerview (I recommend the first one)
So, after you implement the click of each row in your recyclerview, just pass that data throught a bundle or extras to the other Activity
Pseudo code Example
recyclerView.onClick{...
public void recyclerViewListClicked(View v, int position){
if(mAdapter.getItemCount() > 0){
PostUpload post = mAdapter.getItem(position);
}else{
Toast("There is no data into the element");
}
//Go to another Activity
Intent intent = new Intent(PostRecyclerActivity.this,yourSecondActivity.class);
intent.putExtra(post.getHeadding,"postheading");
intent.putExtra(post.getMatter,"postmatter");
//You keep doing the same with the other data you need to send out.
startActivity(intent);
}
How to get the data from Activity2
Intent intent = getIntent();
String postheading = intent.getStringExtra("postheading");
String postmatter = intent.getStringExtra("postmatter");
Since the image is an URL of type String, just pass it as intent.putExtra() as we did before and you can get that URL from the other Activity and inflate your image.
I'm having a problem with making a RecycleView in a fragment with data from Firebase. I expect the app to show the RecycleView after I clicked on a button to change from one fragment to the RecycleView fragment, but it does change the showed fragment but it does not show anything.
I know there are plenty of questions like this but I don't seem to find the correct solution to this problem.
I've made everything needed for a Firebase RecyclerView, and also tried to build it inside an activity instead fragment and it did work, but not with the fragment.
I've tried to initialize the adapter and recyclerview inside the onCreateView method, onActivityCreated, and onViewCreated method and none of them seem to be working.
Here's my fragment code:
private KidAdapter adapter;
private RecyclerView recyclerView;
Button button;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.uangsaku_menu_fragment, container, false);
button = view.findViewById(R.id.btn_add);
button.setOnClickListener(this);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
setUpRecyclerView();
return view;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_add){
Intent intent = new Intent(getActivity(), Register.class);
startActivity(intent);
}
}
public void setUpRecyclerView(){
Query query = FirebaseDatabase.getInstance().getReference("kids");
FirebaseRecyclerOptions<kidData> options = new FirebaseRecyclerOptions.Builder<kidData>()
.setQuery(query, kidData.class)
.build();
adapter = new KidAdapter(options);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
if (adapter != null) {
adapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
The adapter class
public class KidAdapter extends FirebaseRecyclerAdapter<kidData, KidAdapter.KidViewHolder> {
public KidAdapter(#NonNull FirebaseRecyclerOptions<kidData> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull KidViewHolder holder, int position, #NonNull kidData model) {
holder.nama.setText(model.getKidName());
holder.balance.setText(model.getKidBalance());
holder.limit.setText("Limit: "+model.getKidLimit());
holder.spending.setText("Spending xxx.xxx");
}
#NonNull
#Override
public KidViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.kids_card,
viewGroup, false);
return new KidViewHolder(v);
}
public class KidViewHolder extends RecyclerView.ViewHolder {
TextView nama, balance, limit, spending;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.tv_nama);
balance = itemView.findViewById(R.id.tv_balance);
limit = itemView.findViewById(R.id.tv_dailylimit);
spending = itemView.findViewById(R.id.tv_dailyspending);
}
}
}
The kidData model class
public class kidData {
String kidName, kidEmail, kidDoB, kidLimit, kidBalance;
public kidData(){
}
public kidData(String kidName, String kidEmail, String kidDoB, String kidLimit, String kidBalance) {
this.kidName = kidName;
this.kidEmail = kidEmail;
this.kidDoB = kidDoB;
this.kidLimit = kidLimit;
this.kidBalance = kidBalance;
}
public String getKidName() {
return kidName;
}
public String getKidEmail() {
return kidEmail;
}
public String getKidDoB() {
return kidDoB;
}
public String getKidLimit() {
return kidLimit;
}
public String getKidBalance() {
return kidBalance;
}
}
The problem in your code is the use of the following line of code:
recyclerView.setHasFixedSize(true);
And this is because when using the latest version of Firebase-UI library, there is no need to set the size of the RecyclerView as fixed. The solution for solving this problem is to simply remove/comment the above line of code. That's it!
Hello everyone I am doing a news app for university and I have kind of problem with displaying saved data to another activity. Im using retrofit to get data from internet and Sugar ORM to save data localy. So, news are displaying great and I created a CardView where it has a button "Read Later". The method to save data into database s working (at least on log it shows that it is working) but I cant get saved data to read_later activity. Alos I have an Adapter which contains onBindViewHolder.
#Override
public void onBindViewHolder(#NonNull MainArticalAdapter.ViewHolder viewHolder, int position) {
final Article articleModel = articleArrayList.get(position);
if(!TextUtils.isEmpty(articleModel.getTitle())){
viewHolder.titleText.setText(articleModel.getTitle());
}
if(!TextUtils.isEmpty(articleModel.getDescription())) {
viewHolder.descriptionText.setText(articleModel.getDescription());
}
if(!TextUtils.isEmpty(articleModel.getUrlToImage())){
Picasso.get().load(articleModel.getUrlToImage())
.resize(700,500)
.centerInside()
.into(viewHolder.imgView);
}
viewHolder.artilceAdapterParentLinear.setTag(articleModel);
Button btn = viewHolder.btn_read_later;
btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Article art = new Article();
art.setAuthor("Harun Shaban");
art.save();
}
}
);
}
and viewholder which extends RecyclerView.ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView titleText, descriptionText;
private LinearLayout artilceAdapterParentLinear;
private ImageView imgView;
private Button btn_read_later;
public ViewHolder(#NonNull View view) {
super(view);
btn_read_later = view.findViewById(R.id.button_read_later);
imgView = view.findViewById(R.id.article_adapter_image_view);
titleText = view.findViewById(R.id.article_adapter_tv_title);
descriptionText = view.findViewById(R.id.article_adapter_tv_description);
artilceAdapterParentLinear = view.findViewById(R.id.article_adapter_ll_parent);
artilceAdapterParentLinear.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if(onRecyclerViewItemClickListener != null){
onRecyclerViewItemClickListener.onItemClick(getAdapterPosition(),view);
}
}
}
);
}
}
and this is in my MainActivity class which contains a method to display all data received from internet by retrofit
private void showData(){
// Second step to create the recycler view to show the data taken
final RecyclerView mainRecycler = findViewById(R.id.activity_main_tv);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mainRecycler.setLayoutManager(linearLayoutManager);
// First step to create the response
final APIInterface apiService = ApiClient.getClient().create(APIInterface.class);
Call<ResponeModel> call = apiService.getLatestNews("techcrunch", API_KEY);
//third step
call.enqueue(new Callback<ResponeModel>() {
#Override
public void onResponse(Call<ResponeModel> call, Response<ResponeModel> response) {
if(response.body().getStatus().equals("ok")){
List<Article> articleList = response.body().getArticles();
if(articleList.size()>0){
final MainArticalAdapter mainArticalAdapter = new MainArticalAdapter(articleList);
mainArticalAdapter.setOnRecyclerViewItemClickListener(MainActivity.this);
mainRecycler.setAdapter(mainArticalAdapter);
}
}
}
#Override
public void onFailure(Call<ResponeModel> call, Throwable t) {
Log.e("on Fail", t.toString());
}
});
}
I tried to work with same logic in Read_later_Activity but it crashes.
This is my Read_later_activity…
public void getDatafromDB() {
List <Article> savedArticles = Article.listAll(Article.class);
final RecyclerView read_later_recView = findViewById(R.id.activity_read_later_tv);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
read_later_recView.setLayoutManager(linearLayoutManager);
if(savedArticles.size()>0){
final MainArticalAdapter mainArticalAdapter = new MainArticalAdapter(savedArticles);
mainArticalAdapter.setOnRecyclerViewItemClickListener((OnRecyclerViewItemClickListener) ReadLaterActivity.this);
read_later_recView.setAdapter(mainArticalAdapter);
//to retrieve the data from DB, by id (crashes)
//Article art = Article.findById(Article.class, 0);
//titleText_readLater.setText(art.getTitle());
/*Don`t know what to do*/
}
}