I want to send data from my activity to my fragment. What I'm doing now is the following.
String itemDescription = workAssignmentItem.getDescription();
Bundle bundle = new Bundle();
bundle.putString("itemDescription", itemDescription);
FirstFragment.newInstance(bundle);
Then in my Fragment I do:
public static FirstFragment newInstance(Bundle bundle) {
FirstFragment fragment = new FirstFragment();
fragment.setArguments(bundle);
return fragment;
}
However, when I try to do 'getArguments().getString("itemDescription");'in my onCreate, as so:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
description = getArguments().getString("itemDescription");
}
it will not work. getArguments returns null. I'm not quite sure why it returns null, since multiple sources on the internet say this is the way to do it.
Can anyone point me in the right direction?
thanks in advance
You dont need bundle to pass a single string in Fragment
String itemDescription = workAssignmentItem.getDescription();
FirstFragment.newInstance(itemDescription);
Fragment Change to like this :
public static FirstFragment newInstance(String itemDescription){
FirstFragment fragment=new FirstFragment();
bundle args=new Bundle();
args.putString("itemDescription",itemDescription);
fragment.setArguments(args);
return fragment;
}
and onCreate like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
description = getArguments().getString("itemDescription");
}
So actually i had this problem
"Bundle NULL"
I resolve it by implementing the method onFragmentResult.
Context : I want to pass my selected contact inside a fragment into a spinner inside an another fragment
Where i pass my data into the Bundle :
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.item_done) {
// Create a String array to store the names of the selected contacts
ArrayList<String> selectedContacts = new ArrayList<>();
for (int i=0; i < listView.getCount(); i++) {
if (listView.isItemChecked(i)) {
selectedContacts.add(listView.getItemAtPosition(i).toString());
}
}
// Add the String array to the bundle
Bundle bundle = new Bundle();
bundle.putStringArrayList("SELECTED_CONTACTS", selectedContacts);
Log.d("ContactsFragment", "Setting result with selectedContacts: " + selectedContacts);
getParentFragmentManager().setFragmentResult("SELECTED_CONTACTS", bundle);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here is where i retreive my data :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sender, container, false);
// Find the spinner views in the layout and set their adapters
responsesSpinner = view.findViewById(R.id.responses_spinner);
contactsSpinner = view.findViewById(R.id.contacts_spinner);
getParentFragmentManager().setFragmentResultListener("SELECTED_CONTACTS", this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
if (requestKey.equals("SELECTED_CONTACTS")) {
ArrayList<String> selectedContacts = bundle.getStringArrayList("SELECTED_CONTACTS");
Log.d("SenderFragment", "Received selectedContacts: " + selectedContacts);
if (selectedContacts != null && selectedContacts.size() > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, selectedContacts);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
contactsSpinner.setAdapter(adapter);
}
}else{
Toast.makeText(getContext(), "not working", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
Related
i have an activity with multiple buttons , when clicking a button a new activity with two fragments get opened .
i am trying to display a Recyclerview in one of those fragments depending on the button pressed .
the problem is the bundle is null so the recyclerview doesnt show .
the bundle is not null in onAttach,but its null in settextview method
fragment
public class MyFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private static TextView input ;
private static RecyclerView rv ;
private Handler mhandler = new Handler();
public Bundle bundle;
public String data;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_my, container, false);
input =view.findViewById(R.id.input);
rv =view.findViewById(R.id.rv);
return view;
}
public void setTextView(String text){
input.setText(text);
String[] numberList = input.getText().toString();
final Integer[] numbers = new Integer[numberList.length];
ArrayList<String> List ;
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
ListAdapter adapter = new ListAdapter() ;
rv.setAdapter(adapter);
System.out.println("setextview "+bundle);
if(bundle != null){
if (sort1.equals("se")) {
ClassA m1 = new ClassA();
List = m1.etap(numbers);
adapter.setList(mystepsList);
}else if (sort1.equals("in")) {
ClassB = new ClassB();
List = m1.etap(numbers);
adapter.setList(mystepsList);
} }
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
bundle = getActivity().getIntent().getExtras();
sort1 =b.getString("value");
System.out.println("onAttach "+bundle);
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}}
You can it if get extra is null or null, if not null again you can cross check with the key you want to get via containsKey() to check if bundle have data respective to this key or not.
Bundle bundle = getIntent.getExtras();
if (bundle!=null && bundle.containsKey("value") {
boolean value = bundle.getStringExtra("value");
} else {
Log.i("MainActivity", "Bundle is Null or don't have key");
}
Try this code to pass data from activity to fragment
In Activity
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
In Fragment
Bundle bundle= getArguments();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle= getArguments();
if(bundle!=null){
String strtext = bundle.getString("edttext");
}
return inflater.inflate(R.layout.fragment, container, false);
}
i'm trying to send data from my activity class to its tab fragment, but in the fragment adapter it received no data and produced error nullPointerException.
here is my code
from activity
Intent receivedIntent = getIntent();
String tenant = null;
if ((bundle = receivedIntent.getExtras()) != null) {
tenant = (String) bundle.get("tenant");
}
TabFragment tabFragment = new TabFragment();
bundle.putString("tenant", tenant);
tabFragment.setArguments(bundle);
to fragment
Bundle getTenant = this.getArguments();
if(getTenant != null) {
tenant = getTenant.getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
pager adapter
case 0:
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);
return tabFragment;
In your fragment do this
if(getArguments() != null) {
tenant = getArguments().getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
instead of
Bundle getTenant = this.getArguments();
if(getTenant != null) {
tenant = getTenant.getString("tenant");
System.out.println("Tab fragment: " + tenant);
}else {
System.out.println("Tab fragment: null");
}
Use below code:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Another way You are able to pass data using Interface like Below:
1 step: I created public interface in my Activity and setter for it:
Private OnAboutDataReceivedListener mAboutDataListener;
public interface OnAboutDataReceivedListener {
void onDataReceived(YourModelClass model);
}
public void setAboutDataListener(OnAboutDataReceivedListener listener) {
this.mAboutDataListener = listener;
}
2 step: I implemented this interface in my Fragment and set listener:
public class YourActivity extends BaseFragment implements YourBaseActivity.OnAboutDataReceivedListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (YourActivity) getActivity();
mActivity.setAboutDataListener(this);
}
3 step: I overrided interface's method:
#Override
public void onDataReceived(YourClassModel model) {
}
I would like to create an activity which shows 3 tabs. The first tab should show a user's uploaded photos the 2nd all the images a user liked, and 3rd the user's favorite images. All these data comes from a webservice.I would like to use the same fragment with it's layout file and call different URLs. The fragment implements a StringReader and populates a listview inside.
My problem is that I managed to load the Fragment in the first tab, but the second and third tabs remains empty. If I navigate to the last tab and started to navigate back, then the first tab remains empty and the second gets populated. I watched so many tutorials and red what I could reached but It seems that nothing has helped.
The Fragment instantiation in my Activity looks like this :
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return UsersSpheresFragment.newInstance();
case 1:
return UsersSpheresFragment.newInstance();
case 2:
return UsersSpheresFragment.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
my fragment is :
public class UsersSpheresFragment extends Fragment {
CircleImageView userImageFragment;
TextView userNameTextFragment;
TextView nrOfSpheresFragment;
LinearLayout loadingLayoutFragment;
ListView listview_spheresFragment;
public PhotosphereListAdapter adapter;
TextView nrOfLikes;
TextView nrOfSeens;
String userId="";
String userName = "";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_spheres_fragment,container,false);
return view;
}
// newInstance constructor for creating fragment with arguments
public static UsersSpheresFragment newInstance() {
UsersSpheresFragment fragmentFirst = new UsersSpheresFragment();
return fragmentFirst;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
userImageFragment = (CircleImageView) getActivity().findViewById(R.id.userImageFragment);
userNameTextFragment = (TextView) getActivity().findViewById(R.id.userNameTextFragment);
nrOfSpheresFragment = (TextView) getActivity().findViewById(R.id.nrOfSpheresFragment);
loadingLayoutFragment = (LinearLayout) getActivity().findViewById(R.id.loadingLayoutFragment);
listview_spheresFragment = (ListView) getActivity().findViewById(R.id.listview_spheresFragment);
nrOfLikes = (TextView)getActivity().findViewById(R.id.nrOfLikes);
nrOfSeens = (TextView)getActivity().findViewById(R.id.nrOfSeens);
GlobalUserData userData = (GlobalUserData)getActivity().getApplication();
Bundle bundle = this.getArguments();
if (bundle != null) {
userId = bundle.getString("userId","");
userName = bundle.getString("userName","");
userNameTextFragment.setText(userName);
}
else{
if (userData.getUserImageLink().length() > 0) {
LoadUserImage(userData.getName(), userData.getUserImageLink());
}
userNameTextFragment.setText(userData.getName());
}
//Log.i("TAG",userData.GetAllData());
if (userId.length() > 0)
loadImagesFromAPI(MainActivity.URL_DATA+"typ=mysphere&id="+userId);
else
loadImagesFromAPI(MainActivity.URL_DATA+"typ=mysphere&id="+userData.getUserId());
listview_spheresFragment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//send the photosphereId to the Panoviewer fragment
Bundle bundle = new Bundle();
bundle.putString("Id", view.getTag().toString());
bundle.putString("Title", ((Photosphere) adapter.getItem(position)).getTitle());
bundle.putString("Description", ((Photosphere) adapter.getItem(position)).getDescription());
bundle.putString("ThumbUrl", ((Photosphere) adapter.getItem(position)).getImageUrl());
bundle.putBoolean("ShowUserLink", userId.length() > 0 ? false : true);
//create the fragment
SimpleFragment fragment = new SimpleFragment();
fragment.setArguments(bundle);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_main, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
public void LoadUserImage(String userName, String imageUrl){
ImageLoader imageLoader = CustomVolleyRequest.getInstance(getActivity()).getImageLoader();
Bitmap bm = imageLoader.get(imageUrl, ImageLoader.getImageListener(userImageFragment, android.R.color.white, android.R.color.white)).getBitmap();
userImageFragment.setImageBitmap(bm);
userNameTextFragment.setText(userName);
}
public void loadImagesFromAPI(final String Url) {
loadingLayoutFragment.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
ArrayList<Photosphere> photospheres = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.isNull("userModel") || jsonObject.getJSONObject("userModel").isNull("OtherImages")){
loadingLayoutFragment.setVisibility(View.GONE);
nrOfSpheresFragment.setText("No images");
}
else {
if (userId.length() >0){
LoadUserImage((jsonObject.getJSONObject("userModel")).getString("UserName"),(jsonObject.getJSONObject("userModel")).getString("ImgPath"));
}
photospheres = new WebServiceReader().processSpheresModelJsonData(jsonObject.getJSONObject("userModel"),"OtherImages");
loadingLayoutFragment.setVisibility(View.GONE);
//init adapter
adapter = new PhotosphereListAdapter(getActivity(), photospheres, (userId.length() > 0 ? false : true),true);
listview_spheresFragment.setAdapter(adapter);
nrOfSpheresFragment.setText(nrOfSpheresFragment.getText()+"("+listview_spheresFragment.getCount()+")");
nrOfLikes.setText((jsonObject.getJSONObject("userModel")).getString("TotalLikes"));
nrOfSeens.setText((jsonObject.getJSONObject("userModel")).getString("TotalViews"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
nrOfSpheresFragment.setText("An error occurred. Please try again!");
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Update!
It seems that all of the fragments are loaded and overwritten in the first tab.
nrOfSpheresFragment.setText(nrOfSpheresFragment.getText()+"("+listview_spheresFragment.getCount()+")");
this line of code updates a textview and I can see that the textview is updated 3 times (25)(10)(5) which means the number of results. Only the last result's listview is visible
I figured out what was the problem.
When I used the fragment, (the fragment was created before, and used in other way) I didn't notice that when I initialize the controls in the page, I use getactivity() instead of rootview. So in order to make it work I changed those two as shown
userImageFragment = (CircleImageView) view.findViewById(R.id.userImageFragment);
userNameTextFragment = (TextView) view.findViewById(R.id.userNameTextFragment);
nrOfSpheresFragment = (TextView) view.findViewById(R.id.nrOfSpheresFragment);
loadingLayoutFragment = (LinearLayout) view.findViewById(R.id.loadingLayoutFragment);
listview_spheresFragment = (ListView) view.findViewById(R.id.listview_spheresFragment);
nrOfLikes = (TextView)view.findViewById(R.id.nrOfLikes);
nrOfSeens = (TextView)view.findViewById(R.id.nrOfSeens);
You can set variable to fragment, witch helps you to choose content you need
private String mUrl; //url of content
//set url of content via newInstanse() method
public static UsersSpheresFragment newInstance(String dataUrl) {
UsersSpheresFragment fragment = new UsersSpheresFragment();
Bundle arguments = new Bundle();
arguments.putInt(EXTRA_KEY_ULR, dataUrl);
fragment.setArguments(arguments);
return fragment;
}
//get url in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getArguments();
if (extras == null || !extras.containsKey(EXTRA_KEY_URL))
throw new IllegalArgumentException("missing authorId argument");
mUrl = extras.getInt(EXTRA_KEY_URL);
//load your data
webService.loadData(mUrl);
}
another variant is set type of content via newIntanse(int type) method and choose data match it type in fragment#onCreate()
I am trying to send data from activity to fragment,but in fragment i am getting null instead of my values,following is my code can any one help me with this?
String nofrndthere="nofrnds";
String frndthere="frnds";
if(jsonary.length()==0)
{
// Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("nofrndsavailable", nofrndthere);
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
else if(jsonary.length()!=0)
{
// Toast.makeText(MainActivity.this,"Not Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("frndsavailable", frndthere);
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
HomeFragment
public class HomeFragment extends Fragment {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private FragmentTabHost tabHost;
private SearchView searchView;
private String strtext;
private String strtextss,strtextfnrdval;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
tabHost = new FragmentTabHost(getActivity());
tabHost.setup(getActivity(), getChildFragmentManager(), R.layout.my_parent_fragment);
Bundle bundle = this.getArguments();
strtext = bundle.getString("user_login_id");
if (getArguments() != null) {
strtextss = bundle.getString("nofrndsavailable");
strtextfnrdval= bundle.getString("frndsavailable");
}
System.out.println("DATASSSSS : " +strtextss+strtextfnrdval);
System.out.println("<<<<<<<<<<<<<< Session ID : " + strtext+strtextss+strtextfnrdval);
Bundle arg1 = new Bundle();
arg1.putInt("Arg for Frag1", 1);
if(strtext!=null) {
arg1.putString("user_logid", strtext);
}
tabHost.addTab(tabHost.newTabSpec("one").setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_profile_tabs,"Home")), DiscoverFragment.class, arg1);
Bundle arg2 = new Bundle();
arg2.putInt("Arg for Frag2", 2);
if(strtext!=null) {
arg2.putString("user_logid_sectab", strtext);
}
tabHost.addTab(tabHost.newTabSpec("Sec").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_frnds_tab,"Invite")), ShopFragment.class, arg2);
Bundle arg3 = new Bundle();
arg3.putInt("Arg for Frag3", 3);
if(strtext!=null) {
arg3.putString("user_logid_thirdtab", strtext);
}
tabHost.addTab(tabHost.newTabSpec("Third").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_wish_tab,"Wish")), Thirdtab.class, arg3);
Bundle arg4 = new Bundle();
arg4.putInt("Arg for Frag4", 4);
if(strtext!=null) {
arg4.putString("user_logid_fourthtab", strtext);
}
if(strtextss == getArguments().getString("nofrndsavailable"))
{
// Toast.makeText(getActivity(), "Null in home", Toast.LENGTH_SHORT).show();
System.out.println("Null in home");
tabHost.addTab(tabHost.newTabSpec("Four").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_notification_tab, "Alert")), FourthTabs.class, arg4);
}
else if(strtextfnrdval == getArguments().getString("frndsavailable"))
{
// Toast.makeText(getActivity(), "Not Null in home", Toast.LENGTH_SHORT).show();
System.out.println("NotNull in home");
tabHost.addTab(tabHost.newTabSpec("Four").
setIndicator(getTabIndicator(tabHost.getContext(), R.drawable.icon_fnrdalert, "Alert")), FourthTabs.class, arg4);
}
return tabHost;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
public View getTabIndicator(Context context, int icon,String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
ImageView iv = (ImageView) view.findViewById(R.id.indicatorImageView);
iv.setImageResource(icon);
TextView txt = (TextView) view.findViewById(R.id.txttb);
txt.setText(text);
return view;
}
}
before you open the fragment this is how you can attach the bundle to it. following code should be in your activity to put the bundle in the fragment.
Fragment fragment = new YourFragmentClass();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
now that you have attached the bundle open the fragment .
Things which you have to do is Override onCreate() method in your fragment and this is how you will receive the bundle.
private String mParam1; // these are global variable to get the data
private String mParam2; // after you receive the data, it can be used under `onActivityCreated()`
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1,null);
mParam2 = getArguments().getString(ARG_PARAM2,null);
// I have updated the code thisis how you can check which string is empty.
// cause if you try to do some work on null object you will get error
if(mParam1 == null){
// it is empty
}else{
// it is not empty
}
if(mParam2 == null){
// it is empty
}else{
// it is not empty
}
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// here you can use mParam1 and mParam2
}
Update
with conversation I had with you, you can start your fragment though your activity like this to tell the fragment if the array is null or not
HomeFragment fragobj = new HomeFragment();
Bundle bundle = new Bundle();
if(jsonary.length()==0){
bundle.putBoolean("isAvailable", false);
}else{
bundle.putBoolean("isAvailable", true);
}
fragobj.setArguments(bundle);
and in the onCreate() method of your fragment this is how you can read the boolean value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
boolean mParam1 = getArguments().getBoolean("isAvailable",false);
}
}
Updated
ok now i realize what you are doing (fragment is already started before setting the bundle), you can try this. (it is quite cheeky )
make a method inside your HomeFragment
public static void setData(boolean isAvailable){
// here you will get the actual data
}
Now in your Activity when you get the JSONArray depending on that you can that you can do this.
HomeFragment.setData(true/false)
From your question I think you are getting user_login_id as null from bundle
Bundle bundle = this.getArguments();
strtext = bundle.getString("user_login_id");
This is because you have not put any string with user_login_id in your bundle
if(jsonary.length()==0)
{
// Toast.makeText(MainActivity.this,"Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("nofrndsavailable", nofrndthere);
bundle.putString("user_login_id", <userid>); //put user id here
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
else if(jsonary.length()!=0)
{
// Toast.makeText(MainActivity.this,"Not Null",Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("frndsavailable", frndthere);
bundle.putString("user_login_id",<userid>);// put user id here
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
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).