Remove Activity Views after Fragment Loads - android

I have an activity that hosts a fragment. The activity essentially has no content except a spinner that indicates the fragment is loading. The fragment is dependent upon a stable internet connection, therefore the length of time required for the spinner to be visible is dynamic in nature.
I want to remove the spinner on the activity after the fragment successfully loads. I tried using the isAdded() method, however that approach did not work. Any help is appreciated:
Fragment:
public class LatestFragment extends Fragment {
// 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";
private RecyclerView mRecyclerViewForLatestPolls;
private RecyclerView.Adapter mLatestAdapter;
private ArrayList<LatestPoll> mLatestPollsArray;
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private Firebase mBaseRef;
private Firebase mPollRef;
private Firebase mUpdateRef;
private FragmentListener mFragmentListener;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public LatestFragment() {
// Required empty public constructor
}
/**
* 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 LatestFragment.
*/
// TODO: Rename and change types and number of parameters
public static LatestFragment newInstance(String param1, String param2) {
LatestFragment fragment = new LatestFragment();
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);
mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
mDate = new Date();
mCurrentDateString = mDateFormat.format(mDate);
mBaseRef = FirebaseUtil.FIREBASE;
mPollRef = mBaseRef.child("Polls");
mUpdateRef = mPollRef.child(mCurrentDateString);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_latest, container, false);
getActivity().setTitle(R.string.latest_title);
mRecyclerViewForLatestPolls = (RecyclerView) rootView.findViewById(R.id.latest_RecyclerView);
mLatestPollsArray = new ArrayList<>();
mLatestAdapter = new MyAdapter(mLatestPollsArray);
LinearLayoutManager llm = new LinearLayoutManager(getActivity().getApplicationContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerViewForLatestPolls.setLayoutManager(llm);
mRecyclerViewForLatestPolls.setItemAnimator(new SlideInLeftAnimator());
mRecyclerViewForLatestPolls.setAdapter(new AlphaInAnimationAdapter(mLatestAdapter));
mUpdateRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int numberOfPollsForDay = (int) dataSnapshot.getChildrenCount();
for (int i = 0; i < numberOfPollsForDay; i++) {
String latestPollQuestion = (String) dataSnapshot.child(String.valueOf(i + 1)).child("Poll_Question").getValue();
String pollImageURL = (String) dataSnapshot.child(String.valueOf(i + 1)).child("Image").getValue();
mLatestPollsArray.add(0, new LatestPoll(latestPollQuestion, pollImageURL));
mLatestAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
// Inflate the layout for this fragment
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
// Force the parent activity to implement listener.
if (context instanceof FragmentListener) {
mFragmentListener = (FragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
mFragmentListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<LatestPoll> mDataSet;
int lastPosition = -1;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
protected TextView pollQuestion;
protected ImageView pollImage;
public ViewHolder(View v) {
super(v);
pollQuestion = (TextView) v.findViewById(R.id.latest_item_question);
pollImage = (ImageView) v.findViewById(R.id.pollThumbNailImage);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<LatestPoll> myDataset) {
mDataSet = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.latest_item, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.v("ON_BIND", "ON_BINDVIEWHOLDER CALLED");
LatestPoll latestPoll = mDataSet.get(position);
holder.pollQuestion.setText(latestPoll.getQuestion());
Picasso.with(getActivity())
.load(latestPoll.getPollImage())
.fit()
.placeholder(R.drawable.loading_spinnter_white)
.into(holder.pollImage);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataSet.size();
}
}
private void onLoad() {
if (mFragmentListener != null) {
mFragmentListener.onFragmentLoaded();
}
}
public interface FragmentListener {
void onFragmentLoaded();
}
}
Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/action_tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black"
android:titleTextColor="#color/white">
</android.support.v7.widget.Toolbar>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/pbHeaderProgress"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerInParent="true"
android:progressDrawable="#drawable/loading_spinnter_white">
</ProgressBar>
<TextView
android:id="#+id/progress_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pbHeaderProgress"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="#string/loading_poll_data"
android:textColor="#color/white"
android:textSize="24sp" />
</RelativeLayout>
<FrameLayout
android:id="#+id/latest_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</FrameLayout>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
Image:

In fragment create a listener interface,
private MyFragmentListener mListener;
/**
* onLoad should be called when the fragment has loaded.
*/
private void onLoad() {
if (mListener != null) {
mListener.onFragmentLoaded();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Force the parent activity to implement listener.
if (context instanceof MyFragmentListener) {
mListener = (MyFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface MyFragmentListener {
void onFragmentLoaded();
}
Then in parent activity,
public class MainActivity extends Activity implements MyFragment.MyFragmentListener{
#Override
public void onFragmentLoad() {
// HIDE the progressbar spinner.
}
See Communicating with Other Fragments for more info.

Related

Black Screen when opening Layout of Fragment

I followed this tutorial to show my items in a recycler view. Only adaption I made was displaying them inside a Fragment instead of an Activity.
In my App i have a login screen which redirects the user to an Activity when pressing a button. The startup Screen works properly but when pressing the button (→ opening the activity and the fragment) all i get is a black screen. The Logcat output wont help either since it doesn't display any kind of errors. All i get is:
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on ViewConfiguration
This sounds more than a layout issue than a code issue or am I wrong here? Could this bug be caused by some error in the recycler view?
edit:
After a lot of debugging i could at least border the bug to occur when calling the ShopFragment Class/View. When setting the default Fragment to something else, it gets rendered. But once i enter the ShopFragment it becomes blank and freezes. So please be so kind and help me to find the bug:
ShopFragment:
public class ShopFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
protected View mView;
private OnFragmentInteractionListener mListener;
private ArrayList<Item> items;
public ShopFragment() {
}
public static ShopFragment newInstance(String param1, String param2) {
ShopFragment fragment = new ShopFragment();
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) {
//get reference to recyclerView
View view = inflater.inflate(R.layout.fragment_shop, container, false);
this.mView = view;
RecyclerView itemView = mView.findViewById(R.id.rvCategories);
items = Item.ItemList();
ItemAdapter adapter = new ItemAdapter(items);
itemView.setAdapter(adapter);
itemView.setLayoutManager(new LinearLayoutManager(this.getContext()));
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
fragment_shop.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvCategories"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Item:
public class Item {
private static ArrayList<Item> mItemList;
private String mID, mTitle, mDescription, mProductType, mPictureLink, mCondition, mAvailability, mPrice, mBrand, mGtin, mMpn, mShippingCountry, mService, mShippingCosts, mpubDate;
public Item() {
}
public String getName() {
return mProductType;
}
public static ArrayList<Item> ItemList() {
XMLHandler itemFetcher = new XMLHandler();
itemFetcher.execute();
while (itemFetcher.processing()) {
}
mItemList = itemFetcher.getItems();
Log.i("ITEMS CONTENT", itemFetcher.getItems().toString());
return itemFetcher.getItems();
}
}
item_singleproduct.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
>
<TextView
android:id="#+id/category_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
ItemAdapter
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<Item> mCategories;
ViewHolder vh;
public ItemAdapter(List<Item> categories) {
mCategories = categories;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_singleproduct, parent, false);
vh = new ViewHolder(contactView);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Item item = mCategories.get(position);
TextView textView = vh.nameTextView;
textView.setText(item.getmProductType());
}
#Override
public int getItemCount() {
return mCategories.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.category_name);
}
}
}
Try debugging like this
Put your layout of fragment in a new parent
Set wrapped layout visibility to GONE state
Set parent layout color to yellow.
Try Changes:
Change fragment parent layout to Frame Layout
Use Frame layout rather than
If you are able to see yellow color then start looking in the wrapped layout there may be some problem for sure.
Also Share some more code like recycler view Adapter's rows layout for better help.
1.Check import of Fragment of android.support.v4.app.Fragment
2.Use below code for replacing a fragment
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
return false;
}
May issue because of simple fragment and support fragment
There is issue with following code:
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Make sure you are using OnFragmentInteractionListener interface properly in all fragment.

Fragment becomes empty after Notification

I have an Activity which loads a Fragment using getFragmentManager() . The fragment is working perfecty until an android notification appears. After that, the fragment becomes empty.
This is my application after the activity has loaded the fragment. The red square is the fragment.
Here, a external notification arrives to the mobile:
Only the fragment becomes empty:
Here my Activity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentSettings.OnFragmentInteractionListener{
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (fragmentManager == null) {
fragmentManager = getSupportFragmentManager();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (id == R.id.nav_locker_room) {
fragmentNameSection = "FragmentLockerRoom";
fragment = FragmentLockerRoom.newInstance(user, "");
}
fragmentManager.beginTransaction().replace(R.id.flContent, fragment, fragmentNameSection).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onResume() {
super.onResume();
}
}
Here the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/side_nav_menu"
app:itemTextColor="#android:color/white"
app:itemIconTint="#android:color/white"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
And finally this is my Fragment:
public class FragmentSettings extends Fragment {
private static final String ARG_USER = "user";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
getUser user;
View v;
DatabaseManager db;
private OnFragmentInteractionListener mListener;
ToggleButton notificationTrain, notificationNextMatch, liveSounds;
LayoutInflater inflater;
ViewGroup container;
FragmentSettings fragmentSettings;
public FragmentSettings() {
}
public static FragmentSettings newInstance(getUser user, String param2) {
FragmentSettings fragment = new FragmentSettings();
Bundle args = new Bundle();
args.putSerializable(ARG_USER, user);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
user = (com.androidsrc.futbolin.communications.http.auth.get.getUser) getArguments().getSerializable(ARG_USER);
mParam2 = getArguments().getString(ARG_PARAM2);
}
this.fragmentSettings = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
this.inflater = inflater;
this.container = container;
buildLayout();
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void buildLayout(){
db = new DatabaseManager(getActivity());
v = inflater.inflate(R.layout.fragment_fragment_settings, container, false);
notificationTrain = v.findViewById(R.id.fragment_settings_notification_trainment_toggle);
notificationNextMatch = v.findViewById(R.id.fragment_settings_notification_next_match_toggle);
liveSounds = v.findViewById(R.id.fragment_settings_notification_live_sounds_toggle);
notificationTrain.setChecked(db.findNotification().isTrainActive());
notificationNextMatch.setChecked(db.findNotification().isMatchActive());
liveSounds.setChecked(db.findNotification().isLiveSoundsActive());
Log.e("notif",db.findNotification().toString());
notificationTrain.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
if(db == null){
db = new DatabaseManager(getActivity());
}
Notification notification = db.findNotification();
notification.setTrainActive(isChecked);
db.saveNotification(notification);
}
}) ;
notificationNextMatch.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
if(db == null){
db = new DatabaseManager(getActivity());
}
Notification notification = db.findNotification();
notification.setMatchActive(isChecked);
db.saveNotification(notification);
}
}) ;
liveSounds.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
if(db == null){
db = new DatabaseManager(getActivity());
}
Notification notification = db.findNotification();
notification.setLiveSoundsActive(isChecked);
db.saveNotification(notification);
}
}) ;
}
}
And the layout of my Fragment is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ScrollView
android:id="#+id/fragment_locker_room_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="60dp"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/fragment_locker_room_total_constraint_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<!--
REST OF VIEWS
-->
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</LinearLayout>
Finally I found the solution. And ScrollView that has a layout_height="match_parent" when a notification is received changes his layout_height to 0.
Changing layout_height="match_parent" to layout_height="wrap_content" in ScrollView solves the issue.

How to set visibility of RelativeLayout in Adapter from Fragment

I want to set the visibility of my relativelayout from my fragment using my adapter see the image below
HERE IS MY FRAGMENT
I declare relativeLayout to public so i can access it on my adapter to set its visibility but i always get an null error
How i can set the relativelayout visibility to visible when i click my checkbox. Please help me. Thanks a lot.
public class FoodListFragment extends Fragment {
// 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";
public RelativeLayout relativeLayout;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Food_RecyclerAdapter adapter;
private List<Food> foods;
private ApiInterface apiInterface;
ProgressBar progressBar;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FoodListFragment() {
// Required empty public constructor
}
/**
* 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 FoodListFragment.
*/
// TODO: Rename and change types and number of parameters
public static FoodListFragment newInstance(String param1, String param2) {
FoodListFragment fragment = new FoodListFragment();
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);
setHasOptionsMenu(true);
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_food_list, container, false);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
recyclerView = (RecyclerView)view.findViewById(R.id.recycleViewFood);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
relativeLayout = (RelativeLayout)view.findViewById(R.id.cart_add);
relativeLayout.setVisibility(View.GONE);
apiInterface = ApiClient.getClient().create(ApiInterface.class);
progressBar = (ProgressBar)view.findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
Bundle bundle = this.getArguments();
String category_id = bundle.getString("menu_id");
Call<List<Food>> call = apiInterface.getFoodList(category_id);
call.enqueue(new Callback<List<Food>>() {
#Override
public void onResponse(Call<List<Food>> call, Response<List<Food>> response) {
foods = response.body();
adapter = new Food_RecyclerAdapter(getContext(),foods);
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<List<Food>> call, Throwable t) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
}
});
EditText searhText = (EditText)view.findViewById(R.id.search_food);
searhText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getfilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
HERE IS MY ADAPTER
public class Food_RecyclerAdapter extends RecyclerView.Adapter<Food_RecyclerAdapter.myViewHolder>{
Context context;
public List<Food> foods;
public List<Food> mOriginalValues;
public List<Food> mDisplayedValues;
ApiClient apiClient;
FoodListFragment foodListFragment;
public Food_RecyclerAdapter(Context context,List<Food> foods){
this.context = context;
this.foods = foods;
this.mOriginalValues = foods;
this.mDisplayedValues = foods;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_list_row,parent,false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(final myViewHolder holder, int position) {
apiClient = new ApiClient();
Picasso.with(context).load(apiClient.BASE_URL + foods.get(position).getImage()).into(holder.food_image);
holder.food_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.food_check.isChecked()){
//HERE I WANT TO SHOW THE RELATIVE LAYOUT WHEN I CLICK MY CHECKBOX
foodlistFragment = new FoodListFragment();
foodListFragment.relativeLayout.setVisibility(View.VISIBLE);
}else{
holder.food_qty.setText(""+0);
}
}
});
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return foods.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
TextView food_price,food_availability,food_qty;
ImageView food_image,remove_image,add_image;
CheckBox food_check;
public myViewHolder(View itemView) {
super(itemView);
food_check = (CheckBox) itemView.findViewById(R.id.radioFood_name);
food_image = (ImageView)itemView.findViewById(R.id.food_image);
food_availability = (TextView) itemView.findViewById(R.id.food_availability);
food_price = (TextView) itemView.findViewById(R.id.food_price);
food_qty = (TextView) itemView.findViewById(R.id.food_qty);
add_image = (ImageView)itemView.findViewById(R.id.add_image);
remove_image = (ImageView)itemView.findViewById(R.id.remove_image);
}
}
}
Here is the XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.jampol.blogs.FoodListFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/search_food"
android:drawableStart="#drawable/ic_search"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:drawablePadding="10dp"
android:hint="Search.."
android:gravity="center_vertical"
android:textSize="18dp"
android:background="#color/colorPrimary"
android:textColorHint="#color/white"
android:textColor="#color/white"
/>
<ProgressBar
android:id="#+id/progress_bar"
style="?android:progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerInParent="true"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleViewFood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:layout_below="#+id/search_food"
android:layout_alignParentStart="true"
android:layout_above="#+id/cart_add">
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cart_add"
android:layout_alignParentBottom="true"
android:padding="5dp"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total"
android:textSize="16dp"
android:paddingRight="10dp"
android:layout_centerVertical="true"
android:textStyle="bold"
android:id="#+id/total"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/total"
android:text="100000"
android:textSize="16dp"
android:layout_centerVertical="true"
android:textStyle="bold"
/>
<Button
android:layout_width="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#color/red"
android:textColor="#color/white"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:text="Add to cart" />
</RelativeLayout>
Hope this will help you.
You do not need to pass fragment's object in your adapter nor you need to define Relativelayout in your fragment as a public.
Follow this steps it may be lengthy but you can achieve your desire result :
Just pass your activity of fragment as a context in your adapter.
Like this :
adapter = new Food_RecyclerAdapter(getActivity(),foods);
Then in your adapter where you want to show or hide your views do something
like this:
Cast your context to your fragment's activity. Let's your fragment is inside
your MainActivity. So this would be :
MainActivity mActivity = ((MainActivity)context);
Make a public method in your MainActivity and getCurrentFragment of your
activity something like this:
public void showHideViews(){
Fragment currentFragment = getActiveFragment();
if(currentFragment != null){
//Access public method of your fragment from here
((FoodListFragment)currentFragment).showHideViews();
}
}
Make showHideViews() method in your FoodListFragment :
public void showHideViews(){
yourRelativeLayout.setVisibility(View.GONE);
}
First time it looks lengthy but this will be convenient.
Hope it helps you.
you need to pass a listener to your fragment like this:
in your adapter:
private MyClickListener clickListener;
interface MyClickListener{
void onClick(View v, int position);
}
public void setOnMyClickListener(MyClickListener clickListener){
this.clickListener = clickListener;
}
in your holder.food_check onClick:
if(clickListener != null){
clickListener.onClick(v,position);
}
in your fragment(when create adapter):
adapter.setOnMyClickListener(new Food_RecyclerAdapter.MyClickListener()
{
#Override
public void onClick(View v,int position) {
relativeLayout.setVisibility(View.VISIBLE);//or gone
}
});
Your foodListFragment object is not initialized in adapter class. it is null and you are trying to call foodListFragment.relativeLayout.setVisibility(View.VISIBLE); on checkbox click listener in adapter.
So pass foodListFragment reference from Fragment to Adapter class and in adapter class constructor make sure it is initialized.

CardView not appearing on RecyclerView

I am relatively new to android development and I have created an application that fetches data from the database(MySQL) and (should) display on a card loaded within a fragment in android. All my java classes do not show any errors but when I launch the application the card does not inflate within the RecyclerView.
The following are some of the solutions I have tried to no avail:
CardView not shown in RecyclerView,
Android MySQL Tutorial to Perform Basic CRUD Operation How to implement RecyclerView with CardView rows in a Fragment with TabLayout
Any help would be appreciated.
Fragment Containing the class I'm using:
public class bloodBanks extends Fragment {
private RecyclerView recylerView;
private MyAdapter adapter;
private List<MyData>data_List;
private OnFragmentInteractionListener mListener;
public bloodBanks() {
// Required empty public constructor
}
/**
* 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 bloodBanks.
*/
// TODO: Rename and change types and number of parameters
public static bloodBanks newInstance(String param1, String param2) {
bloodBanks fragment = new bloodBanks();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_blood_banks, container, false);
//perform(v);
recylerView=(RecyclerView) v.findViewById(R.id.recyle);
recylerView.setHasFixedSize(true);
data_List = new ArrayList<>();
adapter=new MyAdapter(getActivity(),data_List);
recylerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recylerView.setLayoutManager(llm);
load_data_from_server(0);
return v;
}
private void load_data_from_server(final int id) {
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
OkHttpClient client= new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.137.1:81/card.php?id="+id)
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0;i<array.length();i++){
JSONObject object=array.getJSONObject(i);
MyData data=new MyData(object.getInt("id"),object.getString("hospName"),object.getString("contact"));
data_List.add(data);
}
} catch(IOException e){
e.printStackTrace();
}catch (JSONException e){
System.out.println("No More Hospitals");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
My adapter Class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private Context context;
private List<MyData> my_data;
public MyAdapter(Context context, List<MyData> my_data) {
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cards,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.hospName.setText(my_data.get(position).getHospName());
holder.contact.setText(my_data.get(position).getContact());
}
#Override
public int getItemCount() {
return my_data.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView hospName;
public TextView contact;
public ViewHolder(View itemView){
super(itemView);
hospName=(TextView) itemView.findViewById(R.id.hosp);
contact=(TextView) itemView.findViewById(R.id.contact);
}
}
}
Data definitions:
public class MyData {
private int id;
private String hospName,contact;
public MyData(int id, String hospName, String contact) {
this.id = id;
this.hospName = hospName;
this.contact = contact;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getHospName() {
return hospName;
}
public void setHospName(String hospName) {
this.hospName = hospName;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
}
Cards.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cdBanks"
android:layout_width="329dp"
android:layout_height="137dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent">
<RelativeLayout
android:layout_width="337dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/hospPhoto"
android:layout_width="148dp"
android:layout_height="wrap_content"
android:src="#drawable/contacts_icon" />
<TextView
android:id="#+id/hosp"
android:layout_width="195dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/hospPhoto"
android:textSize="26sp"
tools:layout_editor_absoluteX="256dp"
tools:layout_editor_absoluteY="16dp" />
<TextView
android:id="#+id/contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/hosp"
android:layout_toRightOf="#+id/hospPhoto" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/contact"
android:layout_toRightOf="#+id/hospPhoto"
android:text="Blood Units: " />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
fragment_blood_banks.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:context="layout.bloodBanks">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardUSeCompatPadding="true"
card_view:cardElevation="5dp"
card_view:cardCornerRadius="5dp"
android:scrollbars="vertical"
android:layout_marginRight="6dp"
android:layout_marginLeft="6dp"
android:layout_marginTop="6dp"
/>
</android.support.constraint.ConstraintLayout>
In adapter's xml put your whole layout in CardView....
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="#color/color"
android:id="#+id/cv1"
card_view:cardElevation="3.5dp"
card_view:cardBackgroundColor="#fff"
card_view:cardCornerRadius="3dp"
android:foreground="?android:attr/selectableItemBackground"
xmlns:android="http://schemas.android.com/apk/res/android">
<put your whole layout here....>
</android.support.v7.widget.CardView>
</LinearLayout>

Calling Adapter from Fragments in ViewPager

I have Fragment which have a searchview and viewpager . My viewpager has 3 fragments and each fragment calling adapter . Now to implement searchview , i need to call adapter of visible fragment in view pager .
SlidingTab(Fragment with searchview and ViewPager):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.RareMediaCompany.BDTrial.SlidingTab">
<include
android:id="#+id/toolbar1"
layout="#layout/toolbar_job" />
<com.RareMediaCompany.BDTrial.Utils.CustomTabLayout
android:id="#+id/sliding_tabs"
style="#style/CustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee"
app:tabIndicatorColor="#f39220"
app:tabIndicatorHeight="3dp"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
app:tabPaddingEnd="0dp"
app:tabPaddingStart="0dp"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabSelectedTextColor="#808080" />
<LinearLayout
android:id="#+id/linear1"
android:background="#android:color/white"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:weightSum="1">
<android.support.v7.widget.SearchView
android:layout_width="300dp"
android:layout_height="45dp"
android:id="#+id/searchView"
android:layout_weight="0.9"
android:layout_marginRight="5dp"
android:layout_gravity="center"
style="#style/CitySearchView"
android:background="#drawable/searchview"
android:layout_marginLeft="10dp"/>
<LinearLayout
android:id="#+id/list_linearlayout"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_weight="0"
android:layout_gravity="center"
android:background="#f39220">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="0.3"
android:src="#drawable/list_icon_white"/>
</LinearLayout>
<LinearLayout
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_weight="0"
android:layout_marginRight="10dp"
android:background="#75aadb">
<ImageView
android:layout_width="20dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginRight="2dp"
android:layout_weight="0.3"
android:src="#drawable/mapmarker"/>
</LinearLayout>
</LinearLayout>
<!--android:layout_width="320dp"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_marginLeft="10dp"-->
<!--android:layout_marginTop="10dp"-->
<!--android:id="#+id/searchview"/>-->
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
SlidingTab.class (Implementing SearchView)
public class SlidingTab extends Fragment {
private static final String TAG = "TabLayout";
private static String POSITION = "POSITION";
private Context context;
private SearchView searchview;
private Toolbar toolbar ;
/*searching/filteration query*/
private SearchView.OnQueryTextListener OnQuerySearchView = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
// if (searchCheck) {
Log.i("Recycler query", arg0);
// Fragment frag = new PageAdapter(getChildFragmentManager(),context).getItem(viewPager.getCurrentItem());
PageAdapter adapter = ((PageAdapter) viewPager.getAdapter());
Fragment fragment = adapter.getFragment(viewPager.getCurrentItem());
return false;
}
};
public SlidingTab() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sliding_tab, container, false);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(new PageAdapter(getChildFragmentManager(), context));
slidingTab = (TabLayout) v.findViewById(R.id.sliding_tabs);
searchview = (SearchView)v.findViewById(R.id.searchView);
searchview.setOnQueryTextListener(OnQuerySearchView);
return v;
}
PageAdapter.class
public class PageAdapter extends FragmentStatePagerAdapter {
private static final String TAG = "PageAdapter";
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"New", "In Progress", "Completed"};
private Context context;
public PageAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
Log.d(TAG, "New Instance Created :" + position);
switch (position) {
case 0:
return new JobFragment();
case 1:
return new InProgressJobFragment();
case 2:
return new CompletedJobFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
Fragment RecyclerView Adapter (Call by each fragment in view pager and have searchview filter method)
public class JobAdapter extends RecyclerView.Adapter<JobAdapter.ViewHolder> {
private static final String TAG = "EMPLOYEE ADAPTER";
private static final int VIEW_NORMAL = 0;
private ArrayList<Info> mDataset;
private ArrayList<Info> filterList;
private Context mAct;
public class ViewHolder extends RecyclerView.ViewHolder {
}
}
public void addApplications(ArrayList<Info> candidates) {
}
public void clearApplications() {
}
public JobAdapter(ArrayList<Info> myDataset, Context context) {
this.mDataset = myDataset;
this.mAct = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.job_card_new, parent, false);
ViewHolder fh = new ViewHolder(v);
return fh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// }
**// *searching/filtration on List*/**
public void filter(String charText) {
filterList.clear();
if (charText.length() == 0) {
if(mDataset != null) {
filterList.addAll(mDataset);
}
} else {
if (mDataset != null){
for (Info wp : mDataset) {
if(wp.jobNumber !=null){
if(Pattern.compile(Pattern.quote(charText), Pattern.CASE_INSENSITIVE).matcher(wp.jobNumber).find()){
// if (wp.heading1.toLowerCase().contains(charText.toLowerCase())) {
filterList.add(wp);
}}else{
}
this.notifyItemRangeRemoved(0, filterList.size());
}
}
}
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
Please help me in implementing searchview in viewpager .
With help of uploaded code
I can tell that
make method in your fragments named search and
call adapter filter method
public void search(String text)
{
adapter.filter(text)
}
you can check instance of fragment and call search method of fragment after this line
Fragment fragment = adapter.getFragment(viewPager.getCurrentItem());
I think the best design for this is to use the Activity as the central "hub" for events that need to go the fragments.
So this is how I would do this:
First start with a listener interface. This can be declared as an inner interface of the Activity:
static interface QueryListener {
void onQueryChange(String query);
}
Activity gets properties for holding listeners and methods for adding and removing listeners (declared synchronized to prevent those pesky ConcurrentModificationExceptions:
private List<QueryListener> mQueryListeners = new ArrayList<>();
public synchronized void addQueryListener(#NonNull QueryListener listener) {
// check if the listener was already added
// you could also use a Set instead of a List for this
if (mQueryListeners.contains(listener)) return;
mQueryListeners.add(listener);
}
public synchronized void removeQueryListener(#NonNull QueryListener listener) {
mQueryListeners.remove(listener);
}
Activity also gets a method that can be called by the fragment with the SearchView:
public synchronized void changeQuery(String query) {
for (QueryListener listener : mQueryListeners) {
listener.onQueryChange(query);
}
}
Now your fragments with the adapters need to implement QueryListener and register/unregister themselves:
Add this line somewhere in onCreate():
((YourActivity) getActivity()).addQueryListener(this);
Unregister in onDestroy():
#Override
public void onDestroy() {
((YourActivity) getActivity()).removeQueryListener(this);
super.onDestroy();
}
add the QueryListener method implementation:
#Override
public void onQueryChange(String query) {
// if (isVisible()) { if desired
mAdapter.filter(query);
}
Note: You don't have to have the fragment implement QueryListener; you can use an anonymous class. But you'll have to hold the reference to it so you can call removeQueryListener() with it later.
Now just hook up the SearchView:
#Override
public boolean onQueryTextChange(String query) {
((YourActivity) getActivity()).changeQuery(query);
}
Another pattern I've used is to create a dedicated class for registering/notifying listeners. I create a single instance of this class and have a method on the Activity to access it:
QueryHandler handler = ((YourActivity) getActivity()).getQueryHandler();
// QueryHandler has all the listener properties and methods shown for the Activity
...
handler.changeQuery(query);
Alternatively, you can also use one of the many open-source event bus packages like Otto to pass events amongst your fragments.

Categories

Resources