I am new to android and I am trying to call my MapFragment from adapter after on click using intent below is my code
Below is adapter code:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final BusInfo info = getItem(position);
View view = LayoutInflater.from(context).inflate(R.layout.bus_only_list,null);
TextView busname;
busname = (TextView) view.findViewById(R.id.busname);
busname.setText(info.name);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pref = context.getSharedPreferences("busInfo",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("bus_name",info.name);
editor.commit();
Intent intent = new Intent(context, MapsFragment.class);
intent.putExtra("name",info.name);
context.startActivity(intent);>
}
});
return view;
}
I want to pass to mapfragment using intent but it redirect to MainActivity instead of MapFragment. How can I stop transferring to MainActivity?
Thank you.
A common pattern to passing a value to a Fragment is using newInstance method. In this method you can set Argument to fragment as a means to send the value.
First, create the newInstance method:
public class YourFragment extends Fragment {
...
// Creates a new fragment with bus_name
public static YourFragment newInstance(String busName) {
YourFragment yourFragment = new YourFragment();
Bundle args = new Bundle();
args.putString("bus_name", busName);
yourFragment.setArguments(args);
return yourFragment;
}
...
}
Then you can get the value in onCreate:
public class YourFragment extends Fragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the value from arguments
String busName = getArguments().getString("bus_name", "");
}
...
}
You can set the value to the Fragment from your activity with:
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
YourFragment yourFragment = YourFragment.newInstance("bus_name_value");
fragTransaction.replace(R.id.fragment_place_holder, yourFragment);
fragTransaction.commit();
You can use the above codes to send the value in Fragment initialization.
If you want to set the value to the already instantiated fragment, you can create a method then invoke the method to set the value:
public class YourFragment extends Fragment {
...
public setBusName(String busName) {
// set the bus name to your fragment.
}
...
}
Now, In the activity, you can invoke it with:
// R.id.yourFragment is the id of fragment in xml
YourFragment yourFragment = (YourFragment) getSupportFragmentManager()
.findFragmentById(R.id.yourFragment);
yourFragment.setBusName("bus_name_value");
You cannot pass an intent to a Fragment. Try using a Bundle instead.
Bundle bundle = new Bundle();
bundle.putString("name", info.name);
mapFragment.setArguments(bundle)
In your Fragment (MapsFragment) get the Bundle like this:
Bundle bundle = this.getArguments();
if(bundle != null){
String infoName = bundle.getString("name");
}
As guys mentioned before:
1. Use callback or just casting on your context (your activity must handle changing fragments itself).
2. To change fragments use activity's FragmentManager - intent is used to start another activity.
Fragments Documentation
Related
This is the answer that I got from other topic and applied it to my codes:
From Activity you send data with intent as:
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);
}
These are the codes that I applied, it is not working somehow. The fragment is already opened at the start.
public void onInfoWindowClick(Marker marker) {
if (tag.equals("Click to show all routes in this point")) {
Bundle bundle = new Bundle();
bundle.putString("route1", "Divisoria - San Juan");
// set Fragmentclass Arguments
hideShowFragment fragobj = new hideShowFragment();
fragobj.setArguments(bundle);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
Fragment intersectionFragment = manager.findFragmentById(R.id.fragmentContainer2);
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.add(R.id.fragmentContainer2, fragobj);
ft.show(intersectionFragment);
ft.commit();
}
}
The codes in my onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hide_show, container, false);
if (!routes.equals(none)) {
routes = getArguments().getString("route1");
} else {
routes = "Food";
}
return view;
}
What I want to happen is that the fragment will always update to what marker Tag that I click on the map. In other words, pass the string to the fragment (that is opened) and update it.
I do not want to use startActivityForResult because I can't move around the map if I don't use fragments. Is there a way to send result from activity to fragment that is already opened and running? If none, then how can I make the fragment not running from the start (using supportFragmentManager)? I only know is to hide it
If you have running Fragment and want to pass some data to it, you should create some way to communicate. For that purposes, you can use Observer pattern.
First of all create interface inside Activity if you want to pass data to Fragment:
public interface OnInfoClickedListener {
void onInfoClicked(String info);
}
Implement this interface inside Fragment:
#Override
public void onInfoClicked(String info) {
infoTextView.setText(info);
}
Now, inside your Activity, create variable to store this interface implementation:
private OnInfoClickedListener listener;
And when instantiating Fragment, save instance of it to variable:
InfoFragment fragment = InfoFragment.newInstance();
listener = fragment;
And when needed just provide data through this interface:
listener.onInfoClicked("Info - " + UUID.randomUUID());
I am storing some values in array list now i want to pass the same array list object to fragment from an activity. So how can i send the array list object from an activity and receive the same object in fragment.
Try this code in your activity, It is a code snippet from my working application.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourArrayList.add("test");
yourArrayList.add("test2")
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayList", yourArrayList);
yourFragment yourFragment = new yourFragment();
yourFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, yourFragment);
fragmentTransaction.commit();
}
In your fragment you can access the value like this
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> values = getArguments().getStringArrayList("arrayList");
}
pass activity should follow this lines
Bundle bundle = new Bundle();
bundle.putStringArrayList("valuesArray", namesArray);
namesFragment myFragment = new namesFragment();
myFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, myFragment);
fragmentTransaction.commit();
get Fragment inside follow this lines
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("valuesArray");
You can do this by following the usual way of Fragment-Activity communication. That is:
1) Declare a public interface within your Fragment class.
2) Inside this interface declare a getter method for your list.
3) Make your respective Activity implement this interface.
4) Inside your Fragment, do this:
#Override
public void onAttach(Context context) {
super.onAttach(context);
YourInterfaceType activity = (YourInterfaceType) context;
List<> yourList = activity.getMyList();
}
To make it more clear:
Your activity will be as follows:
public class MyActivity extends Activity implements YourInterfaceType{
#Override
public void getMyList(){
return yourList;
}
}
just put your array with setargument in Actiivty and get Array
getArgument in fragment.
Activity
Bundle bundle = new Bundle();
bundle.putStringArrayList("valuesArray", namesArray);
namesFragment myFragment = new namesFragment();
myFragment.setArguments(bundle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, myFragment);
fragmentTransaction.commit();
fragment
ArrayList<Model> values = getArguments().getStringArrayList("valuesArray");
I have 2 activities MainActivity and DetailActivity, if I click in the ListView in MainActivity will intent to DetailActivity with content "id", in DetailActivity I have 2 fragment (TabLayout-ViewPager).
My question is: How can fragment get "id" from that intent above???
Fragment in android
,If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.for more detail please read this stack overflow answer
private int mId;
private static final String ID = "id";
public static DetailsFragment newInstance(int id) {
DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
get values in oncreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
//mId is variable which contain (YourActivity)MainActivity value.you can use in fragment.
mId = getArguments().getInt(ID);
}
//call in your YourActivity(MainActivity) in oncreate method
int id = yourid;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,DetailFragment.newInstance(id)).commit();
from Android Developer's Fragment Page
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
// add fragment to the fragment manager's stack
Like #cricket_007 says, create a factory method in your fragment and pass the data through bundle arguments consider the example below
public static YourFragment newInstance(Bundle args) {
Yourfragment fragment = new YourFragment();
Bundle bundle = args;
// Or if your args is a variable data for example a string
// use Bundle bundle = new Bundle(); bundle.putString("extra_name",value);
// Now set the fragment arguments
fragment.setArguments(bundle);
return fragment;
}
And now anywhere in your fragment you can do
Bundle args = getArguments();
// and access your extra by args.getString("extra_name"); ...
I have an activity where the user press a button and then is send to a fragment, but I wish to pass an extra for the use of the fragment:
activity A(where is the button):
public OnClickListener publish = new OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),ActivityB.class);
intent.putExtra("friendIdRowID", rowID);
startActivity(intent);
}
};
Activity B is loading the fragment(where I wish to retrieve the extra "friendIdRowID"),
the fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main2, container, false);
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null)
{
String myString = extras.getString("friendIdRowID");
}
}
But it is not working, what can I do to pass and retrieve the extra? thanks.
You need to use the setArguments() method of Fragment to pass information into your fragment. In the activity that creates the fragment, do something like this:
YourFragment f = new YourFragment();
Bundle args = new Bundle();
args.putString("friendIDRowID", getIntent().getExtras().getString("friendIDRowID"));
f.setArguments(args);
transaction.add(R.id.fragment_container, f, "tag").commit();
Then, override the onCreate() method of your Fragment and do the following:
Bundle args = getArguments();
String myString = args.getString("friendIdRowID");
Like extras for an Activity, you can add as many things to your arguments bundle as you wish. Hope this helps!
i have 3 ArrayList> that I want to pass to 3 fragments. Besides making them static, what is the best approach to do this?
You can use the setArguments in the Fragment. Take a look at http://developer.android.com/guide/components/fragments.html, basically, you create a Bundle before create your Fragment and then setup as an Argument.
Example from the Android Documentation:
public static class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
Instead of use getIntent().getExtras(), you create you bundle and set the arguments
Bundle bundle = new Bundle();
bundle.putSerializable(YOUR_KEY, yourObject);
fragment.setArguments(bundle);
And for your Fragment:
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
// We have different layouts, and in one of them this
// fragment's containing frame doesn't exist. The fragment
// may still be created from its saved state, but there is
// no reason to try to create its view hierarchy because it
// won't be displayed. Note this is not needed -- we could
// just run the code below, where we would create and return
// the view hierarchy; it would just never be used.
return null;
}
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getActivity().getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
You can create listener callback interfaces and implement them in your fragments. Something like this:
#Override
public void onSomeEvent(List<SomeData> data) {
//do something with data
}
In your activity create this interface:
public interface OnSomeEventListener {
onSomeEvent(List<SomeData> data);
}
then obtain your fragment by using findFragmentById or findFragmentByTag and assign it to a listener:
this.onSomeEventListener = fragment;
You can then call methods of that interface and your fragment will receive callbacks.
The second and more easier way of communication between fragments and activities is BroadcastReceivers. You can register some BroadcastReceiver in your fragments and then call sendBroadcast() from activity. Your list of data can be put in a bundle of that broadcast message.