passing string from an activity to a fragment - java

Hi ive been going through questions and found a solution to pass a string from an activity (not the fragment activity) to a fragment. i want to pass a document ID on click from RestaurantsList.class to Mainsfragment.class, inside my onclick.
The error message i get is the following:
Attempt to invoke virtual method 'android.content.Intent android.app.Activity.getIntent()' on a null object reference
here is my code for the activity:
package com.example.hostapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RelativeLayout;
import com.example.hostapp.Adapters.RestaurantAdapter;
import com.example.hostapp.Adapters.categoryCardAdapter;
import com.example.hostapp.MenuFragments.MainsFragment;
import com.example.hostapp.Models.Restaurant;
import com.example.hostapp.Models.categoryCard;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class RestaurantList extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference restaurantref = db.collection("restaurants");
private RestaurantAdapter adapter;
String categoryid = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant_list);
setUpRecyclerView();
}
private void setUpRecyclerView() {
//Get intent
if (getIntent() != null)
categoryid = getIntent().getStringExtra("categoryid");
if (!categoryid.isEmpty() && categoryid != null) {
Query query = restaurantref.whereEqualTo("categoryid", categoryid).orderBy("name");
final FirestoreRecyclerOptions<Restaurant> options = new FirestoreRecyclerOptions.Builder<Restaurant>().setQuery(query, Restaurant.class).build();
adapter = new RestaurantAdapter(options);
RecyclerView recyclerView = findViewById(R.id.restaurant_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListerner(new RestaurantAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Restaurant restaurant = documentSnapshot.toObject(Restaurant.class);
Intent foodlist = new Intent(RestaurantList.this, Foodlist.class);
Bundle bundle = new Bundle();
bundle.putString("restaurantid", documentSnapshot.getId());
MainsFragment m4 = new MainsFragment();
m4.setArguments(bundle);
//foodlist.putExtra("restaurantid", documentSnapshot.getId());
startActivity(foodlist);
}
});
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
here is my code for the fragment:
package com.example.hostapp.MenuFragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.hostapp.Adapters.FoodAdapter;
import com.example.hostapp.Models.FoodModel;
import com.example.hostapp.R;
import com.example.hostapp.RestaurantList;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class MainsFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private FoodAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mains, container, false);
String restaurantNumber = getArguments().getString("restaurantid");
Query menuref = db.collectionGroup("Foods").whereEqualTo("menuid", restaurantNumber);
FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>().
setQuery(menuref, FoodModel.class)
.build();
adapter = new FoodAdapter(options);
RecyclerView recyclerView = view.findViewById(R.id.recycler_mains);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(adapter);
return view;
}
private void setUpRecyclerView() {
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}

I had the same experience like this. Here is how I handled it:
1, Pass your data from RestaurantList activity to your foodlist activity via intent.putExtra();
Intent foodlist = new Intent(RestaurantList.this, Foodlist.class);
foodlist.putExtra("restaurantid", documentSnapshot.getId());
startActivity(foodlist);
2, Get the value by getIntent() from Foodlist activity;
String id = getIntent().getStringExtra("restaurantid");
3, Pass your data to the Adapter where you are initializing the adapter. (sth like this :)
YourAdapter adapter = new YourAdapter(getSupportFragmentManager(), tabLayout.getTabCount(),id);
4, Get the data in constractor of adapter (you have to create a global variable and fill it in constructor) and create a bundle in getItem() method and pass the data to it and set arguments to the fragment (like below code)
public class YourAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
String id;
public AdapterPagerShift(FragmentManager fm, int NumOfTabs, String id) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.id = id;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("restaurantid", documentSnapshot.getId());
switch (position) {
case 0:
MainsFragment main = new MainsFragment();
main.setArguments(bundle);
return main;
case 1:
//...
case 2:
//...
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
5, Get the data by using below code in your MainsFragment class :
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String id = getArguments().getString("restaurantid");
}
Hope it helps!

Related

error: non-static method show() cannot be referenced from a static context in FragmentActivity crashes

The sourcecode of the project is given below
non-static method show(FragmentManager,String) cannot be referenced from a static context
my AdminHomeActivity and the AdminComplaintDetailsFragment classes are given below.
Full project source codeof error
Main project source code
AdminHomeFragment.java
package com.example.ecomplaint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class AdminHomeFragment extends Fragment {
ListView listview;
public static ArrayList arrayList;
FirebaseDatabase rootNode;
DatabaseReference reference;
public static CustomRow adapter;
public static ArrayList adapterData;
FloatingActionButton mainbutton,registerbutton,logoutbutton;
Animation fabOpen,fabClose,rotateForward,rotateBackward;
boolean isOpen=false;
DatabaseReference referenceExpert;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_admin_home,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ProgressBar simpleProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
mainbutton=(FloatingActionButton) view.findViewById(R.id.floatingActionButton);
registerbutton=(FloatingActionButton) view.findViewById(R.id.registerbutton);
logoutbutton=(FloatingActionButton) view.findViewById(R.id.logout_button);
fabOpen= AnimationUtils.loadAnimation(getContext(),R.anim.from_buttom_anim);
fabClose= AnimationUtils.loadAnimation(getContext(),R.anim.to_buttom_anim);
rotateForward= AnimationUtils.loadAnimation(getContext(),R.anim.rotate_open_anim);
rotateBackward= AnimationUtils.loadAnimation(getContext(),R.anim.rotate_close_anim);
mainbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animatefab();
}
});
registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(),RegistrationActivity.class);
startActivity(i);
}
});
logoutbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(),MainActivity.class));
}
});
listview=view.findViewById(R.id.list);
listview.setItemsCanFocus(false);
arrayList = new ArrayList<Complaint>();
adapterData = new ArrayList<Complaint>();
adapter = new CustomRow(getContext(), arrayList);
listview.setAdapter(adapter);
simpleProgressBar.setVisibility(View.VISIBLE);
//arrayList.add(new Complaint("123","this is title","akhil","19bce1564","ragging","rahul","registered"));
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!arrayList.isEmpty()){
arrayList.clear();
}
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Complaint complaint=dataSnapshot.getValue(Complaint.class);
// if(complaint.getComplaintFrom().getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
//get all users complaint
arrayList.add(complaint);
// }
adapter.notifyDataSetChanged();
listview.requestLayout();
simpleProgressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Complaint present = (Complaint) arrayList.get(position);
AdminComplaintDetailsFragment admincomplaintDetailsFragment= new AdminComplaintDetailsFragment(present);
AdminComplaintDetailsFragment.show(((FragmentActivity)getContext()).getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
//Toast.makeText(getContext(), "hii", Toast.LENGTH_SHORT).show();
}
});
}
private void animatefab(){
if (isOpen){
mainbutton.startAnimation(rotateForward);
registerbutton.startAnimation(fabClose);
logoutbutton.startAnimation(fabClose);
registerbutton.setClickable(false);
logoutbutton.setClickable(false);
isOpen=false;
}
else{
mainbutton.startAnimation(rotateBackward);
registerbutton.startAnimation(fabOpen);
logoutbutton.startAnimation(fabOpen);
registerbutton.setClickable(true);
logoutbutton.setClickable(true);
isOpen=true;
}
}
}
AdminComplaintDetailsFragment.java
package com.example.ecomplaint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Locale;
/**
* A simple {#link Fragment} subclass.
* Use the {#link ComplaintDetailsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AdminComplaintDetailsFragment extends BottomSheetDialogFragment {
FirebaseDatabase rootNode;
DatabaseReference reference;
String[] items = {"Under investigation","Reviewing complaint","Investigation complete","Case Closed"};
AutoCompleteTextView autoCompleteTxt;
ArrayAdapter<String> adapterItems;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
Complaint present;
public AdminComplaintDetailsFragment() {
// Required empty public constructor
}
public AdminComplaintDetailsFragment(Complaint present){
this.present=present;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ComplaintDetailsFragment.
*/
// TODO: Rename and change types and number of parameters
public static AdminComplaintDetailsFragment newInstance(String param1, String param2) {
AdminComplaintDetailsFragment fragment = new AdminComplaintDetailsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_complaint_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(present.getStatus().equals("registered")){
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
present.setStatus("Seen");
HashMap hashMap=new HashMap();
hashMap.put("status","Seen");
reference.child(present.complaintID).updateChildren(hashMap);
Log.i("this",reference.child("complaintID").child(present.complaintID).child("status").toString());
}
TextView title=view.findViewById(R.id.details_title);
title.setText(present.getTitle());
TextView name=view.findViewById(R.id.details_name);
name.setText(present.getName());
TextView regno=view.findViewById(R.id.details_regno);
regno.setText(present.getRegno());
TextView incident=view.findViewById(R.id.details_info);
incident.setText(present.getIncident_info());
TextView ComplaintFrom=view.findViewById(R.id.complaintFrom);
ComplaintFrom.setText(present.getComplaintFrom().getName());
TextView status=view.findViewById(R.id.details_status);
status.setText(present.getStatus().toUpperCase(Locale.ROOT));
autoCompleteTxt = view.findViewById(R.id.auto_complete_txt);
adapterItems = new ArrayAdapter<String>(getContext(),R.layout.list_item,items);
autoCompleteTxt.setAdapter(adapterItems);
autoCompleteTxt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
present.setStatus(item);
HashMap hashMap=new HashMap();
hashMap.put("status",item);
reference.child(present.complaintID).updateChildren(hashMap);
Log.i("this",reference.child("complaintID").child(present.complaintID).child("status").toString());
status.setText(present.getStatus().toUpperCase(Locale.ROOT));
//Toast.makeText(getContext(),"Item: "+item,Toast.LENGTH_SHORT).show();
}
});
}
}
The show method on AdminComplaintDetailsFragment is not static which is what you are doing via AdminComplaintDetailsFragment.show.
Use the variable admincomplaintDetailsFragment that you've initialized.
Change
AdminComplaintDetailsFragment.show(((FragmentActivity)getContext()).getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
to
admincomplaintDetailsFragment.show(requireActivity.getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());

how to move from a fragment to a new activity when i clicked an item of recyclerview?

I am using recyclerview in fragment dynamically, now i want to open new activity on click of items with the same object / item.
AllCoursesFeagment.java
package com.example.learningapp.ui.NavigationDrawer.AllCourses;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Adapters.AllCoursesMyAdapter;
import com.example.learningapp.Interface.APIinterface;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import com.example.learningapp.Responses.CourseListResponse;
import com.example.learningapp.RetrofitAPIs.RetrofitAPI;
import com.example.learningapp.utility.ConstantData;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AllCoursesFragment extends Fragment {
private RecyclerView recyclerView;
private List<CourseListModel> courseListModelList;
public AllCoursesFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AllCoursesFragment newInstance() {
return new AllCoursesFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_courses,null);
recyclerView = view.findViewById(R.id.allCourseList_RV);
APIinterface apIinterface = RetrofitAPI.getClient().create(APIinterface.class);
Call<CourseListResponse> call = apIinterface.getAllCourses(ConstantData.AppKey);
call.enqueue(new Callback<CourseListResponse>() {
#Override
public void onResponse(Call<CourseListResponse> call, Response<CourseListResponse> response){
if (response.isSuccessful()){
courseListModelList = response.body().getCourseList();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new AllCoursesMyAdapter(getActivity(),courseListModelList));
}
}
#Override
public void onFailure(Call<CourseListResponse> call, Throwable t) {
Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AllCoursesMyAdapter.java
This is my adapter class.
package com.example.learningapp.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Activities.CheckoutActivity;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import java.util.List;
public class AllCoursesMyAdapter extends RecyclerView.Adapter<AllCoursesMyAdapter.RecyclerVH> {
Context context;
List<CourseListModel> courseListModelList;
public AllCoursesMyAdapter(Context context, List<CourseListModel> courseListModelList) {
this.context = context;
this.courseListModelList = courseListModelList;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_row_design_allcourses,parent,false);
return new RecyclerVH(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerVH holder, int position) {
final CourseListModel courseListModel = courseListModelList.get(position);
holder.courseTitle.setText(courseListModel.getCourseName());
holder.courseDesc.setText(courseListModel.getCourseDescription());
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
private void moveToNewActivity () {
Activity activity = new Activity();
Intent i = new Intent(activity, CheckoutActivity.class);
context.startActivity(i);
((Activity) context).overridePendingTransition(0, 0);
}
#Override
public int getItemCount() {
return courseListModelList.size();
}
public class RecyclerVH extends RecyclerView.ViewHolder {
TextView courseTitle,courseDesc;
Button buyBtn;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
courseTitle = itemView.findViewById(R.id.course_title);
courseDesc = itemView.findViewById(R.id.course_desc);
buyBtn = itemView.findViewById(R.id.btn_buycourse);
}
}
}
I'm gettng crashed when i clicked item
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Here i am using a stored list of objects and now i want to move to the new activity when i clicked on an item with given position, but i am not able to do that.
private void moveToNewActivity () {
Activity activity = new Activity(); //this is wrong, delete this
...
}
you can't and shouldn't create an instance of an activity like this, it's something the OS has to schedule and handle for you.
you already seem to have context defined somewhere, so that means:
private void moveToNewActivity () {
Intent i = new Intent(context, CheckoutActivity.class);
context.startActivity(i);
...
}
so that means:
#Override
public void onClick(View v) {
moveToNewActivity();
}

Want to use a floating action button that adds an item to a recyclerview in a specific fragment that is contained in a ViewPager2

I have been having a lot of trouble trying to implement multiple recyclerviews across multiple pages(represented by fragments) in a viewpager2, and I want to use a floating action button that when clicked, props up a page where the user can input data that can eventually be added to the recyclerview within a specific page on the viewpager. The Viewpager2 is applied with a tab layout labeling the days "Monday" to "Sunday." I cannot seem to add to the recyclerview through the activity "activity_add_medication_to_list." There is a long segment of code with 7 intents that is meant to represent adding to a medication list. The project is essentially a medical scheduling/tracking application. For each day of the week, I want to be able to add a specific medication to the list and be able to see it visibly. There are seven fragments representing each of the days of the week. FirstFragment represents Monday, SecondFragment represents Tuesday, etc. I also have a recyclerviewAdapter class and a ViewPagerAdapter class representing the adapters for both the multiple recyclerviews and the viewPager2.
Main problem: After clicking on the floating action button and inputing my data, it is not adding to the end of the recyclerview for any of the pages (represented by FirstFragment class). What am I missing that is not allowing me to see a visible list of items for any of the recyclerviews? How do I properly integrate the recyclerviews into the fragments so that I can update the recyclerviews using the floating action button?
Only 5 of the 7 fragment classes are shown below to conserve space. They are all according to the day of the week. Monday, Tuesday, Wednesday, Thursday, Friday refer to these first 5 fragment classes.
Code:
Add Medication to List class
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class add_medication_to_list extends AppCompatActivity {
String name;
String time;
int quantity;
int dosage;
String dayOfWeek;
EditText nameInput;
EditText timeInput;
EditText quantityInput;
EditText dosageInput;
EditText dayOfWeekInput;
Button add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_medication_to_list);
nameInput = findViewById(R.id.medicine_name);
timeInput = findViewById(R.id.time);
quantityInput = findViewById(R.id.medicine_quantity);
dosageInput = findViewById(R.id.dosage);
dayOfWeekInput = findViewById(R.id.dayOfWeek);
add = findViewById(R.id.addButton);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameInput.getText().toString();
time = timeInput.getText().toString();
quantity = Integer.parseInt(quantityInput.getText().toString());
dosage = Integer.parseInt(dosageInput.getText().toString());
dayOfWeek = dayOfWeekInput.getText().toString();
// setResult(RESULT_OK);
if (dayOfWeek.equalsIgnoreCase("monday")) {
FirstFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("tuesday")) {
SecondFragmentClass.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("wednesday")) {
ThirdFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("thursday")) {
FourthFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("friday")) {
FifthFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("saturday")) {
SixthFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
} else if (dayOfWeek.equalsIgnoreCase("sunday")) {
SeventhFragment.add_new_item(name, time, quantity, dosage);
Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(new_activity);
}
}
});
}
}
FirstFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FirstFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
View view;
public FirstFragment() {
// Required empty public constructor
}
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
public static FirstFragment newInstance(Integer counter) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
medlist = new ArrayList<>();
positionCounter = 0;
myRecyclerView = view.findViewById(R.id.prescription_list);
myRecyclerView.setHasFixedSize(true);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
} });
}
}
SecondFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class SecondFragmentClass extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static SecondFragmentClass newInstance(Integer counter) {
SecondFragmentClass fragment = new SecondFragmentClass();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
positionCounter = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_2, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
positionCounter = 0;
medlist = new ArrayList<>();
myRecyclerView = view.findViewById(R.id.prescription_list_2);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
ThirdFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class ThirdFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist = new ArrayList<>();
private static recyclerViewAdapter anAdapter = new recyclerViewAdapter(context, medlist);
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static ThirdFragment newInstance(Integer counter) {
ThirdFragment fragment = new ThirdFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
positionCounter = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_3, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
positionCounter = 0;
medlist = new ArrayList<>();
myRecyclerView = view.findViewById(R.id.prescription_list_3);
myRecyclerView.setHasFixedSize(true);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
FourthFragment Class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FourthFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static FourthFragment newInstance(Integer counter) {
FourthFragment fragment = new FourthFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_4, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
myRecyclerView = view.findViewById(R.id.prescription_list_4);
positionCounter = 0;
medlist = new ArrayList<>();
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setHasFixedSize(true);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
FifthFragment class
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FifthFragment extends Fragment {
private static final String ARG_COUNT = "param1";
private Integer counter;
private static Context context;
private int[] COLOR_MAP = {
R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
R.color.green_500, R.color.green_700
};
private RecyclerView myRecyclerView;
private static ArrayList<Medicine> medlist;
private static recyclerViewAdapter anAdapter;
private static int positionCounter;
public static void add_new_item(String name, String time, int quantity, int dosage) {
medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
anAdapter.notifyItemInserted(medlist.size()-1);
//anAdapter.notifyDataSetChanged();
positionCounter++;
}
public static FifthFragment newInstance(Integer counter) {
FifthFragment fragment = new FifthFragment();
Bundle args = new Bundle();
args.putInt(ARG_COUNT, counter);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
positionCounter = 0;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
counter = getArguments().getInt(ARG_COUNT);
positionCounter = 0;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_card_5, container, false);
return v;
}
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
medlist = new ArrayList<>();
positionCounter = 0;
myRecyclerView = view.findViewById(R.id.prescription_list_5);
myRecyclerView.setHasFixedSize(true);
anAdapter = new recyclerViewAdapter(getContext(), medlist);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.setAdapter(anAdapter);
new_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent new_activity = new Intent(context, add_medication_to_list.class);
startActivity(new_activity);
}
});
}
}
ViewPagerAdapter
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 7;
private ArrayList<Fragment> arrayList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return arrayList.get(position);
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
public void addFragment(Fragment fragment) {
arrayList.add(fragment);
}
}
recyclerViewAdapter
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class recyclerViewAdapter extends RecyclerView.Adapter<recyclerViewAdapter.MyViewHolder> {
Context data;
List<Medicine> new_list;
public recyclerViewAdapter(Context data, List<Medicine> new_list) {
this.data = data;
this.new_list = new_list;
}
public recyclerViewAdapter() {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(data).inflate(R.layout.new_items, parent, false);
MyViewHolder view = new MyViewHolder(v);
return view;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.new_name.setText(new_list.get(position).getName());
holder.new_quantity.setText(Integer.toString(new_list.get(position).getFrequency()));
holder.new_image.setImageResource(new_list.get(position).getPhoto());
holder.new_time.setText(new_list.get(position).getTime());
}
#Override
public int getItemCount() {
return new_list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView new_name;
private TextView new_quantity;
private ImageView new_image;
private TextView new_time;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
new_name = itemView.findViewById(R.id.prescription_name);
new_image = itemView.findViewById(R.id.new_image);
new_quantity = itemView.findViewById(R.id.quantity_items);
new_time = itemView.findViewById(R.id.new_time);
}
}
}
Medicine Class
package com.example.myapplication;
public class Medicine {
private String name_of_medicine, time_to_take;
private int quantity_remaining, Photo, frequency, dosage;
public Medicine(String name_of_medicine, String time_to_take, int quantity, int dosage, int photo) {
this.name_of_medicine = name_of_medicine;
this.time_to_take = time_to_take;
this.quantity_remaining = quantity;
this.dosage = dosage;
Photo = photo;
}
public String getName()
{
return name_of_medicine;
}
public String getTime()
{
return time_to_take;
}
public int getFrequency() {
return quantity_remaining;
}
public int getPhoto() {
return Photo;
}
}
Resolved this issue. Used finish() after calling add_new_item() method.

How to send Data when cardview clicked to detail content

I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter, but I get an error a null object reference in mOnItemClickListener.onClick(i).
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter.
I want to passing data to DetailMoviesFragment Class.
this is my CardviewMovieAdapter Class
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardviewMovieAdapter extends RecyclerView.Adapter<CardviewMovieAdapter.CardViewViewHolder> {
private ArrayList<Movie> listMovie;
Context context;
OnItemClickListener mOnItemClickListener;
public void setListMovie(ArrayList<Movie> listMovie) {
this.listMovie = listMovie;
}
public ArrayList<Movie> getListMovie() {
return listMovie;
}
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public CardviewMovieAdapter(ArrayList<Movie> listMovie, Context context) {
this.listMovie = listMovie;
this.context = context;
}
#NonNull
#Override
public CardviewMovieAdapter.CardViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_movie, viewGroup,false);
return new CardViewViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CardviewMovieAdapter.CardViewViewHolder cardViewViewHolder, final int i) {
final Movie movie = listMovie.get(i);
Glide.with(cardViewViewHolder.itemView.getContext())
.load(movie.getImageMovie())
.apply(new RequestOptions().override(350, 550))
.into(cardViewViewHolder.imgPhoto);
cardViewViewHolder.tvTitle.setText(movie.getTitleMovie());
cardViewViewHolder.tvDesc.setText(movie.getDescription());
cardViewViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Detail "+
listMovie.get(cardViewViewHolder.getAdapterPosition()).getTitleMovie(), Toast.LENGTH_SHORT).show();
}
});
cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
mOnItemClickListener.onClick(i);
}
});
// cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return listMovie.size();
}
public class CardViewViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvTitle, tvDesc;
Button btnDetail;
public CardViewViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_item_photo);
tvTitle = itemView.findViewById(R.id.tv_title);
tvDesc = itemView.findViewById(R.id.tv_desc);
btnDetail = itemView.findViewById(R.id.btn_detail);
}
}
}
This is my MoviesFragment Class
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MoviesFragment extends Fragment implements View.OnClickListener{
private RecyclerView rvMovie;
private String[] dataMovieTitle;
private String[] dataDescription;
private TypedArray dataPhoto;
private ArrayList<Movie> movies;
Button btnDetail;
private CardviewMovieAdapter adapter;
View view;
final static String KEY = "KEY";
public MoviesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movies, container, false);
//adapter = new CardviewMovieAdapter(movies,getContext());
rvMovie = view.findViewById(R.id.rv_movies);
prepare();
addItem();
showRecyclerCardView();
adapter = new CardviewMovieAdapter(movies, getContext());
adapter.setOnItemClickListener(new CardviewMovieAdapter.OnItemClickListener() {
#Override
public void onClick(int position) {
final Movie movie = movies.get(position);
DetailMoviesFragment detailMoviesFragment = new DetailMoviesFragment();
// Bundle mBundle = new Bundle();
// mBundle.putString(detailMoviesFragment.EXTRA_TITLE, movie.getTitleMovie());
// mBundle.putString(detailMoviesFragment.EXTRA_DESCRIPTION, movie.getDescription());
// mBundle.putInt(detailMoviesFragment.EXTRA_PHOTO, movie.getImageMovie());
// detailMoviesFragment.setArguments(mBundle);
MoviesFragment.newInstance(movie.getTitleMovie(), movie.getDescription(), movie.getImageMovie());
FragmentManager mFragmentManager = getFragmentManager();
if (mFragmentManager!= null) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containterFragment, detailMoviesFragment, DetailMoviesFragment.class.getSimpleName());
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
}
});
return view;
}
public static MoviesFragment newInstance(String title, String desc, int image) {
MoviesFragment moviesFragment = new MoviesFragment();
Bundle args = new Bundle();
args.putInt("image", image);
args.putString("title", title);
args.putString("desc", desc);
moviesFragment.setArguments(args);
return moviesFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void showRecyclerCardView(){
rvMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
CardviewMovieAdapter adapter = new CardviewMovieAdapter(movies,getActivity());
rvMovie.setAdapter(adapter);
}
private void prepare() {
dataMovieTitle = getResources().getStringArray(R.array.data_movie_name);
dataDescription = getResources().getStringArray(R.array.data_desc_movie);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo_movie);
}
private void addItem(){
movies = new ArrayList<>();
for (int i=0; i < dataMovieTitle.length; i++){
Movie movie = new Movie();
movie.setImageMovie(dataPhoto.getResourceId(i, -1));
movie.setTitleMovie(dataMovieTitle[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.card_view){
}
}
}
and this is DetailMoviesActivity Class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailMovieActivity extends AppCompatActivity {
Movie movie;
TextView tvTitle, tvDesc;
ImageView ivMovie;
Button btnDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_movie);
initView();
}
private void initView() {
movie = (Movie) getIntent().getSerializableExtra("informasi");
String judul = movie.getTitleMovie();
String desc = movie.getDescription();
int img = movie.getImageMovie();
tvTitle.setText(judul);
tvDesc.setText(desc);
Picasso.get().load(img).into(ivMovie);
}
}
You can try with delete the setOnItemClickListener and call intent from cardViewViewHolder.itemView.setOnClickListener

How to refresh RecyclerView in one fragment when data changed in another fragment

How do I refresh the data from a local database to RecyclerView when data was successfully submitted? I use the tabs on the application. 2nd-Tab functions to submit the data, and if successful, the data will be stored in localDB.
Data on localDB I will present at the 3rd-Tab.
But what happens, I have to swipe 1st-Tab, then swipe to the 2nd-Tab and then swipe to the new 3rd-Tab data on my localDB successfully displayed.
If the 2nd-Tab me to submit the data, then I swipe to 3rd-Tab, the data will not appear on the list of data.
How do I get the data directly displayed without the need to swipe to the first 1st-Tab and then to the 2nd-Tab and 3rd-Tab ???
MainActivity :
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.bertho.gmyl.fragments.EngagedFragment;
import com.bertho.gmyl.fragments.RequestFragment;
import com.bertho.gmyl.fragments.SigninFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.engine_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new SigninFragment(), "SIGN-IN");
adapter.addFrag(new EngagedFragment(), "ENGAGED ID");
adapter.addFrag(new RequestFragment(), "LOCATION");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
EngagedFragment (2nd-Tab) Form to save data
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bertho.gmyl.R;
import com.bertho.gmyl.model.Engaged;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.bertho.gmyl.realm.RealmHelper;
public class EngagedFragment extends Fragment implements View.OnClickListener {
private static final String TAG = EngagedFragment.class.getSimpleName();
private EditText nama, email, nohp;
private Button btnSaveConnection;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private RelativeLayout mRoot;
private View rootView;
private String userId;
private TextView lblNama, lblEmail, lblNohp;
private RelativeLayout relativeLayout;
private RealmHelper realmHelper;
public EngagedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_engaged, container, false);
realmHelper = new RealmHelper(getActivity());
String appName = getResources().getString(R.string.app_name);
loadLocalDB();
nama = (EditText) rootView.findViewById(R.id.txtName);
email = (EditText) rootView.findViewById(R.id.txtEmail);
nohp = (EditText) rootView.findViewById(R.id.txtNoHp);
lblNama = (TextView) rootView.findViewById(R.id.lblNameval);
lblEmail = (TextView) rootView.findViewById(R.id.lblEmailval);
lblNohp = (TextView) rootView.findViewById(R.id.lblNohpval);
relativeLayout = (RelativeLayout) rootView.findViewById(R.id.panelLabelDetail);
btnSaveConnection = (Button) rootView.findViewById(R.id.btnEngaged);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("tbl_engaged");
mFirebaseInstance.getReference("titleapp").setValue(appName);
mFirebaseInstance.getReference("titleapp").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "TITLE UPDATED FROM FIREBASE");
String appTitle = dataSnapshot.getValue(String.class);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, "FAILED TO READ TITLE FROM FIREBASE.", error.toException());
}
});
btnSaveConnection.setOnClickListener(this);
return rootView;
}
private void showSnack(String notify) {
mRoot = (RelativeLayout) rootView.findViewById(R.id.frag_engaged);
Snackbar snackbar = Snackbar.make(mRoot, notify, Snackbar.LENGTH_LONG);
snackbar.show();
}
public void onClick(View v) {
if(v.getId() == R.id.btnEngaged) {
String txtName = nama.getText().toString();
String txtEmail = email.getText().toString();
String txtNo = nohp.getText().toString();
if(txtName.equals("") || txtName.isEmpty()) {
showSnack("Name must filled");
nama.requestFocus();
} else if (txtEmail.equals("") || txtEmail.isEmpty()) {
showSnack("Email must filled");
email.requestFocus();
} else if (txtNo.equals("") || txtNo.isEmpty()) {
showSnack("No.HP must filled");
nohp.requestFocus();
} else {
createUser(txtName, txtEmail, txtNo);
saveToLocalDB(txtName, txtEmail, txtNo);
}
}
}
private void saveToLocalDB(String txtName, String txtEmail, String txtNo) {
realmHelper.addEngaged(txtName, txtEmail, txtNo);
}
private void loadLocalDB() {
realmHelper.getAllData();
}
private void createUser(String name, String email, String nohp) {
userId = mFirebaseDatabase.push().getKey();
Engaged user = new Engaged(name, email, nohp);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
private void addUserChangeListener() {
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Engaged user = dataSnapshot.getValue(Engaged.class);
if (user == null) {
Log.e(TAG, "ENGAGED DATA IS NULL");
return;
}
Log.e(TAG, "ENGAGED DATA IS CHANGED!" + user.name + ", " + user.email);
lblNama.setText(user.name);
lblEmail.setText(user.email);
lblNohp.setText(user.nohp);
//relativeLayout.setVisibility(View.VISIBLE);
nama.setText("");
email.setText("");
nohp.setText("");
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "FAILED TO READ USER", error.toException());
}
});
}
}
RequestFragment (3rd-Tab) To display localDB
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.bertho.gmyl.R;
import com.bertho.gmyl.adapter.AdapterEngaged;
import com.bertho.gmyl.model.ModelEngaged;
import com.bertho.gmyl.realm.RealmHelper;
import java.util.ArrayList;
public class RequestFragment extends Fragment {
private static final String TAG = "RequestFragment";
private RecyclerView recyclerView;
private View rootView;
private ArrayList<ModelEngaged> data;
private RealmHelper helper;
public RequestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_request, container, false);
data = new ArrayList<>();
helper = new RealmHelper(getActivity());
recyclerView = (RecyclerView) rootView.findViewById(R.id.rvArticle);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
setRecyclerView();
return rootView;
}
public void setRecyclerView() {
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
AdapterEngaged adapter = new AdapterEngaged(data, new AdapterEngaged.OnItemClickListener() {
#Override
public void onClick(ModelEngaged item) {
Toast.makeText(getContext(), "LIST CLICKED", Toast.LENGTH_LONG).show();
}
});
recyclerView.setAdapter(adapter);
}
#Override
public void onResume() {
super.onResume();
try {
data = helper.findAllArticle();
} catch (Exception e) {
e.printStackTrace();
}
setRecyclerView();
}
}
Everything went smoothly, it's just that I hope the data can be displayed when the form is submitted and can be directly viewed on the 3rd-Tab
Try this,
Create an Interface in EngagedFragment
say,
public interface SubmitListener {
void onSubmit();
}
private SubmitListener onSubmitListener;
public void setSubmitListener(SubmitListener onSubmitListener){
this.onSubmitListener = onSubmitListener;
}
public SubmitListener getOnSubmitListener(){
return onSubmitListener;
}
In saveToLocalDB(...) method
call
onSubmitListener.onSubmit();
In MainActivity:
1) Update the below statement:
public class MainActivity extends AppCompatActivity implements EngagedFragment.SubmitListener
2) Make your ViewPagerAdapter adapter; variable as Global variable;
while adding fragment:
EngagedFragment engagedFrag = new EngagedFragment();
adapter.addFrag(engagedFrag, "ENGAGED ID");
...
viewPager.setAdapter(adapter);
3) add this after setting adapter
engagedFrag.setSubmitListener(this);
4) Override onSubmit() method and try the below code in that method
if(viewPager != null){
if(adapter != null){
Fragment fragment = adapter.getItem(2);
if(fragment != null){
RequestFragment requestFragment = (RequestFragment) fragment;
requestFragment.setRecyclerView();
}
}
}
try this
mViewPager.setOffscreenPageLimit(0);
if that doesnt help, please check below SO question:
fragment refresh On Swip
and about : mViewPager.setOffscreenPageLimit(0); this might not work as i found in one of #commonware 's answer's, the following :-
"Does ViewPager require a minimum of 1 offscreen pages
Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small; defaulting to 1"

Categories

Resources