Android RecyclerView adapter with fragment null pointer exception - android

Hi I am new to Android and get a problem with Recycler View and fragment.
There are 3 fragments that can swipe, and there is a recycler view with an adapter that is in the fragment. I got a sample code from http://developer.android.com/training/implementing-navigation/lateral.html but I get null pointer exception in List object. Thanks in advance. My code is showed below:
public class TripHistoryActivity extends FragmentActivity implements ActionBar.TabListener{
private static final String TAG = "TripHistoryActivity";
private CommonDBHelper commonDBHelper;
private List<Trip> allTrips;
private ArrayList<Trip> currentTrips;
private ArrayList<Trip> pastTrips;
private ArrayList<Trip> futureTrips;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trip_history);
commonDBHelper = new CommonDBHelper(this);
TripDBHelper tripDBHelper = new TripDBHelper(commonDBHelper.getWritableDatabase());
allTrips = tripDBHelper.getAllTrips();
currentTrips = new ArrayList<>();
pastTrips = new ArrayList<>();
futureTrips = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(calendar.DAY_OF_MONTH);
int currentMonth = calendar.get(calendar.MONTH);
int currentYear = calendar.get(calendar.YEAR);
for (Trip trip : allTrips) {
String date = trip.getTime().substring(0, trip.getTime().indexOf(" "));
String[] dates = date.split("/");
if (currentYear < Integer.valueOf(dates[2])) {
futureTrips.add(trip);
}
else if (currentYear > Integer.valueOf(dates[2])
|| currentMonth > Integer.valueOf(dates[0])
|| currentDay > Integer.valueOf(dates[1])) {
pastTrips.add(trip);
}
else {
currentTrips.add(trip);
}
}
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i) {
switch (i) {
case 0:
android.support.v4.app.Fragment currentTripsFragment = new CurrentTripsFragment();
Bundle currentTripsBundle = new Bundle();
currentTripsBundle.putParcelableArrayList("currentTrips", currentTrips);
currentTripsFragment.setArguments(currentTripsBundle);
return currentTripsFragment;
case 1:
android.support.v4.app.Fragment pastTripsFragment = new PastTripsFragment();
Bundle pastTripsBundle = new Bundle();
pastTripsBundle.putParcelableArrayList("pastTrips", pastTrips);
pastTripsFragment.setArguments(pastTripsBundle);
return pastTripsFragment;
default:
android.support.v4.app.Fragment futureTripsFragment = new FutureTripsFragment();
Bundle futureTripsBundle = new Bundle();
futureTripsBundle.putParcelableArrayList("futureTrips", futureTrips);
futureTripsFragment.setArguments(futureTripsBundle);
return futureTripsFragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Current Trips";
case 1:
return "Past Trips";
case 2:
return "Future Trips";
default:
return "Fault";
}
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class CurrentTripsFragment extends android.support.v4.app.Fragment {
private RecyclerView mRecyclerView;
private Context context;
List<Trip> currentTrips;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_current_trips, container, false);
context = rootView.getContext();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
currentTrips = getArguments().getParcelableArrayList("currentTrips");
Log.d(TripHistoryActivity.TAG, String.valueOf(currentTrips == null));
RecyclerView.LayoutManager manager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
CardViewAdapter cardViewAdapter = new CardViewAdapter(currentTrips);
mRecyclerView.setAdapter(cardViewAdapter);
cardViewAdapter.setOnItemClick(new CardViewAdapter.OnItemClick() {
#Override
public void onItemClick(int position) {
handleItemClick(position);
}
});
return rootView;
}
public void handleItemClick (int position) {
Toast.makeText(context, "Clicked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ViewTripActivity.class);
intent.putExtra("trip", currentTrips.get(position));
startActivity(intent);
}
}
There are 2 other fragments that are same as this one so I omit them.
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.nyu.cs9033.eta.R;
import com.nyu.cs9033.eta.models.Trip;
import java.util.List;
/**
* Created by Ray on 2016/4/2.
*/
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.CardViewHolder> {
private final List<Trip> trips;
public CardViewAdapter (List<Trip> trips) {
this.trips = trips;
}
public interface OnItemClick {
public void onItemClick(int position);
}
private OnItemClick onItemClick;
public void setOnItemClick (OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_list_item, parent, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(final CardViewHolder holder, final int position) {
holder.name.setText(trips.get(position).getName());
holder.location.setText(trips.get(position).getLocation());
holder.time.setText(trips.get(position).getTime());
if (onItemClick != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onItemClick(position);
}
});
}
}
#Override
public int getItemCount() {
return trips.size();
}
class CardViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private TextView location;
private TextView time;
public CardViewHolder (View view) {
super(view);
name = (TextView) view.findViewById(R.id.card_trip_name);
location = (TextView) view.findViewById(R.id.card_trip_location);
time = (TextView) view.findViewById(R.id.card_trip_time);
}
}
}
This is what logcat says:
FATAL EXCEPTION: mainProcess: com.nyu.cs9033.eta, PID: 14018
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()'
on a null object reference
at com.nyu.cs9033.eta.adapters.CardViewAdapter.getItemCount(CardViewAdapter.java: 57)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java: 2357)
at android.view.View.measure(View.java: 18796)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java: 715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java: 461)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java: 194)
at android.view.View.measure(View.java: 18796)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java: 1488)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java: 194)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java: 446)
at android.view.View.measure(View.java: 18796)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java: 5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java: 194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java: 2643)
at android.view.View.measure(View.java: 18796)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java: 2108)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java: 1224)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java: 1460)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java: 1115)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java: 6023)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java: 858)
at android.view.Choreographer.doCallbacks(Choreographer.java: 670)
at android.view.Choreographer.doFrame(Choreographer.java: 606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java: 844)
at android.os.Handler.handleCallback(Handler.java: 739)
at android.os.Handler.dispatchMessage(Handler.java: 95)
at android.os.Looper.loop(Looper.java: 148)
at android.app.ActivityThread.main(ActivityThread.java: 5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 616)

You should get bundle from onCreate() instead of onCreateView(). Try the below change in your Fragment class:
public static class CurrentTripsFragment extends android.support.v4.app.Fragment {
private RecyclerView mRecyclerView;
private Context context;
List<Trip> currentTrips;
#Override
public void onCreate(Bundle savedInstanceState){
super().onCreate(savedInstanceState);
if(getArguments()!= null){
currentTrips = getArguments().getParcelableArrayList("currentTrips");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_current_trips, container, false);
context = rootView.getContext();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
Log.d(TripHistoryActivity.TAG, String.valueOf(currentTrips == null));
RecyclerView.LayoutManager manager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
CardViewAdapter cardViewAdapter = new CardViewAdapter(currentTrips);
mRecyclerView.setAdapter(cardViewAdapter);
cardViewAdapter.setOnItemClick(new CardViewAdapter.OnItemClick() {
#Override
public void onItemClick(int position) {
handleItemClick(position);
}
});
return rootView;
}
public void handleItemClick (int position) {
Toast.makeText(context, "Clicked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ViewTripActivity.class);
intent.putExtra("trip", currentTrips.get(position));
startActivity(intent);
}
}

You are getting a null pointer exception on your list which you are using to show list items in recycler view...please check whether you are getting your data in the list or not...problem seems to be here:
CardViewAdapter cardViewAdapter = new CardViewAdapter(currentTrips);
and here:
currentTrips = getArguments().getParcelableArrayList("currentTrips");

Related

How to implement recyclerView in tabLayout with firebaseDatabase?

FragmentClass
public class BlankFragment extends Fragment {
//FragmentClass constructor with no parameter
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
**Inflating recyclerView with Dummy data i want to load data from firebase here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
//FInding recyclerViewByid
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
// i have added dummy data into adapter but want toadd data from firebaseDatabase into Myadapter
MyAdapter adapter = new MyAdapter(new String[] {
"test one", // i have hardcoded these data
"test two", // but i want data from firebase to go here
"test three",
"test four",
"test five",
"test six",
"test seven"
});
rv.setAdapter(adapter); //Setting adapter
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView; // returning rootView
}
}
MainActivity
#MainActivity contains 3TabLayouts
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private final String TAG = "SOMETHING";
private ImageView image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
//TabLayout
TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if (position == 1)
Log.d(TAG, "onTabSelected: "); //call some method
else if (position == 2)
Log.d(TAG, "onTabSelected: "); //call some method
else
Log.d(TAG, "onTabSelected: "); //call some method
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//SettingViewpagers
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] {
"NOTICE", // tab1 header
"FEED", // tab2 header
"RESULT" // tab3 header
};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
// 3 tab classes
want to load different data in all 3 tabs
all data should be loaded from firebase
switch (position) {
case 0:
return new BlankFragment(); //FragementClass 1
case 1:
return new BlankFragment(); //FragmentClass 2
case 2:
return new SomeFragment(); //FragmentClass 3
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
// inflate some value should inflate some custom view here
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
#Adapter class
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;
public class MyAdapter extends RecyclerView.Adapter < MyAdapter.MyViewHolder > {
private String[] mDataset;
private final static int FADE_DURATION = 1000;
public MyAdapter() {
}
// 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 static class MyViewHolder extends RecyclerView.ViewHolder {
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText((CharSequence) mDataset[position]);
setScaleAnimation(holder.mCardView);
// setFadeAnimation(holder.mTextView);
;
}
//adding simple scale animation to CardView
private void setScaleAnimation(View view) {
ScaleAnimation anim = new ScaleAnimation(0.0 f, 1.0 f, 0.0 f, 1.0 f, Animation.RELATIVE_TO_SELF, 0.5 f, Animation.RELATIVE_TO_SELF, 0.5 f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
//Adding Fade animation
private void setFadeAnimation(View view) {
AlphaAnimation anim = new AlphaAnimation(0.0 f, 1.0 f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}

Tablayout on swipe not refreshing in android

I am implementing tablayout using view pager and in my scenario I have two tab. In my first tab I have add data which store in share preference. and when I move to second tab then data should be retrieve from share preference and show in listview. When I add the data from my first tab then data is added successfully but not show in my second tab means I have to close my application and again restart the app so that I can see saved the detail which saved from my first tab.
Below is my Activity code.
public class FragmentExample extends AppCompatActivity {
private ViewPagerAdapter viewPagerAdapter;
#BindView(R.id.tabCountryState)
TabLayout tabCountryState;
#BindView(R.id.viewPager)
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_example);
ButterKnife.bind(this);
setViewPager();
setTabIcon();
viewPager.setOffscreenPageLimit(2);
tabCountryState.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.e("Current tab is ", "===> " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager() {
// set Adaapter.
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentExample.this);
viewPager.setAdapter(viewPagerAdapter);
tabCountryState.setupWithViewPager(viewPager);
}
// set custom icon to tab in Tablayout.
private void setTabIcon() {
// First Tab
View firstTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_first, null);
TextView tvFirsIcon = ButterKnife.findById(firstTab, R.id.tvFirsIcon);
tvFirsIcon.setText("First Tab");
tabCountryState.getTabAt(0).setCustomView(firstTab);
// First Tab
View secondTab = (View) LayoutInflater.from(this).inflate(R.layout.tab_icon_second, null);
TextView tvSecondIcon = ButterKnife.findById(secondTab, R.id.tvSecondIcon);
tvSecondIcon.setText("Second Tab");
tabCountryState.getTabAt(1).setCustomView(secondTab);
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private FirstFragment firstFragment;
private SecondFragment secondFragment;
public ViewPagerAdapter(FragmentManager fm, Context mainActivity) {
super(fm);
context = mainActivity;
new FirstFragment();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
firstFragment = new FirstFragment();
return firstFragment;
case 1:
secondFragment = new SecondFragment();
return secondFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return " " + position;
}
}
}
Here is my FirstFragment in which I have added the data into share preference.
public class FirstFragment extends Fragment {
private View v;
#BindView(R.id.btnSubmit)
Button btnSubmit;
#BindView(R.id.edtCityName)
EditText edtCityName;
#BindView(R.id.spStateName)
Spinner spStateName;
private Unbinder unbinder;
private ArrayList<String> alStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private SpinnerStateAdapter spinnerAdapter;
private int spinnerPosition;
private String strCityName, strSpinnerValue;
#OnClick(R.id.btnSubmit)
public void submit(View view) {
if (spinnerPosition !=0) {
strCityName = edtCityName.getText().toString().trim();
alAllStateCity = SessinoManager.getCityList(getActivity());
if (strCityName.length() > 0) {
alAllStateCity.get(spinnerPosition).getAlCityName().add(new CityStateModel(strCityName));
} else {
}
// Save new data to Session.
SessinoManager.saveCityList(getActivity(), alAllStateCity);
SecondFragment.cityAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "Detail saved successfully ", Toast.LENGTH_SHORT).show();
edtCityName.setText("");
} else {
Toast.makeText(getActivity(), "Please select state", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_first, container, false);
unbinder = ButterKnife.bind(this, v);
// arraylist checking if data is available into session.
if(SessinoManager.getCityList(getActivity()).size()>0){
Log.e("First fragment "," if condition ");
alAllStateCity = SessinoManager.getCityList(getActivity());
alStateName = new ArrayList<>();
for(int i=0;i<alAllStateCity.size();i++){
alStateName.add(alAllStateCity.get(i).getStrStateName());
}
setStateSpinner();
}else{
loadArraylist();
setStateSpinner();
}
return v;
}
private void setStateSpinner() {
spStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
strSpinnerValue = alStateName.get(i).toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinnerAdapter = new SpinnerStateAdapter(getActivity(), alStateName);
spStateName.setAdapter(spinnerAdapter);
}
private void loadArraylist() {
alAllStateCity = new ArrayList<>();
alStateName = new ArrayList<>();
alStateName.add(0, "Select State");
alStateName.add("Gujarat");
alStateName.add("Maharashtra");
alStateName.add("Madhya Pradesh");
for (int i = 0; i < alStateName.size(); i++) {
alAllStateCity.add(new AllStateCityModel(alStateName.get(i), alAllStateCity.size(), new ArrayList<CityStateModel>()));
}
SessinoManager.saveCityList(getActivity(), alAllStateCity);
}
#Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
Log.e("First fragment "," on destroy");
}
}
Here is my SecondFragment in which I have to get saved detail from Share preference.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}
And I am saving data into Share preference which is given below.
public class SessinoManager {
private static final String CITY_PREFERENCE = "city_preference";
// Save data to share preference.
public static void saveCityList(Context context, ArrayList<AllStateCityModel> alAllPlayList) {
try {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonUsers = gson.toJson(alAllPlayList);
editor.putString("all_play_list", jsonUsers);
editor.commit();
// Check to save data into share preferent
for(int j=0;j<alAllPlayList.size();j++){
Log.e("State name ","----------------------"+alAllPlayList.get(j).getStrStateName());
ArrayList<CityStateModel> cityName = alAllPlayList.get(j).getAlCityName();
for(int i=0;i<cityName.size();i++){
Log.e("cityName "," in session ==> "+cityName.get(i).getStrCity());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static ArrayList<AllStateCityModel> getCityList(Context context)
{
SharedPreferences settings;
List<AllStateCityModel> users = new ArrayList<>();
settings = context.getSharedPreferences(CITY_PREFERENCE,Context.MODE_PRIVATE);
if (settings.contains("all_play_list"))
{
String jsonUsers = settings.getString("all_play_list", null);
Gson gson = new Gson();
AllStateCityModel[] userItems = gson.fromJson(jsonUsers,AllStateCityModel[].class);
users = Arrays.asList(userItems);
users= new ArrayList<AllStateCityModel>(users);
}
return (ArrayList<AllStateCityModel>) users;
}
}
When I add new city detail into first tab then data is data successfully but when I swipe or move to next then data is not displaying and I have to restart whole application to get updated data from Share preference. Kindly help me to resolve this issue. Thanks in advance.
I have resolved the problem by implementing below method setUserVisibleHint.
public class SecondFragment extends Fragment {
private View v;
private Unbinder unbinder;
#BindView(R.id.lvCityList)
ListView lvCityList;
#BindView(R.id.spinnerStateName)
Spinner spinnerStateName;
private ArrayList<AllStateCityModel> alAllStateCity;
private ArrayList<CityStateModel> alCityName;
private ArrayList<String> alStateName;
private int spinnerPosition;
private SpinnerStateAdapter spinnerAdapter;
private ArrayList<String> alCity;
public static CityAdapter cityAdapter;
private Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
v = inflater.inflate(R.layout.fragment_two, container, false);
unbinder = ButterKnife.bind(this, v);
context = getActivity();
loadArrayList(context);
// Log.e("onCreateView", "onCreateView");
return v;
}
private void loadArrayList(Context context) {
alCityName = new ArrayList<>();
alStateName = new ArrayList<>();
alAllStateCity = SessinoManager.getCityList(context);
for (int j = 0; j < alAllStateCity.size(); j++) {
// Log.e("State name "," =========================> "+allPlayList.get(j).getStrStateName());
// get state name from session
alStateName.add(alAllStateCity.get(j).getStrStateName());
setSpinner(context);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e("setUserVisibleHint","setUserVisibleHint "+isVisibleToUser);
if(isVisibleToUser==true){
loadArrayList(context);
}
}
#Override
public boolean getUserVisibleHint() {
Log.e("getUserVisibleHint","getUserVisibleHint "+super.getUserVisibleHint());
return super.getUserVisibleHint();
}
private void setSpinner(Context context) {
spinnerAdapter = new SpinnerStateAdapter(context, alStateName);
spinnerStateName.setAdapter(spinnerAdapter);
spinnerStateName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerPosition = i;
spinnerAdapter.notifyDataSetChanged();
setList(spinnerPosition);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setList(int position) {
alCityName = alAllStateCity.get(position).getAlCityName();
alCity = new ArrayList<>();
for (int i = 0; i < alCityName.size(); i++) {
// Log.e("City name "," !!!!!!!!!!!!!!!!"+alCityName.get(i).getStrCity());
alCity.add(alCityName.get(i).getStrCity());
}
cityAdapter = new CityAdapter(context, alCity);
lvCityList.setAdapter(cityAdapter);
cityAdapter.notifyDataSetChanged();
}
}

How to pass value from activity to fragment through view pager

I have an activity which uses view pager to switch between fragments. I have three fragments. While switching between these fragments i have to pass a string value to the fragment class to identify which fragment is selected.Because here I am using same fragment class for all the three fragments.
Here is my main activity.
public class mainActivity extends AppCompatActivity {
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
here is my fragment class
public class RemainderFragment extends Fragment {
public RemainderEmailFragment() {
// Required empty public constructor
}
#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
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}
I have tried intents and shared preferences to send data. but nothing worked. I have to get the String value in my fragment class. please help.
Please check the below code for sample required changes, I have modified your file and added some code to support your requirement.
Your Activity file
package com.adobe.reader.test;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.adobe.reader.R;
public class mainActivity extends AppCompatActivity
{
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
// Adding adapter
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// Let's say we need to call some method from fragment in the activity
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
remainderFragment.setString("Testing string");
}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
}
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
remainderFragment.setString(value);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* This method will give you current fragment used in the viewpager.
* #return
*/
public Fragment getCurrentFragment()
{
Fragment fragment = null;
if (viewPager != null)
{
int currentFragmentIndex = viewPager.getCurrentItem();
if (adapter != null)
{
fragment = adapter.getItem(currentFragmentIndex);
}
}
return fragment;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Your Fragment file
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.adobe.reader.R;
public class RemainderFragment extends Fragment
{
public String testingString;
public RemainderEmailFragment() {
// Required empty public constructor
}
// Sample method to be called from activity
public void setString(String testStr)
{
testingString = testStr;
}
#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
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}

Sending data from activity to fragment using set methods

I've posted a question regarding of passing data from activity to a fragment. And I've learnt that implementing Parcelable to a POJO class is a right way of doing it. After some research I also understand that in order to pass data to a fragment should use Bundle instead of Intent.
My previous question -->
Using same fragments but different content in Android
But now, my question is, what should I do in order to display a list of details (name, address, phone) using set methods when the cardview is clicked?
To be clear, what I want is
When first restaurant is clicked, the new intent that contains details fragment will be started. Inside the details fragment, it will display the restaurant name, address and phone of the first restaurant.
Can anyone guide me by showing me the code of two set of different details when two different restaurant cardview is clicked?
RestaurantListAdapter.java
I want to use if else statement under onClick, to display different details when different cardview is clicked
public class RestaurantListAdapter extends RecyclerView.Adapter<RestaurantListAdapter.ViewHolder> {
List<RestaurantList_Item> items;
private static ClickListener clickListener;
private Context context;
public RestaurantListAdapter(){
super();
items = new ArrayList<RestaurantList_Item>();
// POSITION 1
RestaurantList_Item restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_anjappar);
restaurant.setrName("Anjappar Indian Chettinad Restaurant");
restaurant.setrCuisine("Indian");
items.add(restaurant);
// POSITION 2
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_morganfield);
restaurant.setrName("Morganfield");
restaurant.setrCuisine("Western");
items.add(restaurant);
// POSITION 3
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_nandos);
restaurant.setrName("Nando's");
restaurant.setrCuisine("Western");
items.add(restaurant);
// POSITION 4
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_shellout);
restaurant.setrName("Shellout");
restaurant.setrCuisine("Seafood");
items.add(restaurant);
// POSITION 5
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_beyond);
restaurant.setrName("Beyond Veggie");
restaurant.setrCuisine("Vegetarian");
items.add(restaurant);
// POSITION 6
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_myelephant);
restaurant.setrName("My Elephant");
restaurant.setrCuisine("Thai");
items.add(restaurant);
// POSITION 7
restaurant = new RestaurantList_Item();
restaurant.setrImage(R.mipmap.img_padangkota);
restaurant.setrName("Nasi Kandar Padang Kota");
restaurant.setrCuisine("Mamak");
items.add(restaurant);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.cardview_restaurant, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final RestaurantList_Item restaurant = items.get(position);
viewHolder.resImage.setImageResource(restaurant.getrImage());
viewHolder.restaurantName.setText(restaurant.getrName());
viewHolder.cuisine.setText(restaurant.getrCuisine());
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
// Toast.makeText(context, "Item clicked with position " +position, Toast.LENGTH_LONG).show();
if(position == 0){
Intent i = new Intent(context, Restaurant.class);
context.startActivity(i);
}
}
});
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView resImage;
public TextView restaurantName;
public TextView cuisine;
public ViewHolder(final View itemView) {
super(itemView);
resImage = (ImageView) itemView.findViewById(R.id.resImage);
restaurantName = (TextView) itemView.findViewById(R.id.restaurantName);
cuisine = (TextView) itemView.findViewById(R.id.cuisine);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener (ClickListener clickListener){
RestaurantListAdapter.clickListener = clickListener;
}
public interface ClickListener{
void onItemClick (int position, View v);
}
}
RestaurantModel.java
This is the POJO class that contains get set methods, I want to use the set methods to display restaurant details
public class RestaurantModel implements Parcelable{
//empty constructor
public RestaurantModel(){}
//A constructor that initializes the Restaurant object
public RestaurantModel(String resName, String resAddress, String resPhone, String resCuisine, String resPriceRange){
this.resName = resName;
this.resAddress =resAddress;
this.resPhone = resPhone;
this.resCuisine = resCuisine;
this.resPriceRange = resPriceRange;
}
//Parcelling the object
public RestaurantModel(Parcel in){
String[] data = new String [5];
in.readStringArray(data);
this.resName = data[0];
this.resAddress = data[1];
this.resPhone = data[2];
this.resCuisine = data[3];
this.resPriceRange = data[4];
}
// variable main photo
private int mainImage;
//variables for details fragment
private String resName, resAddress, resPhone, resCuisine, resPriceRange;
//variables for menu fragment
private int foodPhoto;
private String foodPrice, foodDescription;
/*get set methods*/
public int getMainImage(){
return mainImage;
}
public void setMainImage(int mainImage){
this.mainImage = mainImage;
}
public String getResName(){
return resName;
}
public void setResName(String resName){
this.resName = resName;
}
public String getResAddress(){return resAddress;}
public void setResAddress(String resAddress){this.resAddress = resAddress;}
public String getResPhone(){return resPhone;}
public void setResPhone(String resPhone){this.resPhone = resPhone;}
public String getResCuisine(){return resCuisine;}
public void setResCuisine(String resCuisine){this.resCuisine = resCuisine;}
public String getResPriceRange(){return resPriceRange;}
public void setResPriceRange(String resPriceRange){this.resPriceRange = resPriceRange;}
public int getFoodPhoto(){return foodPhoto;}
public void setFoodPhoto(int foodPhoto){this.foodPhoto = foodPhoto;}
public String getFoodDescription(){return foodDescription;}
public void setFoodDescription(String foodDescription){this.foodDescription = foodDescription;}
public String getFoodPrice(){return foodPrice;}
public void setFoodPrice(String foodPrice){this.foodPrice = foodPrice;}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[]{
this.resName,this.resAddress,this.resPhone, this.resCuisine, this.resPriceRange
});
}
// Creator
public static final Parcelable.Creator<RestaurantModel> CREATOR = new Parcelable.Creator<RestaurantModel>(){
#Override
public RestaurantModel createFromParcel(Parcel source) {
return new RestaurantModel(source);
}
#Override
public RestaurantModel[] newArray(int size) {
return new RestaurantModel[size];
}
};
}
Restaurant.java
This activity contains the fragments that will be shown when the cardview is clicked
public class Restaurant extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
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.addFragment(new details(), "Details");
adapter.addFragment(new menu(), "Menu");
adapter.addFragment(new tableBooking(), "Table booking");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager){
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment (Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
Details.java
This class extends fragment that contains restaurant details such as name, address and phone
public class details extends Fragment {
private TextView resName, resAddress, resPhone, resCuisine, resPriceRange;
public details() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* resName = (TextView) getView().findViewById (R.id.resName);
resAddress = (TextView) getView().findViewById (R.id.resAddress);
resPhone = (TextView) getView().findViewById (R.id.resPhone);
resCuisine = (TextView) getView().findViewById (R.id.resCuisine);
resPriceRange = (TextView) getView().findViewById (R.id.resPriceRange);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_details, container, false);
}
}
Homepage.java
public class Homepage extends Activity {
RecyclerView recyclerView;
RecyclerView.LayoutManager llm;
RecyclerView.Adapter adapter;
private static final String TAG = Homepage.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//super.onCreateDrawer(R.layout.activity_homepage);
setContentView(R.layout.activity_homepage);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(Homepage.this);
recyclerView.setLayoutManager(llm);
adapter = new RestaurantListAdapter();
recyclerView.setAdapter(adapter);
}
}
EDIT: I'm not sure if I'm doing this correctly. I created multiple arraylist that describes different details for different restaurant. I put the code at onClick methods in RestaurantListAdapter.
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final RestaurantList_Item restaurant = items.get(position);
viewHolder.resImage.setImageResource(restaurant.getrImage());
viewHolder.restaurantName.setText(restaurant.getrName());
viewHolder.cuisine.setText(restaurant.getrCuisine());
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
RestaurantModel rAnjappar = new RestaurantModel();
details fragment = new details();
Intent i = new Intent(context, Restaurant.class);
// Array List
ArrayList<RestaurantModel> a1 = new ArrayList<RestaurantModel>();
rAnjappar.setResName("Anjappar");
rAnjappar.setResAddress("Bandar Kinrara");
rAnjappar.setResPhone("03-80807362");
rAnjappar.setResCuisine("Mamak");
rAnjappar.setResPriceRange("RM 30 for 2 person");
ArrayList<RestaurantModel> a2 = new ArrayList<RestaurantModel>();
rAnjappar.setResName("Morganfield");
rAnjappar.setResAddress("Bandar Utama");
rAnjappar.setResPhone("03-80807362");
rAnjappar.setResCuisine("Western");
rAnjappar.setResPriceRange("RM 60 for 2 person");
// action when card view is clicked
if(position == 0){
Bundle b1 = new Bundle();
b1.putParcelableArrayList("anjappar", a1);
fragment.setArguments(b1);
context.startActivity(i);
}
}
});
}
If this is acceptable, next thing I should do is retrieve the bundle in my fragment code right? But since I will be having multiple bundles, how am I supposed to retrieve all the bundles in a correct way?
Ok so from as far as i understand you can do following things
1 Add this method in Adapter
public RestaurantList_Item getItem(int pos) {
return items.get(pos);
}
2. Homepage is your clicklistner activity (Hope so) in it
public void onItemClick(int position, view v) {
RestaurantList_Item row_object = adapter.getItem(position);
Intent i = new Intent(context, Restaurant.class);
i.putExtra(Common.Data_Object, row_object);
startActivity(i);
}
3. Replace code of Restaurant class
public class Restaurant extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private RestaurantList_Item row_object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
getIntentData(getIntent());
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void getIntentData(Intent i) {
if (i != null) {
row_object = i.getParcelableExtra(Common.Data_Object);
}
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
Fragment f = new details();
Bundle arguments = new Bundle();
arguments.putParcelable(Common.Data_Object, row_object);
f.setArguments(arguments);
adapter.addFragment(f, "Details");
adapter.addFragment(new menu(), "Menu");
adapter.addFragment(new tableBooking(), "Table booking");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager){
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment (Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
4. get object from bundle in Detail fragment
private void getIntentData(Bundle b)
{
if (b != null)
{
detailObject = b.getParcelable(Common.Data_Object);
}
}
Hope it will help.
You can use setArguments() method of the fragment to pass your restaurant model class to new fragment while creating the new instance of it.You can get it back using getArguments() in newly created fragment's onCreate() method. You have to make your resturantModel.java class Serializable.
public class RestaurantModel implements Serializable{
...
}
Add data:-
Bundle bundle = new Bundle();
bundle.putSerializable("restaurant", restaurant);
Fragment1 frag1 = new Fragment1();
frag1.setArguments(bundle);
Get data :-
RestauranModel restaurant = (RestauranModel) getArguments().getSerializable("restaurant");
FYI: Difference between Parcelable and Serializable : https://stackoverflow.com/a/3323554/4690731

How to enable CardView in ViewPager

I have tried using CardView in ViewPager and everytime I swipe left/right on CardView it goes to the next screen. I want the card to delete itself then. Currently as a standalone both are working fine but when I combine then only viewpager is working and not cardswipe dismiss.
I tried to disable ViewPager with the code below but this code also disables CardView swipe gestures. How can I make only CardView to have gesture and when you swipe in between 2 cards then its should have ViewPager as its not connected to card element.
Or disable ViewPager completely and use it as buttons and enable swipe on CardView. I really appreciate any help. Thanks in Advance.
FYI: I have tried android_horizontal_listview in ViewPager and that works fine and exactly like this.
For ViewPager:
mPager.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
For CardView:
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(mRecyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
mRecyclerView.addOnItemTouchListener(swipeTouchListener);
Mainactivity.java
public class MainActivity extends Activity implements ActionBar.TabListener {
ViewPager vp;
View viewpager_layout_1;
View viewpager_layout_2;
View viewpager_layout_3;
ActionBar.Tab tab_1;
ActionBar.Tab tab_2;
ActionBar.Tab tab_3;
ActionBar bar;
/////
String jsonstring1;
CardViewAdapter spinnerArray;
ImageLoader imageLoader = ImageLoader.getInstance();//
DisplayImageOptions options;
ArrayList<HashMap<String, String>> array_list1;
RecyclerView recyclerView;
RelativeLayout re1;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mContext = this;
viewpager_layout_1 = new View(mContext);
viewpager_layout_1 = getLayoutInflater().inflate(R.layout.sample1, null);
viewpager_layout_3 = new View(mContext);
viewpager_layout_3 = getLayoutInflater().inflate(R.layout.sample2, null);
viewpager_layout_2 = new View(mContext);
viewpager_layout_2 = getLayoutInflater().inflate(R.layout.sample3, null);
vp = (ViewPager) findViewById(R.id.vp);
bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
Vector<View> pages = new Vector<View>();
pages.add(viewpager_layout_1);
pages.add(viewpager_layout_3);
pages.add(viewpager_layout_2);
CustomPagerAdapter adapter = new CustomPagerAdapter(mContext, pages);
vp.setAdapter(adapter);
vp.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
bar.setSelectedNavigationItem(position);
}
});
tab_1 = bar.newTab();
tab_1.setCustomView(R.layout.tab_layout_1);
tab_1.setTabListener(this);
bar.addTab(tab_1);
tab_2 = bar.newTab();
tab_2.setCustomView(R.layout.tab_layout_2);
tab_2.setTabListener(this);
bar.addTab(tab_2);
tab_3 = bar.newTab();
tab_3.setCustomView(R.layout.tab_layout_3);
tab_3.setTabListener(this);
bar.addTab(tab_3);
////
imageLoader.init(ImageLoaderConfiguration.createDefault(MainActivity.this));
jsonstring1 = "[{\"category\":\"1\",\"no\":\"1\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/c/c3/Jordan_by_Lipofsky_16577.jpg\"},{\"category\":\"2\",\"no\":\"2\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Basketball_World_Cup_2014.jpg/800px-Basketball_World_Cup_2014.jpg\"},{\"category\":\"3\",\"no\":\"3\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/4/4e/Basketball_Goal.jpg\"},{\"category\":\"4\",\"no\":\"4\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/1/10/Basketball_through_hoop.jpg\"}]";
//////////
array_list1 = new ArrayList<HashMap<String, String>>();
JSONArray arr = null;
try {
arr = new JSONArray(jsonstring1);
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
String category = e1.getString("category").trim();
String no = e1.getString("no").trim();
String image = e1.getString("image").trim();
HashMap<String, String> map = new HashMap<String, String>();
map.put("category", category);
map.put("no", no);
map.put("image", image);
// adding HashList to ArrayList
array_list1.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OnItemTouchListener itemTouchListener = new OnItemTouchListener() {
#Override
public void onCardViewTap(View view, int position) {
Toast.makeText(MainActivity.this, "Tapped " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton1Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button1 in " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton2Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button2 in " + array_list1.get(position), Toast.LENGTH_SHORT).show();
}
};
spinnerArray = new CardViewAdapter(itemTouchListener, MainActivity.this, array_list1);
recyclerView = (RecyclerView) viewpager_layout_3.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
SlideInBottomAnimationAdapter alphaAdapter = new SlideInBottomAnimationAdapter(spinnerArray);
ScaleInAnimationAdapter alphaAdapter2 = new ScaleInAnimationAdapter(alphaAdapter);
final AlphaInAnimationAdapter alphaAdapter3 = new AlphaInAnimationAdapter(alphaAdapter2);
alphaAdapter3.setDuration(500);
alphaAdapter3.setFirstOnly(true);
recyclerView.setAdapter(alphaAdapter3);
final SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(recyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// mItems.remove(position);
Toast.makeText(MainActivity.this, array_list1.get(position) + " swiped left", Toast.LENGTH_SHORT).show();
array_list1.remove(position);
alphaAdapter3.notifyItemRemoved(position);
}
alphaAdapter3.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//
Toast.makeText(MainActivity.this, array_list1.get(position) + " swiped right", Toast.LENGTH_SHORT).show();
array_list1.remove(position);
alphaAdapter3.notifyItemRemoved(position);
}
alphaAdapter3.notifyDataSetChanged();
}
});
recyclerView.addOnItemTouchListener(swipeTouchListener);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
vp.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 2) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_2);
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_1);
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_33);
} else if (tab.getPosition() == 1) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_22);
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_1);
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_3);
} else if (tab.getPosition() == 0) {
tab_1.setCustomView(null);
tab_1.setCustomView(R.layout.tab_layout_11);
if (tab_2 != null) {
tab_2.setCustomView(null);
tab_2.setCustomView(R.layout.tab_layout_2);
}
if (tab_3 != null) {
tab_3.setCustomView(null);
tab_3.setCustomView(R.layout.tab_layout_3);
}
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Toast.makeText(getBaseContext(), tab.toString(), 5).show();
}
public interface OnItemTouchListener {
// this will disallow the touch request for parent scroll on touch of child view
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
public void onCardViewTap(View view, int position);
/**
* Callback invoked when the Button1 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton1Click(View view, int position);
/**
* Callback invoked when the Button2 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton2Click(View view, int position);
}
public class CustomPagerAdapter extends PagerAdapter {
private final Context mContext;
private final Vector<View> pages;
public CustomPagerAdapter(Context context, Vector<View> pages) {
this.mContext = context;
this.pages = pages;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View page = pages.get(position);
container.addView(page);
return page;
}
#Override
public int getCount() {
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
ArrayList<HashMap<String, String>> d;
Activity a;
private List<String> cards;
private OnItemTouchListener onItemTouchListener2;
public CardViewAdapter(OnItemTouchListener onItemTouchListener, Activity a, ArrayList<HashMap<String, String>> d) {
// this.cards = cards;
this.onItemTouchListener2 = onItemTouchListener;
this.a = a;
this.d = d;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
// viewHolder.title.setText(cards.get(i));
HashMap<String, String> item = d.get(i);
viewHolder.title.setText(item.get("category"));
imageLoader.displayImage(item.get("image"), viewHolder.im2);
}
#Override
public int getItemCount() {
// return d == null ? 0 : d.size();
return (null != d ? d.size() : 0);
// return d.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
MotionEvent motionEvent;
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
// private RecyclerView mRecyclerView;
private SwipeableRecyclerViewTouchListener.SwipeListener mSwipeListener;
// Transient properties
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
private int mDismissAnimationRefCount = 0;
private float mAlpha;
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private int mAnimatingPosition = ListView.INVALID_POSITION;
private View mDownView;
private boolean mPaused;
private float mFinalDelta;
///
private TextView title;
private Button button1;
private Button button2;
private ImageView im2;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.card_view_title);
im2 = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativelayout_1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:id="#+id/linearlayout_1"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
</RelativeLayout>
sample2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/re1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
To solve this issue I used an ItemTouchHelper provided by Android to easily swipe to delete an item from a RecyclerView.
Please see implementation below:
MainActivity:
Here I have the implementation of the ViewPager and it's child Fragments.
package za.co.gadgetgirl.testcardpager;
import android.os.Bundle;
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 java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
Frag1 frag1 = new Frag1();
Frag2 frag2 = new Frag2();
Frag3 frag3 = new Frag3();
adapter.addFragment(frag1, "frag1");
adapter.addFragment(frag2, "frag2");
adapter.addFragment(frag3, "frag3");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Frag1:
On this Fragment I have a RecyclerView that has an ItemTouchHelper attached. The ItemTouchHelper listens for the onSwiped(...) method that is defined in the SimpleCallback interface and I just remove the swiped item in this method.
package za.co.gadgetgirl.testcardpager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Frag1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1, container, false);
final RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
final RVAdapter rvAdapter = new RVAdapter(Person.initializeData());
rv.setAdapter(rvAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
rvAdapter.removeItem(viewHolder.getAdapterPosition());
}
});
itemTouchHelper.attachToRecyclerView(rv);
return v;
}
}
RVAdapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
//...implementation...
public void removeItem(int position) {
persons.remove(position);
notifyItemRemoved(position);
}
}
To use the ItemTouchHelper, you will need the appcompat-v7:22.2.0 dependency and above defined in your app gradle file.
I haven't use SwipeableRecyclerView before so I cannot really say much. I have a problem same as you before. I solve it by handling onTouch event of the base container of fragment (such as LinearLayout,RelativeLayout) and it work for me. Why don't you try this solution and get back to us
For the use case that you are describing, I don't think that ViewPager is the class that you want to use to get your swipe action. It seems to me that the combination of CoordinatorLayout and SwipeDismissBehavior is more appropriate.
EDIT:
See my solution below:
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CardView cardView = (CardView) findViewById(R.id.cardView);
SwipeDismissBehavior<CardView> behavior = new SwipeDismissBehavior();
behavior.setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_START_TO_END);
behavior.setListener(new SwipeDismissBehavior.OnDismissListener() {
#Override
public void onDismiss(View view) {
finish(); // close activity if desired
}
#Override
public void onDragStateChanged(int state) {
}
});
((CoordinatorLayout.LayoutParams) cardView.getLayoutParams()).setBehavior(behavior);
}
}
Also, here are some examples of using the CoordinatorLayout:
How to use SwipeDismissBehavior.OnDismissListener on RecyclerView
CoordinatorLayout using the ViewPager's RecyclerView
https://lab.getbase.com/introduction-to-coordinator-layout-on-android/
http://android-developers.blogspot.co.uk/2015/05/android-design-support-library.html
I haven't been able to find many examples using SwipeDismissBehavior specifically, but the concepts are similar to the links above.
Alternatively, you may also be able to follow the suggestions of a similar post:
Android swipe layout to dismiss to get the results you desire.
Hope this helps.

Categories

Resources