Passing data between fragments with value not reference - java

I'm trying to pass MyData(Parcelable object including ArrayList) from AFragment to BFragment.
Certainly,it works.However,the problem is that when I pass data(MyData) from AFragment to BFragment, the reference of arraylist(mList) is the same. This causes when I change value of mList in BFragment, Value of mList in AFragment changes as well.
I have no idea to resolve the problem.
I've looked at various articles about Parcelable,and finally I found out that Parcelable recreate instance only when two objects is in different task.
How can I pass data with a new instance?
I wrote codes like below.
MyData:
public class MyData implements Parcelable {
public List<String> mList = new ArrayList<>(0);
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeStringList(mList);
}
public static final Parcelable.Creator<MyData> CREATOR = new Parcelable.Creator<MyData>() {
public MyData createFromParcel(Parcel in) {
return new MyData(in);
}
public MyData[] newArray(int size) {
return new MyData[size];
}
};
private MyData(Parcel in) {
in.writeStringList(mList);
}
public MyData() {
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SampleFragment sampleFragment = new SampleFragment();
replaceFragment(sampleFragment);
}
public void replaceFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
if (manager.findFragmentByTag(fragment.getClass().getCanonicalName()) != null) {
return;
}
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_layout, fragment, fragment.getClass().getCanonicalName());
transaction.addToBackStack(null);
transaction.commit();
}
}
AFragment:
public class SampleFragment extends Fragment implements View.OnClickListener {
MainActivity mActivity;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (MainActivity) context;
}
#Override
public void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sample1, container, false);
view.findViewById(R.id.button).setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.button) {
List<String> list = new ArrayList<>(0);
list.add("sample1");
list.add("sample2");
list.add("sample3");
HogeData data = new HogeData();
data.mList = list;
SampleFragment2 sampleFragment2 = new SampleFragment2();
Bundle bundle = new Bundle();
bundle.putParcelable(sampleFragment2.getClass().getCanonicalName(), data);
sampleFragment2.setArguments(bundle);
mActivity.replaceFragment(sampleFragment2);
}
}
}
BFragment:
public class SampleFragment2 extends Fragment {
MainActivity mActivity;
HogeData mData;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (MainActivity) context;
}
#Override
public void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
mData = bundle.getParcelable(getClass().getCanonicalName());
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable final Bundle savedInstanceState) {
return inflater.inflate(R.layout.sample2, container, false);
}

Related

Material Container Transform animation not working in Java

Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.
RecyclerView Adapter Class(source)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private Context context;
private List<Astadhyayi> wordList;
private List<Astadhyayi> filwordList;
private DictionaryDB dictionaryDB;
private OnclickListenerInterface listener;
public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Astadhyayi>(itemList);
}
public void setClickListener(OnclickListenerInterface onclickListener) {
this.listener = onclickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Astadhyayi word = wordList.get(position);
holder.rsutras.setText(word.mSutras);
// Animation******
holder.rsutras.setTransitionName(word.getMSutras());
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
} else {
holder.bookmark.setImageDrawable(null);
}
}
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Astadhyayi> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Astadhyayi item : filwordList) {
if (item.getMSutras().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Astadhyayi>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView rsutras;
private ImageView bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rsutras = itemView.findViewById(R.id.tvSansTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
/*
#Override
public void onClick(View view) {
if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);
}
*/
#Override
public void onClick(View view) {
int position = this.getAbsoluteAdapterPosition();
Astadhyayi word = wordList.get(position);
//*************** Bundle **************\\
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
bundle.putString("transition_name", word.getMSutras());
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.setReorderingAllowed(true);
fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
}
}
RecyclerView Fragment Class(source)
public class ShowtermsTwoFragment extends Fragment {
private RecyclerView rv;
private EditText tV;
private Toolbar toolbar;
private LinearLayoutManager layoutManager;
private static DictionaryDB db;
private RecyclerViewAdapter rvAdapter;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
private List<Astadhyayi> wordsList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setExitTransition(new MaterialElevationScale(false));
setReenterTransition(new MaterialElevationScale(true));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
rv = view.findViewById(R.id.rvTerms);
tV = view.findViewById(R.id.tVinput);
//*********** TOOLBAR
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
// new Get_DbData().execute();
databaseCheck();
recyclerCheck1();
postponeEnterTransition();
((ViewGroup) view.getParent()).getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
startPostponedEnterTransition();
return true;
}
});
}
private void databaseCheck() {
String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");
//*********** ### DATABASE OPENING ### ***********\\
db = DictionaryDB.getInstance(this.getActivity());
wordsList = db.getWords((sanskritWord));
}
private void recyclerCheck1() {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
rv.addItemDecoration(dividerItemDecoration);
rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);
rv.setAdapter(rvAdapter);
/////********** rvAdapter.setClickListener(this);
rvAdapter.notifyDataSetChanged();
}
}
Details Fragment Class(destination)
public class TermThreeDetailsFragment extends Fragment {
private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fabBtn;
private static DictionaryDB db;
private Astadhyayi word;
private BottomAppBar bottomAppBar;
private TextToSpeech pronunciation;
private AudioManager audio;
private String ttsID , trans;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MaterialContainerTransform transform = new MaterialContainerTransform();
transform.setScrimColor(Color.TRANSPARENT);
setSharedElementEnterTransition(transform);
setSharedElementReturnTransition(transform);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sutraTV = view.findViewById(R.id.tvSutra);
adhyayTV = view.findViewById(R.id.tVAdhyay);
padaTv = view.findViewById(R.id.tVPada);
sutraIdTV = view.findViewById(R.id.tVSutraId);
vrittiTV = view.findViewById(R.id.tvVritti);
fabBtn = view.findViewById(R.id.favFAB);
coordinatorLayout = view.findViewById(R.id.parentCordlayout);
bottomAppBar = view.findViewById(R.id.bottom_app_bar);
bundleCheckWithDb();
WordCheck();
}
private void bundleCheckWithDb() {
//*********** Geting Parcelable Data
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
trans = bundle.getString("transition_name");
adhyayTV.setText(word.getMAdhyay());
padaTv.setText(word.getMPada());
sutraIdTV.setText(word.getMSutra_id());
sutraTV.setText(word.getMSutras());
vrittiTV.setText(word.getMVritti());
}
//*********** DATABASE OPENING
db = DictionaryDB.getInstance(this.getActivity());
}
private void WordCheck() {
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
fabBtn.setImageResource(R.drawable.cards_heart);
} else {
fabBtn.setImageResource(R.drawable.cards_heart_white);
}
fabBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, fabBtn);
}
});
}
}
Error im getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)
From the current given information, I think you should do something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
}
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
Again, I am not sure what getMSutras() actually returns and if it's right to use that here.

Sending Data From Fragment to Fragment Using TabLayout

I’ve been having difficulties sending data from one fragment to another when utilizing a TabLayout. I’ve read copious amounts of online posts pertaining to how to do this and have had no success when implementing them myself.
I have four fragments set up in my application. I'm trying to send data gathered from an EditText element in the fourth fragment to the TextView element of the second fragment.
I don't get any errors, but the text does not show up in the second fragment. I don't know how to proceed from here. Thanks!
Fourth Fragment (sending Fragment)
public class settings extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.setl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
public interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
Second Fragment (receiving fragment)
public class tt extends Fragment {
TextView txtData;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.ttl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtData = (TextView)view.findViewById(R.id.txtData);
}
public void displayReceivedData(String message) {
txtData.setText("Data received: "+ message);
}
}
Main Activity
public class MainActivity extends AppCompatActivity implements settings.SendMessage {
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.view_pager + ":" + 1;
tt f = (tt) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
Something might be breaking in other part of your app.
Below is code of your working example.
class MainActivity
public class MainActivity extends AppCompatActivity implements Setting.SendMessage {
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),this );
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.sliding_tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.viewpager + ":" + 1;
tt f = (tt) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
class Setting
public class Setting extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.setl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
public interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
class tt
public class tt extends Fragment {
TextView txtData;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.tt, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtData = (TextView)view.findViewById(R.id.txtData);
}
public void displayReceivedData(String message) {
txtData.setText("Data received: "+ message);
}
}
class SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Tab1", "Tab2"};
private Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
if(position==0){
return new Setting();
}
else
return new tt();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}

viewpager using JSON

i have written code for image slider but i use drawable images..
Actually i want to know, How to use online images in slideshow instead of
drawables...please help me with complete code as i am new to android..
public class DealsFragment extends Fragment {
private PagerAdapter mPagerAdapter;
public static DealsFragment newInstance() {
DealsFragment fragment = new DealsFragment();
return fragment;
}
public DealsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_deals, container, false);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(getActivity(), ImageOneDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageTwoDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageThreeDeals.class.getName()));
mPagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), fragments);
pager.setAdapter(mPagerAdapter);
return view;
}
}
ImageOneDeals.java
public class ImageOneDeals extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if(container==null){
return null;
}
return (LinearLayout) inflater.inflate(R.layout.image1_deals,container,false);
}
}
ImagePagerAdapter.java
public class ImagePagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public ImagePagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments){
super(fragmentManager);
this.fragments=fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Your Deal Fragment:-
public class DealFragment extends Fragment {
private View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.slide_view_pager, container, false);
new GetUserImage().execute(); //run your webservices here
}
return rootView;
}
public class GetUserImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected String doInBackground(String... params) {
postUserImageData();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//save your data in a list
// set Adapter after you get data from webservices
mPager = (ViewPager) rootView.findViewById(R.id.slidePager);
ImagePagerAdapter viewImagePagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), TotalCount, imagearr);
mPager.setAdapter(viewImagePagerAdapter);
mPager.getCurrentItem();
}
public void postUserImageData() {
}
}
}
your Adapter:-
public class ImagePagerAdapter extends FragmentPagerAdapter {
private int numOfItemSize;
List<UserImage> arr1;
public ImagePagerAdapter (FragmentManager childFragmentManager, int num_pages, List<UserImage> customMessageListView) {
super(childFragmentManager);
this.numOfItemSize = num_pages;
this.arr1 = customMessageListView;
}
#Override
public Fragment getItem(int position) {
ImageOneDeals userImageDetailFragment = new ImageOneDeals ();
UserImage sc = arr1.get(position);
Bundle bundle = new Bundle();
bundle.putString("ProfilePic", sc.ProfilePic);
bundle.putString("Work", sc.Work);
bundle.putString("BirthTime", sc.BirthTime);
bundle.putString("Message", sc.Message);
userImageDetailFragment.setArguments(bundle);
return userImageDetailFragment;
}
#Override
public int getCount() {
return numOfItemSize;
}
}
your ImageOneDeals :-
public class ImageOneDeals extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Title = getArguments().getString("ProfilePic");
BirthTime = getArguments().getString("BirthTime");
Work = getArguments().getString("Work");
Message = getArguments().getString("Message");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = (View) inflater.inflate(R.layout.slide_user_image, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialiseViews();
}
public void initialiseViews() {
ImageView imgDetails = (ImageView) getView().findViewById(R.id.UserimageView);
TextView usrname = (TextView) getView().findViewById(R.id.userName);
TextView usrwork = (TextView) getView().findViewById(R.id.userWork);
// imgLoader.DisplayImage(Title,imgDetails);
Picasso.with(getActivity())
.load(Title)
.placeholder( R.mipmap.add_photo)
.error( R.mipmap.add_photo)
.into(imgDetails);
usrname.setText(Message);
usrwork.setText(Work);
}
}

Does ListFragments not automatically restore dataset?

I have a fragment that extends ListFragment and when I minimize the app and go back to it, the listview is empty.
Does it not restore automatically?
public class LocationListViewFrag extends ListFragment implements AdapterView.OnItemClickListener {
private static final String TAG = "LocationListViewFrag";
private ArrayList<LocationObj> mLocations = new ArrayList<>();
private LocationAdapter mTaxAdapter;
private LocationListViewListener mListener;
#Bind(R.id.listLabel)
TextView listLabel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTaxAdapter = new LocationAdapter(getActivity(), mLocations);
setListAdapter(mTaxAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tax_location_list, container, false);
ButterKnife.bind(this, v);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setOnItemClickListener(this);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (LocationListViewListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement LocationListViewListener");
}
}
public void setLocations(ArrayList<LocationObj> Locations) {
mLocations = Locations;
mTaxAdapter.clear();
mTaxAdapter.addAll(mLocations);
mTaxAdapter.notifyDataSetChanged();
if(mLocations.isEmpty()){
listLabel.setVisibility(View.VISIBLE);
} else {
listLabel.setVisibility(View.GONE);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LocationObj aLocation = mLocations.get(position);
Log.d(TAG, String.format("Clicked - %s", aLocation.toString()));
mListener.onLocationSelected(aLocation);
}
public interface LocationListViewListener {
void onLocationSelected(LocationObj LocationObj);
}
}
Activity
onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.free_tax_prep_providers_new);
initDrawer();
ButterKnife.bind(this);
if (savedInstanceState != null) {
//Restore the fragment's instance
mLocationListViewFrag = (LocationListViewFrag)getSupportFragmentManager().getFragment(savedInstanceState, "mLocationListViewFrag");
} else if (findViewById(R.id.fragment_container) != null) {
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
// Create a new Fragment to be placed in the activity layout
mLocationListViewFrag = new LocationListViewFrag();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, mLocationListViewFrag).commit();
}
}
onSavedInstance
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "mLocationListViewFrag", mLocationListViewFrag);
}
You can actually override onSaveInstanceState within the fragment itself instead of the activity. Doing that did the job for me when I was working with list fragments.

ViewPager with SherlockFragment always empty

Currently I have a tab host activity that contains SherlockFragment. In one of these tabs (Fragments), I want to implement a ViewPager that will show images (ImageView). I created a FragmentPagerAdapter and Fragment to add it in the ViewPager. But when I run the application, my ViewPager appears empty with no image in it.
Here are my classes:
BonusFragment.Java
public class BonusFragment extends SherlockFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getImages(); //Here I get the images for the viewpager
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.bonus_frag, container, false);
viewPager = (ViewPager) view.findViewById(R.id.pagr);
Q.ADAPTER = new BonusPagerAdapter(getActivity()
.getSupportFragmentManager(), myImagesList);
viewPager.setAdapter(Q.ADAPTER);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
BonusPagerAdapter.Java
private ArrayList<Bitmap> items;
public BonusPagerAdapter(FragmentManager fm, ArrayList<Bitmap> items) {
super(fm);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Fragment getItem(int position) {
Bitmap bitmap = items.get(position);
BonusImageFragment fragment = BonusImageFragment.newInstance("Glass 1");
fragment.setBitmap(bitmap);
return fragment;
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
BonusImageFragment.Java
public class BonusImageFragment extends SherlockFragment {
private Bitmap bitmap;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
private static String frag = "";
public BonusImageFragment() {
}
public static final BonusImageFragment newInstance(String message)
{
frag = message;
BonusImageFragment f = new BonusImageFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.glass_item, container, false);
ImageView image = (ImageView) v.findViewById(R.id.glass_view);
image.setImageBitmap(bitmap);
return v;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
Now why does my ViewPager always appears empty?
Fixed it... I had to change "getActivity().getSupportFragmentManager()" in "BonusFragment.Java" with "getChildFragmentManager()"

Categories