How to share the data between Fragments using ViewModel - java

I have a main fragment and inside the main fragment, I have a ViewPager that consists of Nested Fragment (Detail Fragment & Summary Fragment). If I click the button in the main fragment, the data will be set in both the main fragment and Detail fragments in the ViewPager. The problem is how do I get the data from the main fragments that can be used in Detail fragments?
I tried using ViewModel in the main fragment. Suppose that the data should be passing in Detail Fragment.
//Main Fragment
private void initializeViewPager()
{
vpExpenses.setOffscreenPageLimit(2);
setupViewPager(vpExpenses);
}
private void setupViewPager(final ViewPager viewPager)
{
adapter = new ViewPagerWithTitleAdapter(getFragmentManager());
adapter.addFragment(new ExpensesDetailsListFragment(), "Detail");
adapter.addFragment(new ExpensesSummaryListFragment(), "Summary");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override public void onPageScrollStateChanged(int state) { }
#Override public void onPageSelected(int position) {
if(position == 0)
{
tvDetailExpenses.setSelected(true);
tvSummaryExpenses.setSelected(false);
}
else if(position == 1)
{
tvDetailExpenses.setSelected(false);
tvSummaryExpenses.setSelected(true);
}
}
});
tvDetailExpenses.setSelected(true);
viewPager.setCurrentItem(0);
tvDetailExpenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
viewPager.setCurrentItem(0,false);
}
});
tvSummaryExpenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(1,false);
}
});
}
//Expenses Details List
private void setupExpensesDetailsList(String expenseCategoryId)
{
expensesViewModel = ViewModelProviders.of(this.getActivity()).get(ExpensesViewModel.class);
expensesViewModel.setToken(token);
expensesViewModel.setUserId(userId);
expensesViewModel.setDeviceId("ABCDE1234567890");
expensesViewModel.setCarId("24");
expensesViewModel.setExpensesId(expenseCategoryId);
getExpensesDetailsList();
}
public void getExpensesDetailsList()
{
expensesViewModel.getExpensesDetailsList().observe(this, expensesdetailslistObserver);
}
public Observer<ExpensesDetailsListResult> expensesdetailslistObserver = new Observer<ExpensesDetailsListResult>() {
#Override
public void onChanged(#Nullable ExpensesDetailsListResult result)
{
if(result.getStatus())
{
summary = result.getData().getSummary();
tvTotalExpenses.setText("RM"+summary.getYearly());
tvExpensesPerDay.setText("/ "+summary.getDaily_avg()+" per day");
}
else
{
if(!result.getStatus())
{
if(result.getCode() == 300)
{
new MaterialDialog.Builder(getActivity())
.title("Failed")
.content(result.getMsg())
.positiveText("OK")
.show();
}
else if(result.getCode() == 302)
{
new MaterialDialog.Builder(getActivity())
.title("Failed")
.content(result.getMsg())
.positiveText("OK")
.show();
}
}
if(result.getRedirectLogin() != null)
{
if (result.getRedirectLogin())
{
func.showErrorExpired();
}
}
}
}
};
//Details Fragment
private ExpensesDetailsListResult expensesDetails;
private List<ExpensesTypes> listExpensesType;
private Unbinder unbinder;
private ExpensesViewModel expensesViewModel;
private Function func;
#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_expenses_list_details, container, false);
unbinder = ButterKnife.bind(this, view);
func = new Function(getActivity());
expensesViewModel = ViewModelProviders.of(this.getActivity()).get(ExpensesViewModel.class);
expensesViewModel.getExpensesDetailsList().observe(this, item -> {
//expensesDetails = expensesViewModel.setExpensesDetailsList(item);
});
return view;
}
//View Model
public ExpensesViewModel(#NonNull Application application)
{
super(application);
}
public void setToken(String token)
{
this.token = token;
}
public void setUserId(String userId)
{
this.userId = userId;
}
public void setDeviceId(String deviceId)
{
this.deviceId = deviceId;
}
public void setCarId(String carId)
{
this.carId = carId;
}
public void setExpensesId(String expensesId)
{
this.expensesId = expensesId;
}
//THIS IS THE MAIN FUNCTION THAT UI CONTROLLER CAN OBSERVE FOR CHANGES
//Expenses Category
public MutableLiveData<ExpensesCategoryResult> getExpensesCategory()
{
expensescategoryObservable = ExpensesRepository.getInstance().getExpensesCategory(token, userId, deviceId);
return expensescategoryObservable;
}
//Expenses Details List
public MutableLiveData<ExpensesDetailsListResult> getExpensesDetailsList()
{
expensesdetailslistObservable = ExpensesRepository.getInstance().getExpensesDetailsList(token, userId, deviceId, carId, expensesId, "1");
return expensesdetailslistObservable;
}

You're passing in the wrong Lifecycle Owner when you're observing your ViewModel's data. In order for both fragments to share the data through the ViewModel, the Lifecycle Owner should be the Activity.
Both Fragments should contain something like the following:
// Get the View Model with the Activity as the owner
expensesViewModel = ViewModelProviders.of(getActivity()).get(ExpensesViewModel.class);
// Observe the LiveData by passing in the Activity as the owner, & the observer
expensesViewModel.getExpensesDetailsList().observe(getActivity(), new Observer<ExpensesDetailsListResult>(){
#Override
public void onChanged(ExpensesDetailsListResult result) {
// Do something with the data according to which Fragment this is in
}
});

Related

Prevent repeating of items when i back to fragment

In my application , I have ViewPager containing 3 fragments (Home , Profile and More)
Home Fragment contain RecyclerView
when i navigate from Home Fragment to Profile Fragment or More Fragment, it work like expected.
But when i navigate back to Home Fragment , items in RecyclerView duplicate...
And when i navigate again and back , it duplicate again
Here is my MainActivity.java Code:
public class MainActivity extends AppCompatActivity {
TabLayout mainTabLayout;
ViewPager mainViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainTabLayout = findViewById(R.id.main_tablayout);
mainViewPager = findViewById(R.id.main_viewpager);
mainTabLayout.setupWithViewPager(mainViewPager);
//to put mainTabLayout Icons...
MainTabLayoutIcons();
}
//to Change MainLayout Icons...
private void MainTabLayoutIcons() {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// add fragments to the adapter
adapter.addFragment(new Home());
adapter.addFragment(new MyActivity());
adapter.addFragment(new More());
mainViewPager.setOffscreenPageLimit(0);
mainViewPager.setAdapter(adapter);
// Select Home tab as default tab on startup
mainViewPager.setCurrentItem(0);
mainTabLayout.getTabAt(0).select();
// Set tabs Initial icons
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_black);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
/* tabSelectedListener to change the icon color once it is selected
// and change it back once another tab is selected */
mainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_black);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
}
if (tab.getPosition() == 1) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_outline);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
}
if (tab.getPosition() == 2) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_outline);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_black);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//no need for it
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//no need for it
}
});
}
}
and here is ViewPagerAdapter Code:
//Adapter for mainActivity ...
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment) {
fragmentList.add(fragment);
}
}
and here is first Fragment Home.java Code:
public class Home extends Fragment {
View v;
public SwipeRefreshLayout mSwipeRefreshLayout;
public RecyclerView mainRecyclerView;
private LinearLayoutManager linearLayoutManager;
public final List<MyActivityModel> mainPosts = new ArrayList<>();
private PostAdapter mAdapter;
public Home() {
/*Required Empty Constructor... */
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle bundle) {
v = layoutInflater.inflate(R.layout.fragment_home, container, false);
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.mainSwipeRefresh);
mainRecyclerView = (RecyclerView) v.findViewById(R.id.MainRecyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity());
mainRecyclerView.setLayoutFrozen(true);
mainRecyclerView.setNestedScrollingEnabled(false);
mainRecyclerView.setLayoutManager(linearLayoutManager);
mAdapter = new PostAdapter(mainPosts);
mainRecyclerView.setAdapter(mAdapter);
Swipe();
LoadPosts();
return v;
}
/**
* -----------------TODO: to load posts in Home RecyclerView...----------------
*/
public void LoadPosts() {
Query database = FirebaseDatabase.getInstance().getReference().child("Posts");
database.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
if (snapshot.exists()) {
MyActivityModel post = snapshot.getValue(MyActivityModel.class);
mainPosts.add(0, post);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void Swipe() {
//to refresh page after swipe
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mainPosts.clear();
LoadPosts();
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(v.getContext(),"Refreshed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
}, 500);
}
});
}
}
and this is an image showing item reeating
Anyone can help me how to prevent this duplication...
You may need to use FragmentPagerAdapter instead of FragmentStatePagerAdapter. Also, set mainRecyclerView.setLayoutFrozen(true); to false because, it will stop everything in recyclerView.
When you need to use FragmentPagerAdapter?
FragmentStatePagerAdapter is more useful when there are a large number
of pages, working more like a list view. When pages are not visible to
the user, their entire fragment may be destroyed, only keeping the
saved state of that fragment. This allows the pager to hold on to
much less memory associated with each visited page as compared to
FragmentPagerAdapter at the cost of potentially more overhead when
switching between pages.
Example of FragmentPagerAdapter:
class viewpager_class extends FragmentPagerAdapter {
int tabcount;
public viewpager_class(#NonNull FragmentManager fm, int tab_count) {
super(fm, tab_count);
this.tabcount = tab_count;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment1 fragment1 = new Fragment1 ();
return todayBAFragment;
case 1:
Fragment2 fragment2 = new Fragment2 ();
return todayReminderDue;
case 2:
Fragment3 fragment3 = new Fragment3 ();
return currentTransaction;
default:
return null;
}
}
#Override
public int getCount() {
return tabcount;
}
}
Also, set adapter into ViewPager wherever you want show viewPager:
//set adapter into viewpager
viewpager_class viewpagerClass = new viewpager_class(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewpagerClass);
viewPager.setOffscreenPageLimit(2);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

Is it possible to set ViewPager inside a fragment class?

I have a Fragment class and an Activity class which is related to that fragment, ViewPager has been initialized inside the Activity of MizActivity
My question is it possible to move ViewPager initialization from Activity class to the Fragment class So that I have better control?
Thanks in advance
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
TextClicked mCallback;
public interface TextClicked{
void sendText(int position);
}
private Activity mContext;
private TvShowEpisode mEpisode;
private ImageView mBackdrop, mEpisodePhoto;
private TextView mTitle, mDescription, mFileSource, mAirDate, mRating, mDirector, mWriter, mGuestStars, mSeasonEpisodeNumber;
private View mDetailsArea;
private Picasso mPicasso;
private Typeface mMediumItalic, mMedium, mCondensedRegular;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private long mVideoPlaybackStarted, mVideoPlaybackEnded;
private boolean mShowFileLocation;
private Bus mBus;
private int mToolbarColor = 0;
private FloatingActionButton mFab;
private PaletteLoader mPaletteLoader;
private ObservableScrollView mScrollView;
private RecyclerView mEpisodesList;
private String mShowId;
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private static final String SHOW_ID = "showId";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ViewPager mViewPager;
public PlanetAdapter.OnItemClickListener listener;
/**
* Empty constructor as per the Fragment documentation
*/
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
// initializing mEpisodes
mShowId = getActivity().getIntent().getExtras().getString(SHOW_ID);
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(mContext, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
} // mEpisodes initialized
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TextClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement TextClicked");
}
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
// setting RecyclerView
mEpisodesList = (RecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
mEpisodesList.setAdapter(new PlanetAdapter(episodeslist, new PlanetAdapter.OnItemClickListener() {
#Override public void onItemClick(String item) {
SharedPreferences getPref = getActivity ().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition",0);
mCallback.sendText(pos);
}
}));
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
if (MizLib.isTablet(mContext))
mFab.setType(FloatingActionButton.TYPE_NORMAL);
final int height = MizLib.getActionBarAndStatusBarHeight(getActivity());
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mScrollView.setOnScrollChangedListener(new OnScrollChangedListener() {
#Override
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
final int headerHeight = mEpisodePhoto.getHeight() - height;
final float ratio = (float) Math.min(Math.max(t, 0), headerHeight) / headerHeight;
final int newAlpha = (int) (ratio * 255);
mBus.post(new BusToolbarColorObject(mToolbarColor, newAlpha));
if (MizLib.isPortrait(mContext)) {
// Such parallax, much wow
mEpisodePhoto.setPadding(0, (int) (t / 1.5), 0, 0);
}
}
});
mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewUtils.setLayoutParamsForDetailsEmptyView(mContext, view,
mBackdrop, mScrollView, this);
}
});
loadData();
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto, new Callback() {
#Override
public void onError() {
if (!isAdded())
return;
int width = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_width);
int height = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_height);
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).resize(width, height).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto);
}
#Override
public void onSuccess() {
if (mPaletteLoader == null) {
mPaletteLoader = new PaletteLoader(mPicasso, Uri.fromFile(mEpisode.getEpisodePhoto()), new PaletteLoader.OnPaletteLoadedCallback() {
#Override
public void onPaletteLoaded(int swatchColor) {
mToolbarColor = swatchColor;
}
});
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
mPaletteLoader.execute();
} else {
// Clear old views after configuration change
mPaletteLoader.clearViews();
// Add views after configuration change
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
// Re-color the views
mPaletteLoader.colorViews();
}
}
});
if (!MizLib.isPortrait(getActivity()))
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).error(R.drawable.bg).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getEpisodePhoto().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override public void onError() {
if (!isAdded())
return;
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getTvShowBackdrop().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override
public void onError() {}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onDetach() {
mCallback = null; // => avoid leaking, thanks #Deepscorn
super.onDetach();
}
private void loadData() {
// Set the episode title
mTitle.setVisibility(View.VISIBLE);
mTitle.setText(mEpisode.getTitle());
mTitle.setTypeface(mCondensedRegular);
mDescription.setTypeface(mCondensedRegular);
mFileSource.setTypeface(mCondensedRegular);
mDirector.setTypeface(mCondensedRegular);
mWriter.setTypeface(mCondensedRegular);
mGuestStars.setTypeface(mCondensedRegular);
mAirDate.setTypeface(mMedium);
mRating.setTypeface(mMedium);
mSeasonEpisodeNumber.setTypeface(mMediumItalic);
mSeasonEpisodeNumber.setText(getString(R.string.showSeason) + " " + mEpisode.getSeason() + ", " + getString(R.string.showEpisode) + " " + mEpisode.getEpisode());
// Set the movie plot
if (!MizLib.isPortrait(getActivity())) {
mDescription.setBackgroundResource(R.drawable.selectable_background);
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true); // true = collapsed
mDescription.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((Boolean) mDescription.getTag())) {
mDescription.setMaxLines(1000);
mDescription.setTag(false);
} else {
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true);
}
}
});
mDescription.setEllipsize(TextUtils.TruncateAt.END);
mDescription.setFocusable(true);
} else {
if (MizLib.isTablet(getActivity()))
mDescription.setLineSpacing(0, 1.15f);
}
mDescription.setText(mEpisode.getDescription());
if (mShowFileLocation) {
mFileSource.setText(mEpisode.getAllFilepaths());
} else {
mFileSource.setVisibility(View.GONE);
}
// Set the episode air date
mAirDate.setText(MizLib.getPrettyDatePrecise(getActivity(), mEpisode.getReleasedate()));
// Set the movie rating
if (!mEpisode.getRating().equals("0.0")) {
try {
int rating = (int) (Double.parseDouble(mEpisode.getRating()) * 10);
mRating.setText(Html.fromHtml(rating + "<small> %</small>"));
} catch (NumberFormatException e) {
mRating.setText(mEpisode.getRating());
}
} else {
mRating.setText(R.string.stringNA);
}
if (TextUtils.isEmpty(mEpisode.getDirector()) || mEpisode.getDirector().equals(getString(R.string.stringNA))) {
mDirector.setVisibility(View.GONE);
} else {
mDirector.setText(mEpisode.getDirector());
}
if (TextUtils.isEmpty(mEpisode.getWriter()) || mEpisode.getWriter().equals(getString(R.string.stringNA))) {
mWriter.setVisibility(View.GONE);
} else {
mWriter.setText(mEpisode.getWriter());
}
if (TextUtils.isEmpty(mEpisode.getGuestStars()) || mEpisode.getGuestStars().equals(getString(R.string.stringNA))) {
mGuestStars.setVisibility(View.GONE);
} else {
mGuestStars.setText(mEpisode.getGuestStars());
}
}
Rest of the code
}
Activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked{
private static final String SHOW_ID = "showId";
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private int mSeason, mEpisode;
private String mShowId, mShowTitle;
private ViewPager mViewPager;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private Bus mBus;
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
#Subscribe
public void onScrollChanged(TvShowEpisodeDetailsFragment.BusToolbarColorObject object) {
ViewUtils.updateToolbarBackground(this, mToolbar, object.getAlpha(),
mEpisodes.get(mViewPager.getCurrentItem()).getTitle(), object.getToolbarColor());
}
public void onResume() {
super.onResume();
mBus.register(this);
ViewUtils.updateToolbarBackground(this, mToolbar, 0, mShowTitle, Color.TRANSPARENT);
}
#Override
public void onPause() {
super.onPause();
mBus.unregister(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStart() {
super.onStart();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", mViewPager.getCurrentItem());
}
#Override
public void sendText(int position) {
mViewPager.setCurrentItem(position,false);
//Toast.makeText(getContext(), "Item Clicked " + text, Toast.LENGTH_SHORT).show();
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
setResult(Activity.RESULT_OK);
finish();
}
}
}
}
Yes, a Viewpager can be setup in a Fragment.
You just need to get the right FragmentManager when constructing it i.e use getChildFragmentManager() in mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
From https://developer.android.com/guide/fragments/fragmentmanager
Access the FragmentManager
Accessing in an activity
Every FragmentActivity and subclasses thereof, such as
AppCompatActivity, have access to the FragmentManager through the
getSupportFragmentManager() method.
Accessing in a Fragment
Fragments are also capable of hosting one or more child fragments.
Inside a fragment, you can get a reference to the FragmentManager that
manages the fragment's children through getChildFragmentManager().

What to set on textview from the JSON response I'm getiing through retrofit for DashboardResponse?

I'm getting nullPointerException when I try to set data to textviews from the JSON response,I'm getting through retrofit. I would like to set the total sale, total expense and total purchase values to the textviews:
tv_total_purchase_today,
tv_total_sale_today,
tv_total_expense_today
What should I put in the setsaleInformations method?
Here's my code:
API Response
public class DashboardResponse extends CommonResponse {
#Expose
#SerializedName("graph_data")
private ArrayList<Graph> graph_data;
#Expose
#SerializedName("total_sale")
private String total_sale;
#Expose
#SerializedName("total_purchase")
private String total_purchase;
#Expose
#SerializedName("total_expense")
private String total_expense;
public ArrayList<Graph> getGraph_data() {
return graph_data;
}
public void setGraph_data(ArrayList<Graph> graph_data) {
this.graph_data = graph_data;
}
public String getTotal_sale() {
return total_sale;
}
public void setTotal_sale(String total_sale) {
this.total_sale = total_sale;
}
public String getTotal_purchase() {
return total_purchase;
}
public void setTotal_purchase(String total_purchase) {
this.total_purchase = total_purchase;
}
public String getTotal_expense() {
return total_expense;
}
public void setTotal_expense(String total_expense) {
this.total_expense = total_expense;
}
}
API Interactor Implementation
#Override
public void getDashboard(final DashboardListener dashboardListener) {
Call<DashboardResponse> call = apiServiceInterface.getDashboard();
call.enqueue(new Callback<DashboardResponse>() {
#Override
public void onResponse(Call<DashboardResponse> call, Response<DashboardResponse> response) {
if(isResponseValid(response) && response.body().isSuccess()){
dashboardListener.onDashboardFetch(response.body());
}else{
dashboardListener.onFailed(prepareFailedMessage(response), APIConstants.DASHBOARD);
}
}
Dashboard Fragment
public class DashboardFragment extends Fragment {
private Context context;
private SalesUtils salesUtils;
private DashboardResponse dashboardResponse;
private HomePresenter homePresenter;
private HomeView homeView;
#BindView(R.id.tv_total_sale_today)
TextView tv_total_sale_today;
#BindView(R.id.tv_total_purchase_today)
TextView tv_total_purchase_today;
#BindView(R.id.tv_total_expense_today)
TextView tv_total_expense_today;
#BindView(R.id.cv_sale_today)
CardView cv_sale_today;
#BindView(R.id.cv_purchase_today)
CardView cv_purchase_today;
#BindView(R.id.cv_expense_today)
CardView cv_expense_today;
private ArrayList<Sale> salesToday;
private ArrayList<Product> productSoldToday;
private SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
public DashboardFragment() {
// Required empty public constructor
}
public static DashboardFragment newInstance(HomePresenter homePresenter) {
DashboardFragment fragment = new DashboardFragment();
fragment.initializeSaleInfo(homePresenter);
return fragment;
}
private void initializeSaleInfo(HomePresenter homePresenter) {
this.homePresenter = homePresenter;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
homeView = (HomeView) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
ButterKnife.bind(this, rootView);
cv_sale_today.startAnimation(AnimationUtils.loadSlideInLeftAnimation(context));
cv_purchase_today.startAnimation(AnimationUtils.loadFadeInAnimation(context));
cv_expense_today.startAnimation(AnimationUtils.loadSlideInRightAnimation(context));
homePresenter.fetchDashboard();
setListeners();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
if(homeView!=null) {
homeView.changeSearchState(false);
}
}
#Override
public void onPause() {
super.onPause();
if(homeView != null)
homeView.setIsInSaleInfo(false);
}
public void setSaleInformations() {
if (getActivity() != null && isAdded())
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_total_purchase_today.setText();
tv_total_sale_today.setText();
tv_total_expense_today.setText();
}
});
}
private Thread resumeSaleInfo = new Thread(new Runnable() {
#Override
public void run() {
salesToday = salesUtils.getSalesDuring(ApplicationUtils.getStartingDateTime(simpleDateTimeFormat.format(System.currentTimeMillis())), ApplicationUtils.getEndingDateTime(simpleDateTimeFormat.format(System.currentTimeMillis())));
if (getActivity() != null && isAdded())
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_total_purchase_today.setText(ApplicationUtils.getBengaliNumber(salesToday.size() + "") + " " + getString(R.string.buy_today_label));
tv_total_sale_today.setText(ApplicationUtils.currencyFormat(SalesUtils.getTotalSale(salesToday)));
tv_total_expense_today.setText(ApplicationUtils.getBengaliNumber(SalesUtils.countUnitSold(productSoldToday) + "") + " " + getString(R.string.unit_sold));
}
});
}
});
private void setListeners() {
cv_sale_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePresenter.showSaleAt(simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
cv_purchase_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homePresenter.showSaleAt(simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
cv_expense_today.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homePresenter.showUnitSold(simpleDateTimeFormat.format(System.currentTimeMillis()), simpleDateTimeFormat.format(System.currentTimeMillis()));
}
});
}
public void setDashboard(DashboardResponse dashboardResponse) {
Log.e("DASHBOARD", new Gson().toJson(dashboardResponse));
this.dashboardResponse = dashboardResponse;
setSaleInformations();
}
}
That means either the text views haven't loaded onto the screen yet or the views haven't been initialized yet.

Trying to call method from MainActivity in Another Activity it is me leading to error

I have Recycler ListView which I show in MainActivity and the first item it is as selected, I have done to click for another items but the last stays clicked and when I try to take this recycler view to show me in next Activity it doesn't work.
The first item it is selected but I have a click method which when click an image makes as selected but when I click a new image this works but the first item stays as selected so continues for others images. I want only a image to be selected.
I don't want to write twice the same code.
Is it good if I have a class only for this method which I can use everytime I want.
The id of recycler view list it is the same on both xml's.
If you have any suggestion for my question please let me know.
This is the adapter for the RecyclerView.
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
This is the method in MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
This is the button which takes to another activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
Cursor data = mDatabaseHelper.getData();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("name", newEntry);
intent.putExtra("test", mSearchUrl.get(0));
startActivityForResult(intent, 2);
}
});
This is the another activity
public class ActivitySearchEngine extends Activity implements
SwipeRefreshLayout.OnRefreshListener {
public ImageView mHome;
public EditText searchPlugin;
public WebView webView;
Button btnSearch;
public ImageButton clearSearch, exitButton;
public ImageView favIcon;
public ProgressBar loadIcon;
String text;
SwipeRefreshLayout refreshLayout;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
private String selectedSearchUrl;
RecyclerView mListView;
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
mHome = findViewById(R.id.imgBtnHome);
searchPlugin = findViewById(R.id.etSearch);
webView = findViewById(R.id.webView);
clearSearch = findViewById(R.id.btnClearSearch);
btnSearch = findViewById(R.id.btnSearch);
favIcon = findViewById(R.id.imgViewFavIcon);
loadIcon = findViewById(R.id.progressBarIcon);
exitButton = findViewById(R.id.imgBtnStopLoad);
refreshLayout = findViewById(R.id.refreshLayout);
mListView = findViewById(R.id.lvEngines);
refreshLayout.setOnRefreshListener(this);
mDatabaseHelper = new DatabaseHelper(this);
mainActivity.intSearch(); // Here it is the error
Activity.ActivitySearchEngine}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("test");
searchPlugin.setText(selectedName);
loadIcon.setVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.bing.com/search?=" + selectedName);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
favIcon.setImageBitmap(icon);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadIcon.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
try {
if (loadIcon.getVisibility() == View.VISIBLE) {
loadIcon.setVisibility(View.GONE);
favIcon.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
exitButton.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRefresh();
}
});
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
searchPlugin.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
processButtonByTextLength();
}
});
mHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText(null);
finish();
}
});
clearSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText("");
}
});
public void processButtonByTextLength() {
String inputText = searchPlugin.getText().toString();
if(inputText.length() > 0) {
btnSearch.setVisibility(View.VISIBLE);
mHome.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.VISIBLE);
loadIcon.setVisibility(View.GONE);
exitButton.setVisibility(View.GONE);
} else if(inputText.length() == 0) {
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
clearSearch.setVisibility(View.GONE);
}
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
}
This is the photo with RecyclerView at MainActivity.class
Photo of another Activity

Update TAB 2 Recyclerview When Data Added in TAB 1's RecyclerView

I have kind of to-do app. In profile activity, there are 2 tabs.
To-do and Done. In Tab 1, user can check as "done" of their "to-do". In this case, I want to update TAB 2's recyclerview.
I tried several things, but didn't work. Here is TAB 1 codes, it's almost same as TAB 2.
TAB 1 Class
public class Tab_Profile_1 extends Fragment {
private RecyclerView recyclerView_tab_todo;
private List<Model_ListItem> itemList;
private Adapter_Profile_ToDo adapter_profile_toDo;
SharedPreferences mSharedPref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_tab_1, container, false);
//TO-DO
//
recyclerView_tab_todo = view.findViewById(R.id.recyclerView_tab_todo);
//
fetchUserToDo();
return view;
}
public void fetchUserToDo() {
itemList = new ArrayList<>();
//First Settings
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchUserToDo(session_user_id);
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
itemList = response.body();
adapter_profile_toDo = new Adapter_Profile_ToDo(getContext(), itemList);
recyclerView_tab_todo.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView_tab_todo.setLayoutManager(layoutManager);
recyclerView_tab_todo.setAdapter(adapter_profile_toDo);
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}}
TAB 1 RecyclerView Adapter
public class Adapter_Profile_ToDo extends RecyclerView.Adapter {
private Context context;
private List<Model_ListItem> itemList;
private String url_extension_images = URL_Extension.url_extension_images;
SharedPreferences mSharedPref;
ProgressDialog progressDialog;
View view;
public Adapter_Profile_ToDo(Context context, List<Model_ListItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(context).load(url_extension_images + itemList.get(position).getItem_image()).into(holder.imageView_profile_todo);
holder.textView_profile_todo_name.setText(itemList.get(position).getItem_name());
holder.textView_profile_todo_desc.setText(itemList.get(position).getItem_description());
holder.layout_profile_todo_detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//detail
}
});
holder.layout_profile_todo_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.AlertStyle);
builder.setTitle("\"" + itemList.get(position).getItem_name() + "\"" + "\n");
builder.setIcon(R.drawable.ic_bookmark);
builder.setPositiveButton("YAPTIM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
addDone("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNegativeButton("SİL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
deleteUserToDo("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNeutralButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_profile_todo;
TextView textView_profile_todo_name, textView_profile_todo_desc;
LinearLayout layout_profile_todo_detail, layout_profile_todo_add;
public ViewHolder(View itemView) {
super(itemView);
imageView_profile_todo = itemView.findViewById(R.id.imageView_profile_todo);
textView_profile_todo_name = itemView.findViewById(R.id.textView_profile_todo_name);
textView_profile_todo_desc = itemView.findViewById(R.id.textView_profile_todo_desc);
layout_profile_todo_detail = itemView.findViewById(R.id.layout_profile_todo_detail);
layout_profile_todo_add = itemView.findViewById(R.id.layout_profile_todo_add);
}
}
public void deleteUserToDo(final String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = api_service.deleteUserToDo(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Silindi!", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
});
}
public void addDone(String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service apiService = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = apiService.addDone(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Eklendi", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
}
});
}
public void showProgressDialog() {
progressDialog = new ProgressDialog(view.getRootView().getContext());
progressDialog.setMessage("Yükleniyor");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
If i'm reading this correctly, you have two tabs and a backend database that stores the to do items and their state? To get the second list to update, you just need to do the same thing that you're doing in your first list, and update the adapter's data set and notify that the data set changed. How you trigger this action in your second tab is really the question.
You can either use an interface and have your adapter notify your activity that recycler view 1 had an action on it, and you can then tell adapter 2 to update its data. You can either pass back the data and only notify one row, or you could notify the entire data set. If you're doing this all service based, you could just reload the recycler view from the service and it will have the new data.
I think all you need to figure out is how you want to notify tab 2 that it needs to update its data. My recommendation is:
public interface AdapterInterface
{
void itemCompleted(Item hereIsTheItemThatNeedsToBeAddedTo2);
}
Then inside your adapter have a property with getters/setters such as:
private AdapterInterface adapterInterfaceListener;
Inside your Fragment/Activity implement AdapterInterface and implement the itemCompleted function.
And then set your adapter.setAdapterInterfaceLisetener to that function that you implemented. Then inside your adapter when the user clicks the checkbook to mark it as done, you can call the adapterInterfaceListener.itemCompleted() function, and it will send that information to your Fragment/Activity. From there you can give that new data to adapter2, or recall the API, however you want to get the new data.
Does this help?

Categories

Resources