I am trying to add an contact object and the way I do it is when the user hits add button in the menu bar; this is how I do it.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_contact:
Contact contact = new Contact();
ContactLab.get(getActivity()).addContact(contact);
updateUI();
mCallbacks.onContactSelected(contact);
return true;
case R.id.action_edit:
return true;
case R.id.action_delete:
ContactLab crimeLab = ContactLab.get(getActivity());
crimeLab.deleteContact(mContact);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I have the following fragment
public class ContactListFragment extends Fragment {
// private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
private static final String ARG_CRIME_ID = "crime_id";
private RecyclerView mCrimeRecyclerView;
private ContactAdapter mAdapter;
public Contact mContact;
private Callbacks mCallbacks;
/**
* Required interface for hosting activities.
*/
public interface Callbacks {
void onContactSelected(Contact contact);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallbacks = (Callbacks) context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.contact_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (savedInstanceState != null) {
}
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
private void updateSubtitle() {
ContactLab crimeLab = ContactLab.get(getActivity());
int contactCount = crimeLab.getContacts().size();
String subtitle = getString(R.string.subtitle_format, contactCount);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
public void updateUI() {
ContactLab crimeLab = ContactLab.get(getActivity());
List<Contact> contacts = crimeLab.getContacts();
if (mAdapter == null) {
mAdapter = new ContactAdapter(contacts);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setContacts(contacts);
mAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
private class ContactHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private TextView mTitleTextView;
public ContactHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_content, parent, false));
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.content_name);
}
public void bind(Contact contact) {
mContact = contact;
mTitleTextView.setText(mContact.getName());
}
#Override
public void onClick(View view) {
mCallbacks.onContactSelected(mContact);
}
}
private class ContactAdapter extends RecyclerView.Adapter<ContactHolder> {
private List<Contact> mContacts;
public ContactAdapter(List<Contact> crimes) {
mContacts = crimes;
}
#Override
public ContactHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new ContactHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(ContactHolder holder, int position) {
Contact contact=mContacts.get(position);
holder.bind(contact);
}
#Override
public int getItemCount() {
return mContacts.size();
}
public void setContacts(List<Contact> contacts) {
mContacts = contacts;
}
}
and then I start the above fragment from the following activity fragment
public class ContactListActivity extends SingleFragmentActivity
implements ContactListFragment.Callbacks, ContactFragment.Callbacks {
#Override
protected Fragment createFragment() {
return new ContactListFragment();
}
#Override
protected int getLayoutResId() {
return R.layout.activity_masterdetail;
}
#Override
public void onContactSelected(Contact contact) {
if (findViewById(R.id.detail_fragment_container) == null) {
Intent intent = ContactPagerActivity.newIntent(this, contact.getIDD());
startActivity(intent);
} else {
Fragment newDetail = ContactFragment.newInstance(contact.getId());
getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_fragment_container, newDetail)
.commit();
}
}
public void onContactUpdated(Contact crime) {
ContactListFragment listFragment = (ContactListFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
listFragment.updateUI();
}
}
could any one show me whre I am doing wrong because I see the followoig error in my log
Process: com.bignerdranch.android.adressbook, PID: 28871
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.bignerdranch.android.adressbook.Contact.getName()' on a null object reference
atcom.bignerdranch.android.adressbook.ContactFragment.onCreateView(ContactFragment.java:82)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
Related
my code has Class Cast Exception error.
When the string is sent from the adapter to the fragment by interface. In the fragment, the interface goes to the specific activity if the particular string is selected.
this is Interface code:
public interface StringListener {
void sendStr(String title);
}
and so this is adapter code:
public class StringRecyclerViewAdapter extends RecyclerView.Adapter<StringRecyclerViewAdapter.MyViewHolder>{
List<GridSubject> subjects;
Context context;
public StringRecyclerViewAdapter(Context context,List<GridSubject> subjects)
{
this.context=context;
this.subjects=subjects;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater=LayoutInflater.from(context);
view=inflater.inflate(R.layout.custom_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
final GridSubject subject=subjects.get(position);
holder.txts.setText(subject.text);
holder.imgs.setImageResource(subject.drwab);
holder.myCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendStrMe(subject.getText());
}
});
}
#Override
public int getItemCount() {
return subjects.size();
}
public void sendStrMe(String title) {
StringListener listener=(StringListener) context;
listener.sendStr(title);
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView txts;
ImageView imgs;
CardView myCard;
public MyViewHolder(View itemView) {
super(itemView);
txts=itemView.findViewById(R.id.txt);
imgs=itemView.findViewById(R.id.img);
myCard=itemView.findViewById(R.id.my_card);
}
}
and this is Fragment Code:
public class FragmentA extends Fragment implements SportListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public Intent intent;
public FragmentA() {
// Required empty public constructor
}
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.my_layout_sport, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
try {
super.onActivityCreated(savedInstanceState);
RecyclerView recyclerView=getView().findViewById(R.id.recycler_me);
final String[] txts={"Special","Hard","Manual","Easy"};
int[] imgs={R.drawable.special,R.drawable.hard,R.drawable.manual,R.drawable.easy};
List<GridSubject> subjects=new ArrayList<>();
for(int i=0;i<imgs.length;i++) {
subjects.add(new GridSubject(txts[i], imgs[i]));
}
int ori=getResources().getConfiguration().orientation;
int span;
if(ori== Configuration.ORIENTATION_LANDSCAPE)
span=3;
else
span=2;
StringRecyclerViewAdapter adapter=new StringRecyclerViewAdapter(getActivity(),subjects);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),span));
recyclerView.setAdapter(adapter);
}
catch (Exception e)
{
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void sendSport(String title) {
if(title=="Special") {
intent=new Intent(getActivity(),WebActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
else{
intent=new Intent(getActivity(),SportShowActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
}
}
and this is Activity code:
public class MainActivity extends AppCompatActivity {
BottomNavigationView btm_navs;
FragmentA afrag;
FragmentB bfrag;
FragmentC cfrag;
FragmentD dfrag;
ViewPager pagerS;
MenuItem menuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btm_navs = findViewById(R.id.btn_navs);
pagerS = findViewById(R.id.view_pager_mes);
btm_navs.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.item_a:
pagerS.setCurrentItem(0);
break;
case R.id.item_b:
pagerS.setCurrentItem(1);
break;
case R.id.item_c:
pagerS.setCurrentItem(2);
break;
case R.id.item_d:
pagerS.setCurrentItem(3);
break;
}
return true;
}
});
pagerS.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (menuItem != null) {
menuItem.setChecked(false);
}
else {
btm_navs.getMenu().getItem(position).setChecked(false);
}
btm_navs.getMenu().getItem(position).setChecked(true);
menuItem = btm_navs.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setupViewPager();
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void setupViewPager()
{
ViewPageradapter pageradapter=new ViewPageradapter(getSupportFragmentManager());
afrag=new FragmentA();
bfrag=new FragmentB();
cfrag =new FragmentC();
dfrag=new FragmentD();
pageradapter.addFragment(afrag);
pageradapter.addFragment(bfrag);
pageradapter.addFragment(cfrag);
pageradapter.addFragment(dfrag);
pagerS.setAdapter(pageradapter);
}
}
and so these are errors:
java.lang.ClassCastException: com.example.project.MainActivity cannot be cast to com.example.project.StringListener
at com.example.pakhkhsh.StringRecyclerViewAdapter.sendStrMe(StringRecyclerViewAdapter.java:56)
at com.example.pakhkhsh.StringRecyclerViewAdapter$1.onClick(StringRecyclerViewAdapter.java:45)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Your activity needs to implement SportListener, not the fragment.
just do it:
public class MainActivity extends AppCompatActivity implements SportListener {
// your code ...
}```
As i'm using FragNav library i have some items into List and when i switching on other fragment and after pressing on BackButton i have some other items into this List,
for example generally i have 1 item into List with RecyclerView after switching on other fragment and pressing back button on phone i have 2 items into RecyclerView and using onSaveInstanceState,
onActivityCreated couldn't resolve my problem
my Fragment:
public class HomeFragment extends BaseFragment implements IAnimationListener, View.OnClickListener, InstagramFeedsAdapter.OnClickListener {
...
// constructor
public static HomeFragment createInstance(int instance) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(BaseFragment.ARGS_INSTANCE, instance);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.instagram_post_container, container, false);
activity = getActivity();
context = getActivity().getBaseContext();
mediaUrls = new ArrayList<>();
feedsSchema = new FeedsSchema();
feedsSchema.setId(1);
mediaUrls.add("http://gizasystems.com/wp-content/uploads/2014/08/natural-world-hero3.jpg");
feedsSchema.setFeed_media_url(mediaUrls);
feedsSchema.setFollowers_count(10);
feedsSchema.setFollowings_count(20);
feedsSchema.setPage_name("my test");
feedsSchema.setType(FeedsSchema.feed_types.IMAGE);
items.add(feedsSchema);
instagram_feeds = mView.findViewById(R.id.instagram_feeds);
layoutManager = new LinearLayoutManager(context);
instagram_feeds.setLayoutManager(layoutManager);
instagram_feeds.setNestedScrollingEnabled(false);
instagramFeedsAdapter = new InstagramFeedsAdapter(activity, context, this, items);
return mView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
}
#Override
public void onAnimationEnd() {
}
#Override
public void onClick(View view) {
int clickedItem = view.getId();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onItemClick(View view, String transitionName, int position) {
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("someVarA", new ArrayList<>(items));
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
items = savedInstanceState.getParcelableArrayList("someVarA");
}
}
and my Adapter:
public class InstagramFeedsAdapter extends RecyclerView.Adapter<InstagramFeedsAdapter.InstagramFeedsViewHolder>
implements PreviewView.OnPreviewChangeListener {
private OnClickListener listener;
private List<FeedsSchema> feedsItems;
private Context context;
private boolean hoveredOnPopup = false;
private ExoPlayerManager exoPlayerManager;
private Activity activity;
private enum feedType {
IMAGE,
IMAGESLIDER,
VIDEO
}
public InstagramFeedsAdapter(Activity activity, Context context, OnClickListener listener, List<FeedsSchema> items) {
this.listener = listener;
this.feedsItems = items;
this.context = context;
this.activity = activity;
}
#Override
public void onBindViewHolder(#NonNull final InstagramFeedsViewHolder holder, int position) {
int feedType = feedsItems.get(position).getType().ordinal();
implementingGeneralViewData(holder, position);
if (feedType == 0) {
if (feedsItems.get(position).getFeed_media_url().size() > 1) {
implementingImageSliderView(holder, position);
} else {
implementingImageView(holder, position);
}
} else {
implementingVideoPlayerView(holder, position);
}
}
private void implementingVideoPlayerView(InstagramFeedsViewHolder holder, int position) {
}
#SuppressLint("CheckResult")
private void implementingImageSliderView(final InstagramFeedsViewHolder holder, final int position) {
}
#SuppressLint("CheckResult")
private void implementingImageView(final InstagramFeedsViewHolder holder, final int position) {
}
#Override
public int getItemCount() {
return feedsItems.size();
}
public class InstagramFeedsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, PopupInflaterListener, PopupStateListener, PopupOnHoverListener {
...
public InstagramFeedsViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
ButterKnife.bind(this, itemView);
}
#Override
public void onClick(View view) {
}
public void bind(int position) {
...
}
}
I have the code for a fragment of the as follows that works very well:
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
private boolean mSubtitleVisible;
private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_crime_list,container,false);
mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (null != savedInstanceState) {mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);}
updateUI();
return view;
}
#Override
public void onResume()
{
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisible);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem subtitleItem = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible) {subtitleItem.setTitle(R.string.hide_subtitle);}
else {subtitleItem.setTitle(R.string.show_subtitle);}
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_item_new_crime:
{
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
}
case R.id.menu_item_show_subtitle:
{
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
}
default: return super.onOptionsItemSelected(item);
}
}
private void updateSubtitle()
{
CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeCount = crimeLab.getCrimes().size();
String subtitle = getString(R.string.subtitle_format,crimeCount);
if (!mSubtitleVisible) {subtitle = null;}
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
private void updateUI()
{
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes =crimeLab.getCrimes();
if (null == mAdapter)
{
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
else {mAdapter.notifyDataSetChanged();}
updateSubtitle();
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
//public TextView mTitleTextView;
private TextView mTitleTextView;
private TextView mDateTextView;
private CheckBox mSolvedCheckBox;
private Crime mCrime;
public CrimeHolder(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
//mTitleTextView = (TextView) itemView;
mTitleTextView = (TextView) itemView.findViewById(R.id.list_item_crime_title_text_view);
mDateTextView = (TextView) itemView.findViewById(R.id.list_item_crime_date_text_view);
mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.list_item_crime_solved_check_box);
}
public void bindCrime(Crime crime)
{
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateTextView.setText(mCrime.getDate().toString());
mSolvedCheckBox.setChecked(mCrime.isSolved());
}
#Override
public void onClick(View v)
{
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder>
{
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes){mCrimes = crimes;}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_crime/*android.R.layout.simple_list_item_1*/,parent,false);
return new CrimeHolder(view);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) //finalmente a esta de aquĆ
{
Crime crime = mCrimes.get(position);
/*holder.mTitleTextView.setText(crime.getTitle());*/
holder.bindCrime(crime);
}
#Override
public int getItemCount()
{
return mCrimes.size();
}
}
}
I have tried to implement the examples of Drag and Swipe with RecyclerView, like this medium article:
But I only get errors.
What do I need to implement onSwiped and where?
Thanks
I am having trouble implementing view.OnClickListener in my RecyclerView.Adapter. I am trying to implement multi-pane layout (landscape tablet layout version with RecyclerView and detail side by side). I have so far created this Activity:
public class MovieListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MovieListFragment movieListFragment = new MovieListFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recycler_view_fragment, movieListFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
which starts a Fragment:
public class MovieListFragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MoviesAdapter(getContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
ButterKnife.bind(this,view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) { error.printStackTrace(); }
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
which calls the RecyclerView.Adapter:
public class MoviesAdapter extends RecyclerView.Adapter<MovieViewHolder> {
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context) {
this.mContext = context;
this.mInflater = LayoutInflater.from(context); //
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.movie_row_item, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.MOVIE_EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.thumbnail);
holder.movieTitle.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
}
Here in onClick I need to decide whether to start a new Activity (like in my code) or update content of detail Fragment (in my tablet landscape layout).
According to this link, you should decide based on fact if your DetailFragment is != null in activity like this:
public void onItemSelected(int position) {
DisplayFragment displayFrag = (DisplayFragment) getFragmentManager()
.findFragmentById(R.id.display_frag);
if (displayFrag == null) {
// DisplayFragment (Fragment B) is not in the layout (handset layout),
// so start DisplayActivity (Activity B)
// and pass it the info about the selected item
Intent intent = new Intent(this, DisplayActivity.class);
intent.putExtra("position", position);
startActivity(intent);
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
displayFrag.updateContent(position);
}
}
But I'm not able to check this in Adapter. Any help would be highly appreciated!
Thank you.
Created the custom interface click action to get the control in fragment class
i hope it will works for you
public class MoviesAdapter extends RecyclerView.Adapter {
MoviesAdapterCallback moviesAdapterCallback;
private List<Movie> mMovieList;
private LayoutInflater mInflater;
private Context mContext;
public MoviesAdapter(Context context,MoviesAdapterCallback moviesAdapterCallback) {
this.mContext = context;
this.moviesAdapterCallback =moviesAdapterCallback;
this.mInflater = LayoutInflater.from(context); //
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = mInflater.inflate(R.layout.movie_row_item, parent, false);
final MovieViewHolder viewHolder = new MovieViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/* int position = viewHolder.getAdapterPosition();
Intent intent = new Intent(mContext, MovieDetailActivity.class);
intent.putExtra(MovieDetailActivity.MOVIE_EXTRA, mMovieList.get(position));
mContext.startActivity(intent);
*/ moviesAdapterCallback.MovieClicked(view);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Movie movie = mMovieList.get(position);
Picasso.with(mContext)
.load(movie.getPoster())
.placeholder(R.color.colorAccent)
.into(holder.thumbnail);
holder.movieTitle.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
}
#Override
public int getItemCount() {
return (mMovieList == null) ? 0 : mMovieList.size();
}
public void setMovieList(List<Movie> movieList) {
this.mMovieList = new ArrayList<>();
this.mMovieList.addAll(movieList);
notifyDataSetChanged();
}
public interface MoviesAdapterCallback {
void MovieClicked(View view);
}
}
in Fragment Class
public class MovieListFragment extends Fragment {
#BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
public MovieListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_movie_list, container, false);
ButterKnife.bind(this,view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAdapter = new MoviesAdapter(getContext(), new MoviesAdapter.MoviesAdapterCallback(){
#Override
public void MovieClicked(View view) {
DisplayFragment displayFrag = (DisplayFragment) getFragmentManager()
.findFragmentById(R.id.display_frag);
if (displayFrag == null) {
// DisplayFragment (Fragment B) is not in the layout (handset layout),
// so start DisplayActivity (Activity B)
// and pass it the info about the selected item
Intent intent = new Intent(this, DisplayActivity.class);
intent.putExtra("position", position);
startActivity(intent);
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
displayFrag.updateContent(position);
}
}
});
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
getPopularMovies();
}
private void getPopularMovies() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://api.themoviedb.org")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
MoviesApiService service = restAdapter.create(MoviesApiService.class);
service.getPopularMovies(new Callback<Movie.MovieResult>() {
#Override
public void success(Movie.MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) { error.printStackTrace(); }
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.