Get value between View Pager - java

I want to get value from my actvity ControlAccountPassword.java to my FragmentEditoreProfile.java, I am using view pager and tab layout, what can I use for transfer data from my activity to view pager fragment like Intent or etc.
Here is my code
ControlAccountPassword.java
public class ControlAccountPassword extends AppCompatActivity {
private TabLayout tab_Layout;
private AppBarLayout appBarLayout;
private ViewPager view_Pager;
private ImageView img1;
private String temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_p_change_p);
//Get Intent Data
Intent intent=getIntent();
temp=intent.getStringExtra("email");
tab_Layout=(TabLayout)findViewById(R.id.tabLayout);
appBarLayout=(AppBarLayout)findViewById(R.id.appBar);
view_Pager=(ViewPager)findViewById(R.id.viewPager);
img1=(ImageView)findViewById(R.id.imgBack);
//adding fragment
ViewPagerAdapter adapter=new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new FragmentEditProfile(),"Edit Profile");
adapter.AddFragment(new FragmentChangePassword(),"Change Password");
//adapter setting
view_Pager.setAdapter(adapter);
tab_Layout.setupWithViewPager(view_Pager);
//onClickListener
onClickBack(this);
}
public void onClickBack(ControlAccountPassword view){
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ControlAccountPassword.super.onBackPressed();
System.exit(1);
}
});
}
}
FragmentEditorProfile.java
public class FragmentEditProfile extends Fragment {
View view;
private ProgressDialog progress;
private String URL;
private String name,phone,email;
private GetURL getURL=new GetURL(URL);
public FragmentEditProfile() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.edit_profile,container,false);
return view;
}
public void getDataPelanggan(){
progress = new ProgressDialog(getActivity());
progress.setCancelable(false);
progress.setMessage("Loading. . .");
progress.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getURL.GetMyURL())
.addConverterFactory(GsonConverterFactory.create())
.build();
PelangganAPI api = retrofit.create(PelangganAPI.class);
//Call<PelangganList> call = api.getPelanggan();
}}

create new class and extends Application:
public class YourClassName extends Application {
public Context context;
public static int iID;
public static String sDeviceID;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
you can change public static var's value everywhere or using vars everywhere you want:
in other class:
YourClassName.sDeviceID = "EB67";
and in another class:
int iVar;
String sVar;
iVar = YourClassName.iID;
sVar = YourClassName.sDeviceID;

Related

Get different data via Retrofit for the Fragment in FragmentPagerAdapter for the several tablayout tabs

Conditions:
I have an Activity and I'm creating PagerAdapter extends FragmentPagerAdapter with one Fragment class. TabLayout includes 10 tabs. I have TabLayout.addOnTabSelectedListener and there in onTabSelected() I am updating some custom variable in app's SharedPreferences which depends on current tab name and tab index. Tab's names are not static - there are loading from server too.
My task:
With this value I should make a retrofit2 Call to my server and load values in adapter with recyclerview for my Fragment.
My problem:
I am loading the same data for the different tabs, which should contatin different data! I am understand that this happens because in all cases I have the same SharedPreferences variable's value so I am making retrofit Call with same conditions.
setOffscreenPageLimit() can't be setted to 0 - default is 1 according documentation:
https://developer.android.com/reference/kotlin/androidx/viewpager/widget/ViewPager#setoffscreenpagelimit;
setUserVisibleHint() on SO I've found this like some variant for solving my problem, but it can't be overrided because is deprecated now.
Solution:
I think I should save previous and next tab name in some way and then I can make different parallel retrofit Calls with different conditions. When tab selected I can get current, previous and next tab name. But how, where and when I should make two more retrofit calls?
UPD 08.02.2022: Still thinking about this problem.
Code:
SomeActivity.java
public class SomeActivity extends BaseActivity {
private String TAG="SomeActivity";
private Context context;
private TabLayout tabs;
private ViewPager viewpager;
private ProgressBar PBLoading;
private PagerAdapter_SomePAdapter adapter;
List<String> names = new ArrayList<>();
private String[] tabTitles;
public String previousTabName;
public String nextTabName;
public int counterForPreviousTabName;
public int counterForNextTabName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
context = getApplicationContext();
String categories = AppPreferences.getCategories(context);
tabTitles = categories.split(";");
tabs = findViewById(R.id.tabs);
viewpager = findViewById(R.id.viewpager);
PBLoading = findViewById(R.id.PBLoading);
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d(TAG, "onTabSelected");
AppPreferences.setCurrentValueForRetrofit(getApplicationContext(), tab.getPosition());
counterForPreviousTabName = tmpTab.getPosition() - 1;
counterForNextTabName = tmpTab.getPosition() + 1;
//here I can get tab names.
}
});
adapter = new PagerAdapter_SomePAdapter(getSupportFragmentManager(), SomeActivity.this);
viewpager.setAdapter(adapter);
adapter.updateTitleData(tabTitles);
tabs.setupWithViewPager(viewpager);
adapter.notifyDataSetChanged();
}
}
PagerAdapter_SomePAdapter.java:
public class PagerAdapter_SomePAdapter extends FragmentPagerAdapter {
int PAGE_COUNT = 2;
private String[] tabTitles = new String[] { "", ""};
private Context mContext;
Fragment_fragment fragment_fragment;
String TAG = "PagerAdapter_SomePAdapter";
public PagerAdapter_SomePAdapter(FragmentManager fm, Context context) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
fragment_fragment = new Fragment_fragment();
}
#Override public int getCount() {
return PAGE_COUNT;
}
#Override public Fragment getItem(int position) {
return fragment_fragment.newInstance(position + 1, tabTitles[position]);
}
#Override public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public void updateTitleData(String[] tabTitlesNew) {
tabTitles = tabTitlesNew;
PAGE_COUNT = tabTitlesNew.length;
notifyDataSetChanged();
}
}
Fragment_fragment.java:
public class Fragment_fragment extends Fragment {
private String TAG = "Fragment_fragment";
private static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
private View rootView;
private RecyclerView RV;
private Adapter_Items adapter;
public static Fragment_fragment newInstance(int page, String tabName) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Fragment_fragment fragment = new Fragment_fragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPage = getArguments().getInt(ARG_PAGE);
}
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext=context;
}
#SuppressLint("ClickableViewAccessibility")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.content_list, container, false);
RV = rootView.findViewById(R.id.recycler_view);
new loadDataAS().execute();
return rootView;
}
private void loadData(){
//retrofit call code;
}
class loadDataAS extends AsyncTask<Void, Void, Void> {
final ProgressDialog progress = new ProgressDialog(mContext);
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
loadData();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new Adapter_Items(arguments, arguments2, arguments3);
RV.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
Adapter_Items:
public class Adapter_Items extends RecyclerView.Adapter<Adapter_Items.ViewHolder>{
private LayoutInflater mInflater;
private Context mContext;
private static String TAG = "Adapter_Items";
public Adapter_Items(List<Integer>arguments, List<String>arguments2, List<String>arguments3){
//initializing arguments
}
// inflates the row layout from xml when needed
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recycle_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//setting view's information
}
#Override
public int getItemCount() {
return arguments.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
First thing,
fragment should contain different data
Saving tab name after tab selected will not work. You should remove this
AppPreferences.setCurrentValueForRetrofit(getApplicationContext(),
tab.getPosition());
You should call retrofit code inside the fragment with the tabName (Not from sharedPref) to get data for that tab.
For this, make the following changes,
You are already passing the tabName to fragment instance
newInstance(int page, String tabName)
use that tabName and pass to your AsyncTask -> loadData() as
loadData(tabName);
Then you can use that in your retrofit call and get the data.
Note:
setOffscreenPageLimit()
This method will load fragments just before they are completely visible. It would be useful and a great user experience to display data directly rather than fetching only when user selects the tab.

How to handle configuration change for fragment with view model

I want to make my fragment wont re-load the data when configuration change with view model.
So, i try to make an App about gitHub User.
My Main Activity contain Search view to search user and show the result with recyclerview.
My Detail Activity is showing the detail of user when one of user in the list clicked, and in my detail activity i use Tab Layout and view pager to show user's followers and following.
My ViewModel for activity works well and can keep my data when orientation change.
But when i do the same to my fragment, my fragment keep re-loading new data when orientation change.
Here my fragment
i use View Model to request data
public class FollowingFragment extends Fragment {
public static final String KEY_FOLLOWING = "key_following";
private RecyclerView recyclerView;
private FollowingViewModel followingViewModel;
private FollowingAdapter followingAdapter;
ShimmerFrameLayout shimmerFrameLayout;
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
ArrayList<FollowingResponse> followingResponse = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_following, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.rv_following);
shimmerFrameLayout = view.findViewById(R.id.shimmer_frame_layout2);
followingViewModel = ViewModelProviders.of(this).get(FollowingViewModel.class);
followingAdapter = new FollowingAdapter();
followingAdapter.setOnItemClickCallback(new FollowingAdapter.OnItemClickCallback() {
#Override
public void onItemClicked(FollowingResponse followingResponse) {
showSelectedItem(followingResponse);
}
});
//this is what i've tried and worked, but my fragment result with double or triple the data.
if (savedInstanceState == null){
}
else {
followingResponse = savedInstanceState.getParcelableArrayList(KEY_FOLLOWING);
}
showRecyclerView();
getData();
}
private void getData() {
followingViewModel.setDataFollowing(DetailUserActivity.clickedUser);
followingViewModel.getDataFollowing().observe(getViewLifecycleOwner(), new Observer<ArrayList<FollowingResponse>>() {
#Override
public void onChanged(ArrayList<FollowingResponse> followingResponses) {
shimmerFrameLayout.setVisibility(View.GONE);
shimmerFrameLayout.stopShimmer();
followingAdapter.setData(followingResponse);
followingResponse.addAll(followingResponses);
recyclerView.setAdapter(followingAdapter);
followingAdapter.notifyDataSetChanged();
}
});
}
private void showRecyclerView() {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
}
#Override
public void onResume() {
super.onResume();
followingViewModel.setDataFollowing(DetailUserActivity.clickedUser);
}
private void showSelectedItem(FollowingResponse item) {
Intent intent = new Intent(getContext(), DetailUserActivity.class);
intent.putExtra("EXTRA_DATA", item.getLogin());
startActivity(intent);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
outState.putParcelableArrayList(KEY_FOLLOWING, followingResponse);
super.onSaveInstanceState(outState);
}
}
Detail Activity
public class DetailUserActivity extends AppCompatActivity {
private TextView tvName, tvNickname, tvLocation, tvCompany, tvEmail, tvWebsite;
private TextView tvCountFollowers, tvCountRepository, tvCountFollowing;
private ImageView imgProfile;
ProgressBar progressBar;
public static String clickedUser;
UserViewModel userViewModel;
private ViewPager viewPager;
TabLayout tabLayout;
private final String EXTRA_DATA = "EXTRA_DATA";
private static final String EXTRA_FOLLOW = "extra_follow";
// Fragment followingFragment;
// FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_user_activity);
// i've tried this, but when the orientation change, my detail activity force close and throw me to my main activity.
// if (savedInstanceState != null){
// followingFragment = getSupportFragmentManager().getFragment(savedInstanceState, KEY_FOLLOWING);
// } else {
// followingFragment = new FollowingFragment();
//
// getSupportFragmentManager().beginTransaction().replace(R.id.tv_view_pager, followingFragment).commit();
// }
tvName = findViewById(R.id.tv_item_name);
tvNickname = findViewById(R.id.tv_item_nickname);
tvLocation = findViewById(R.id.tv_item_location);
tvCompany = findViewById(R.id.tv_item_company);
tvEmail = findViewById(R.id.tv_item_email);
tvWebsite = findViewById(R.id.tv_item_website);
imgProfile = findViewById(R.id.img_item_photo);
tvCountFollowers = findViewById(R.id.tv_count_follower);
tvCountRepository = findViewById(R.id.tv_count_repo);
tvCountFollowing = findViewById(R.id.tv_count_following);
progressBar = findViewById(R.id.progressbar2);
setForUserData();
setForTabLayout();
}
private void setForUserData(){
Intent detailIntent = getIntent();
clickedUser = detailIntent.getStringExtra("EXTRA_DATA");
userViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(UserViewModel.class);
userViewModel.setUserUVM(clickedUser);
userViewModel.getUserUVM().observe(this, new Observer<UserResponse>() {
#Override
public void onChanged(UserResponse userResponse) {
progressBar.setVisibility(View.GONE);
Glide.with(getApplicationContext())
.load(userResponse.getAvatarUrl())
.into(imgProfile);
tvName.setText(userResponse.getLogin());
tvLocation.setText(userResponse.getLocation());
tvNickname.setText(userResponse.getName());
tvCompany.setText(userResponse.getCompany());
tvEmail.setText(userResponse.getEmail());
tvWebsite.setText(userResponse.getBlog());
tvCountRepository.setText(String.valueOf(userResponse.getPublicRepos()));
tvCountFollowers.setText(String.valueOf(userResponse.getFollowers()));
tvCountFollowing.setText(String.valueOf(userResponse.getFollowing()));
}
});
}
private void setForTabLayout(){
tabLayout = findViewById(R.id.tv_tab_layout);
viewPager = findViewById(R.id.tv_view_pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int totalTab;
#SuppressWarnings("deprecation")
ViewPagerAdapter(FragmentManager fragmentManager, int totalTabs) {
super(fragmentManager);
this.totalTab = totalTabs;
}
#SuppressWarnings("ConstantConditions")
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FollowersFragment();
case 1:
return new FollowingFragment();
default:
return null;
}
}
#Override
public int getCount() {
return totalTab;
}
}
// #Override
// protected void onSaveInstanceState(#NonNull Bundle outState) {
// getSupportFragmentManager().putFragment(outState, KEY_FOLLOWING, followingFragment );
// super.onSaveInstanceState(outState);
// }
}
im trying to solve my FollowingFragment first, then ill do the same on my FollowerFragment.
im really new in programming, and have no one to ask.. can someone help me to solve my problem with keep data in fragment when orientation change?
followingViewModel = ViewModelProviders.of(this).get(FollowingViewModel.class);
In Fragment insted of writing this code in onViewCreated() write it inside OnCreate()
onViewCreated() will get called everytime the orientation changes so it will create new instance of view model everytime the orientation changes making viewmodel to reload the data
If you need to load data only once for the FollowingViewModel a good place to do it should be inside the constructor of the view model in this way you won't need to worry about the orientation change of the fragment.

FragmentStateAdapter onRefreshListener

how can i implement a onRefreshListener in fragments if i am using ViewPager (ViewPager 2) with FragmentStateAdapter.
I found only examples with FragmentPageAdapter.
the other code works so far, i mean swiping between fragments an displaying a list of strings.
Just the refresh (pull from top to bottom) don't work.
I just see the refresh symbol short and then it dissapears.
In the debugger the onRefresh functions will not be called, after a refresh action.
This is my Code:
main activity
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this, dataManager));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewpager
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 3;
private DataManager dataManager;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, DataManager dataManager) {
super(fragmentActivity);
this.dataManager = dataManager;
}
#NonNull #Override public Fragment createFragment(int position) {
Fragment fragment = null;
if (position == 0)
{
fragment = new FragmentA();
Bundle bundle = new Bundle(2);
bundle.putString("TOKEN", dataManager.getToken());
bundle.putString("SERVER_URL", dataManager.getServerURL());
fragment.setArguments(bundle);
}
else if (position == 1)
{
fragment = new FragmentB();
}
else if (position == 2)
{
fragment = new FragmentC();
}
return fragment;
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
fragment
public class FragmentA extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeLayout;
private Bundle bundle;
private ListView mainListView;
private LibrariesAdapter listAdapter;
private LibraryDataManager libraryDataManager;
private RecyclerViewAdapter adapter;
private GetLibrariesTask getLibrariesTask;
private String token;
private String serverUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = getArguments();
if (bundle != null) {
token = bundle.getString("TOKEN");
serverUrl = bundle.getString("SERVER_URL");
libraryDataManager = new LibraryDataManager(token, serverUrl);
} else {
// ToDo show error or something else
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
swipeLayout = rootView.findViewById(R.id.swiperefresh);
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainListView = view.findViewById(android.R.id.list);
ArrayList<Library> librariesList = new ArrayList<>();
listAdapter = new LibrariesAdapter(getActivity(), librariesList);
mainListView.setAdapter(listAdapter);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
}
});
}
private class GetLibrariesTask extends AsyncTask<Void, Void, List<Library>> {
#Override
protected List<Library> doInBackground(Void... args) {
List<Library> libraries = libraryDataManager.getLibraries();
return libraries;
}
#Override
protected void onPostExecute(List<Library> libraries) {
listAdapter.clear();
listAdapter.addAll(libraries);
listAdapter.notifyDataSetChanged();
Logger.debug("on refresh2");
// swipeLayout.setRefreshing(false);
}
}
}

switch fragment code to activity code

hi i am begineer on android ,i have an app that contains a history fragment I am trying to convert my Fragment Code to Activity code !(i want to start this activity after button click) but i don't know how to do that so please help me
here's my fragment :
public class HistoryFragment extends Fragment implements MainActivity.FragmentRefresh {
ImageView ivSettings;
private FragmentActivity mContext;
private RecyclerView rvInsta;
//DB
private DBController dbcon;
private ImageRecyclerAdaptor imageRecyclerAdaptor;
public static HistoryFragment newInstance() {
//Bundle args = new Bundle();
//args.putString(ARG_PAGE, title);
HistoryFragment fragment = new HistoryFragment();
//fragment.setRetainInstance(true);
//fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Tag1","MoviesFrag");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_history, container, false);
mContext =getActivity();
//DB
dbcon = new DBController(mContext);
rvInsta= (RecyclerView) rootView.findViewById(R.id.rvInstaImages);
imageRecyclerAdaptor = new ImageRecyclerAdaptor(mContext);
rvInsta.setAdapter(imageRecyclerAdaptor);
rvInsta.setLayoutManager(new LinearLayoutManager(mContext));
rvInsta.setHasFixedSize(true);
rvInsta.setItemViewCacheSize(20);
rvInsta.setDrawingCacheEnabled(true);
rvInsta.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
//rvInsta.s/
imageRecyclerAdaptor.notifyDataSetChanged();
return rootView;
}
#Override public void refresh() {
if (imageRecyclerAdaptor!=null) {
imageRecyclerAdaptor.onRefreshh();
}
}
}
public class MainActivity extends AppCompatActivity implements FragmentRefresh{
ImageView ivSettings;
private RecyclerView rvInsta;
//DB
private DBController dbcon;
private ImageRecyclerAdaptor imageRecyclerAdaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_history);
dbcon = new DBController(this);
rvInsta= (RecyclerView) findViewById(R.id.rvInstaImages);
imageRecyclerAdaptor = new ImageRecyclerAdaptor(this);
rvInsta.setLayoutManager(new LinearLayoutManager(this));
rvInsta.setAdapter(imageRecyclerAdaptor);
rvInsta.setHasFixedSize(true);
rvInsta.setItemViewCacheSize(20);
rvInsta.setDrawingCacheEnabled(true);
rvInsta.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
imageRecyclerAdaptor.notifyDataSetChanged();
}
#Override public void refresh() {
if (imageRecyclerAdaptor!= null) {
imageRecyclerAdaptor.onRefreshh();
}
}
}

Parse Recyclerview Data between fragments

I have a recyclerview in a fragment which displays a list of movies. i want to when user clicks item, it opens a new fragment which will be detailed page of that item.
I have tried bundles and intent putExtra but does not work, keeps coming up with null pointer error.
i have tried with Hardcoded strings as a test and works fine but trying to get item POJO data does not.
Anyone have an idea how to parse data between fragments from recyclerview onclick function?
1st Fragment which displays recyclerview data:
public class HomeFragment extends Fragment {
private static final String TAG = HomeFragment.class.getSimpleName();
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private MovieAdapter mAdapter;
private List<Movie> movieList;
private TextView title;
private final static String API_KEY = "670d03a721dd007862c0181bfd097e5d";
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for this fragment
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
FragmentTransaction fragTrans = getFragmentManager().beginTransaction();
MovieDetail movieDetail = new MovieDetail();
//Bundle Send Data
Bundle bundle = new Bundle();
bundle.putString("title", movieList.get(position).getTitle());
movieDetail.setArguments(bundle);
fragTrans.replace(R.id.container_body, movieDetail);
fragTrans.isAddToBackStackAllowed();
fragTrans.addToBackStack(null);
fragTrans.commit();
}
}));
return rootView;
}
private void initData() {
ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
Call<MovieResponse> call = api.getMostPopularMovies(API_KEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statusCode = response.code();
List<Movie> movies = response.body().getResults();
mRecyclerView.setAdapter(new MovieAdapter(movies, R.layout.list_item_movie, getContext()));
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d(TAG, t.toString());
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Detail Fragment:
public class MovieDetail extends Fragment {
private TextView titleTv;
public MovieDetail() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// // Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie_detail, container, false);
titleTv = (TextView) view.findViewById(R.id.detailTitleTV);
Bundle bundle = getArguments();
titleTv.setText(String.valueOf(bundle.getString("title")));
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
/**
* .
*/
}
i have looked at other questions similar but they deal with hardcoded Strings not POJO data for item click. Any help appreciated
You should create a class which extends parcelable and then pass the object in the bundle, then access each field with get methods.

Categories