I am sending arraylist from gridviewadapter to the fragment but data its not displayed. the gridview code was working when sending arraylist to an activity, so the problem is with the fragment
this is the grid view adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("entering adapter1");
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.imageView = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Listitem item = getItem(position);
System.out.println("item.getUrl() ");
System.out.println(item.getUrl());
Picasso.with(mcontext).setIndicatorsEnabled(true);
holder.imageTitle.setText(item.getId());
/* Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(holder.imageView)
;*/
//int maxSize = 4 * 1024 * 1024; // 4MiB
//Picasso myNewPicasso = new Picasso.Builder(mcontext).memoryCache(new LruCache(maxSize)).build();
Picasso.with(mcontext)
.load(item.getUrl())
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(holder.imageView);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<Listitem> personArrayList = new ArrayList<>();
personArrayList.add(new Listitem(item.getId(), item.getUrl()));
Intent intent = new Intent(mcontext,SingleViewActivity.class);
intent.putExtra("Person_List", personArrayList);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(intent);
Log.d("OnImageButton", "Clicked");
}
});
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView imageView;
}
this is the fragment that contain also a view pager
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
Log.d("s","adapterview");
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
ImageView imageView;
int imageResourceId;
int numberSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
Log.d("s","fragview");
}
public static Fragment newInstance(Context context,ArrayList<Listitem> personArrayList, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args= new Bundle();
args.putParcelableArrayList("Person_List", personArrayList);
//args.putInt("",imageResourceId);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
A bit explanation of what I am doing
In my main activity I have a grid view of image, when I click on one image , I get the single image-clicked on a new activity. I used that with parcelable arraylist that send data from gridview to singleview acitivity. it was working for the activity. but when I implemented the viewpager and the fragment and fragment adapter nothing is showing I dont know why,
this is my logcat , as you notice its not proceeding to the rest,fragview is a log print added in my code.
01-11 20:54:40.814 3323-3323/com.justedhak.www.i D/Activity: performCreate Call secproduct feature valuefalse
01-11 20:54:40.814 3323-3323/com.justedhak.www.i D/Activity: performCreate Call debug elastic valuetrue
01-11 20:54:40.829 3323-3323/com.justedhak.www.i D/s: fragview
01-11 20:54:40.839 3323-3323/com.justedhak.www.i D/s: fragview
01-11 20:54:40.954 3323-3323/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#211f949f time:9248062
this is part of the fragment code in Singleviewactivity.java
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
ImageView imageView;
int imageResourceId;
int numberSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
Log.d("s","fragview");
}
public static Fragment newInstance(Context context,ArrayList<Listitem> personArrayList, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args= new Bundle();
args.putParcelableArrayList("Person_List", personArrayList);
//args.putInt("",imageResourceId);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
Moudiz,
You need to change your DemoCollectionPagerAdapter constructor to accept the ArrayList of people as such:
DemoCollectionPagerAdapter(FragmentManager fm, ArrayList<Listitem> personArrayList)
With the new constructor be sure to pass this to your adapter object when you first create it at the SinglePageActivity View.
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
Bundle bundle = getIntent().getExtras();
ArrayList<Listitem> personList = getIntent().getParcelableArrayListExtra("Person_List");
// Pass it here using your new constructor.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager(), personList);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
The next part is for you to figure out because it is rather confusing why you are passing in your ArrayList when you create a Fragment object here :
public static Fragment newInstance(Context context,ArrayList<Listitem> personArrayList, int numberSelected) {
Let me know if this helps.
Related
This question is something serious for me , i need to someone help me regarding this. Actually i am creating an RSS feed app by combining navigation drawer and view pager tabbed activity. i want to pass a string value from one fragment to other fragment. here is the thing. It was working properly when it was with the navigation drawer activity but after combining with view-pager , String is not passing to other fragment through bundle, i can't find the error because its not showing any error,
This is from i am passing string
public class RssFragment extends Fragment implements OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
startService();
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService.class);
getActivity().startService(intent);
}
/**
* Once the {#link RssService} finishes its task, the result is sent to this BroadcastReceiver
*/
private BroadcastReceiver resultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>) intent.getSerializableExtra(RssService.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getDescription());
String string;
string=uri.toString();
result Des_1=new result();
FragmentManager fragmentManager1 =getActivity().getSupportFragmentManager();
fragmentManager1.beginTransaction().replace(R.id.content_main_layout_frame,Des_1 ).addToBackStack("fragBack").commit();
result ldf = new result();
Bundle args = new Bundle();
args.putString("YourKey", string);
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_main_layout_frame, ldf).commit();
}
#Override
public void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter(RssService.ACTION_RSS_PARSED);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(resultReceiver, intentFilter);
}
#Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(resultReceiver);
}
}
This is how i am receiving the string
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
Bundle bundle = getArguments();
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(bundle != null) {
String value = bundle.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
I pleasing someone to figure it out. i repeat it was working but now its not
It is another fragment
public class datafragment extends Fragment {
View view;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.sample,container,false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new sliderAdapter(getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
private class sliderAdapter extends FragmentPagerAdapter{
final String tabs[]={"tab1", "tab2","tab3"};
public sliderAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new RssFragment();
break;
case 1:
fragment = new RssFragment();
break;
case 2:
fragment = new RssFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
}
Try the below one,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.replace(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Remove both the transaction and add the below code instead,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.add(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Let me know if that helps!
Try this
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(savedInstanceState!= null) {
String value = savedInstanceState.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
I used to get Bundle in activity like this and it worked fine
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singleview);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// list = (ListView) findViewById(R.id.ListView);
toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(this).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
My problem is I want to get arraylist paracble in fragment
I am having error in word bundle in the below code
ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");
I though using instance:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
imageResourceId = getArguments().getInt("param");
numberSelected = getArguments().getParcelableArrayList("number"); // this is wrong but i was trying something
}
public Fragment newInstance(int imageResourceId, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
f.imageResourceId = imageResourceId;
f.numberSelected = numberSelected;
}
this is my code for your reference
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
DemoCollectionPagerAdapter
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
ImageView imageView;
int imageResourceId;
int numberSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
imageResourceId = getArguments().getInt("param");
numberSelected = getArguments().getInt("number");
}
public Fragment newInstance(int imageResourceId, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
f.imageResourceId = imageResourceId;
f.numberSelected = numberSelected;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(mcontext).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
It works for me, if it doesn't work for you post the error message from the logcat,
ArrayList<Listitem> personArrayList;
//To put your arraylist
Bundle b = new Bundle();
b.putParcelableArrayList("Person_List", personArrayList);
//To get your arraylist
Bundle extras = getIntent().getExtras();
personArrayList = extras.getParcelableArrayList("Person_List");
I need to know how to get array list using Bundle in fragment , in the examples I have seen they are using ints or strings. how to get fragments ? In my activity it was working good getting the arraylist
my updated code
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
ArrayList<Listitem> personArrayList = new ArrayList<Listitem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
/*
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);*/
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public static final String ARG_OBJECT = "Person_List";
public DemoCollectionPagerAdapter(FragmentManager fm, ArrayList<Listitem> personArrayList)
{
super(fm);
Log.d("s","adapterview");
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_PERSON_LIST, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<Listitem> items;
public DemoObjectFragment newInstance(ArrayList<Listitem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<Listitem>();
}
// use this.items as you wish, but it will be empty if you didn't set the Bundle argument correctly
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
I have 2 errors now :
for newInstance as I mentioned before I cannot refer to not static .
and I am getting error now for picasso
edit 3
This is a good start for what you are looking for and assumes you have correctly implemented Parcelable for the ListItem class.
Somewhere in your Activity
ArrayList<ListItem> personArrayList = new ArrayList<ListItem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
From the top of your Fragment class (note: it is not a static class)
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<ListItem> items;
public static DemoObjectFragment newInstance(ArrayList<ListItem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<ListItem>();
}
/*
* use this.items as you wish, but
* it will be empty if you didn't set the
* Bundle argument correctly
*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
Log.i("DemoObjectFragment", "Inside onCreateView");
if (this.items.isEmpty()) {
Log.i("DemoObjectFragment", "Warning: There are no items!");
}
if (this.items != null) {
for (Listitem person : items) {
Picasso.with(getActivity())
.load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("DemoObjectFragment", "Person URL: " + String.valueOf(person.url));
}
} else {
Log.i("DemoObjectFragment", "Oh no! items is null!");
}
return rootView;
}
}
From what I see the fragment has no way of knowing what personArrayList you are referring to. Usually you pass the list as an extra argument in the newInstance method (step 1), save it in the bundle (step 2) and then retrieve it from the bundle in onCreate (step 3).
To fix you code you would have to either initialize the list with a new ArrayList(), but it would be empty in that case, or do as I said above (you're just missing step 1, so you're almost done).
Only the first fragment is populated with the image, the second fragment is blank. I am using the same adapter for both fragments. I am not sure where is the problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mSectionsPagerAdapter.addFragment(PopularMoviesFragment.newInstance(SORT_POPULAR), "MOST POPULAR");
mSectionsPagerAdapter.addFragment(RatingMoviesFragment.newInstance(SORT_RATING), "TOP RATING");
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void switchToDetail(Intent intent){
startActivity(intent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
static class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
First fragment
public static PopularMoviesFragment newInstance(String sort) {
PopularMoviesFragment fragment = new PopularMoviesFragment();
Bundle args = new Bundle();
args.putString("sort", sort);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sortOrder = getArguments().getString("sort");
mContext = getActivity();
if (savedInstanceState != null) {
mPopularList = savedInstanceState.getParcelableArrayList(POPULAR_LIST);
for (Movie m : mPopularList) {
Log.d(LOG_TAG, "onCreate: " + m.getTitle());
}
} else {
FetchPopularMovies pm = new FetchPopularMovies();
pm.execute(SORT_POPULAR);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View pView = inflater.inflate(R.layout.fragment_popular_movies, container, false);
mAdapter = new MoviePosterAdapter(mContext, mPopularList);
mProgressBar = (ProgressBar) pView.findViewById(R.id.movies_progress_bar);
RecyclerView mRecyclerView = (RecyclerView) pView.findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return pView;
}
Second fragment
public static RatingMoviesFragment newInstance(String sort) {
RatingMoviesFragment fragment = new RatingMoviesFragment();
Bundle args = new Bundle();
args.putString("sort", sort);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sortOrder = getArguments().getString("sort");
mContext = getActivity();
if (savedInstanceState != null) {
Log.d(LOG_TAG, "Has saved instance");
mRatingList = savedInstanceState.getParcelableArrayList(RATING_LIST);
} else {
FetchRatingMovies rm = new FetchRatingMovies();
rm.execute(SORT_RATING);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_rating_movies, container, false);
ratingAdapter = new MoviePosterAdapter(mContext, mRatingList);
mProgressBar = (ProgressBar) view.findViewById(R.id.movies_progress_bar);
RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(ratingAdapter);
return view;
}
MoviePosterAdapter
public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.ViewHolder> {
private final String LOG_TAG = MoviePosterAdapter.class.getSimpleName();
final Context mContext;
private ArrayList<Movie> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
//public final View mView;
public final ImageView mImageView;
public ViewHolder(View view) {
super(view);
mImageView = (ImageView) view.findViewById(R.id.imageView);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MoviePosterAdapter(Context context, ArrayList<Movie> myDataset) {
this.mContext = context;
mDataset = myDataset;
}
public void setMoviesData(ArrayList<Movie> moviesData){
mDataset = moviesData;
}
// Create new views (invoked by the layout manager)
#Override
public MoviePosterAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(mContext).inflate(R.layout.movie_poster, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Movie mMovie = mDataset.get(position);
//Creating URL for image
final String POSTER_BASE_URL = "http://image.tmdb.org/t/p/";
final String SIZE_PATH = "w185";
String IMG_PATH = mMovie.getImg();
//Loading image using Glide
Glide.with(holder.mImageView.getContext())
.load(POSTER_BASE_URL + SIZE_PATH + IMG_PATH)
.placeholder(R.color.grid_placeholder_bg)
.into(holder.mImageView);
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, DetailActivity.class);
i.putExtra("id", mMovie.getId());
i.putExtra("title", mMovie.getTitle());
if (mContext instanceof MainActivity) {
MainActivity main= (MainActivity) mContext;
main.switchToDetail(i);
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
Please help me!
EDIT: Both the arrays are not empty. Here is the issue I think, only one fragment gets populated, maybe because there is some problem with the adapter(not sure). If I try to stop first fragment to get populated(commenting out the notifyDatasetChanged()), then the second fragment works fine.
The image wasn't populating in the second fragment because it was an issue with Glide library. Switched to Picasso. Works fine.
I checked your code and i found that everything is fine. I tried with dummy data so i am damn sure that the mistake is in your data or adapter where you are setting data. Just try once with dummy data so you will be more clear or if still you are getting blank screen then let me know.
Generally blank screen comes because of there is no data. so please check once..
I'm trying to implement an activity with tabs in action bar and a view pager. I have the same fragment for every tab.
I need to update fragments after onCreateView is called, passing objects.
Pager adapter :
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return cat_pages.getList_categories().size();
}
#Override
public Fragment getItem(int position) {
Log.i("position fragment", "i = " + position);
final Handler uiHandler = new Handler();
int index = position;
final Category cat = cat_pages.getList_categories().get(index);
Log.i("position fragment", "name = " + cat.getName());
mCategoriesFragment = new ListPostFragment();
return mCategoriesFragment;
}
}
Fragment :
public class ListPostFragment extends Fragment {
// Layouts
private LinearLayout layout_loading;
public static GridView list_view_articles;
private TextView txt_nothing, txt_title;
// The list of headlines that we are displaying
private List<Post> mPostsList = new ArrayList<Post>();
private List<Post> list_posts = new ArrayList<Post>();
// The list adapter for the list we are displaying
private ArticlesAdapter mListAdapter;
private Category mCurrentCat;
Category clicked_cat;
String activity;
String title;
public ListPostFragment() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListAdapter = new ArticlesAdapter(getActivity(), mPostsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_grid_posts, container, false);
layout_loading = (LinearLayout) rootView.findViewById(R.id.layout_loading);
list_view_articles = (GridView) rootView.findViewById(R.id.gridViewArticles);
txt_nothing = (TextView) rootView.findViewById(R.id.txt_no_result);
txt_title = (TextView) rootView.findViewById(R.id.txt_title);
Log.i("frag", "frag create view");
return rootView;
}
#Override
public void onStart() {
super.onStart();
list_view_articles.setAdapter(mListAdapter);
}
public void loadPosts(Category clicked_cat, List<Post> list_posts, String title) {
Log.i("frag", "frag load");
layout_loading.setVisibility(View.VISIBLE);
list_view_articles.setVisibility(View.GONE);
txt_title.setVisibility(View.GONE);
mPostsList.clear();
layout_loading.setVisibility(View.GONE);
if(list_posts != null){
mPostsList.addAll(list_posts);
if(mPostsList.size() > 0){
list_view_articles.setVisibility(View.VISIBLE);
txt_nothing.setVisibility(View.GONE);
}else{
list_view_articles.setVisibility(View.GONE);
txt_nothing.setVisibility(View.VISIBLE);
}
mListAdapter.notifyDataSetChanged();
}else{ // Nothing to display
list_view_articles.setVisibility(View.GONE);
txt_nothing.setVisibility(View.VISIBLE);
}
}
}
==> What I need to to call loadPosts(...) in PagerAdapter getItem(), once onCreateView has been called.
Any help is very appreciated.
You should pass your Category as an Extra to the fragment like so:
Bundle bundle = new Bundle();
bundle.putSerializable("CATEGORY", cat);
mCategoriesFragment.setArguments(bundle);
and then in onCreate() in the fragment you can read it using:
Bundle bundle = this.getArguments();
Category cat = (Category) bundle.getSerializable("CATEGORY");
// now you can call loadPosts()