Passing data from activity to fragment in android is not working - android

I want to pass parameters from activity to fragment.
This is the code from the activity:
public class MatchActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match);
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
MarqueFragment fragobj = new MarqueFragment();
fragobj.setArguments(bundle);
}
}
This is the code from the fragment:
public class MarqueFragment extends Fragment {
#Override
public void onCreate ( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView ( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
View convertView=inflater.inflate(R.layout.fragment_marque, container, false);
if (getArguments() != null) {
String mParam1 = getArguments().getString("edttext");
System.out.println("got this from MatchActivity "+mParam1);
}else{
System.out.println("got nothing");
}
}
I am not getting any arguments I don't know why.
Notice : am not getting an error am getting "got nothing" as output.

Change your code to this
Bundle bundle = new Bundle();
bundle.putString(edttext", "From Activity");
MarqueFragment fragobj = new MarqueFragment();
fragobj.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_marque, fragobj);
transaction.commit();

Related

Send Intent From Activity To Fragment

I want to send intent from activity to fragment. I know how to send from fragment to activity just like this
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
but now i want to send from activity to fragment. I don't necessarily need to start the fragment i just want to make one of the id in my activity accessible in my fragment.
From your activity, you send your data, using bundle:
Bundle newBundle = new Bundle();
newBundle.putString("key", "text");
YourFragment objects = new YourFragment();
objects.setArguments(newBundle);
Your fragment class in onCreateView function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
if(getArguments() != null){
String yourText = getArguments().getString("key");
}
return inflater.inflate(R.layout.your_fragment, container, false);
}`
Passing the data from activity to fragment
Bundle bundle = new Bundle();
bundle.putString("params", "String data");
// set MyFragment Arguments
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
Receiving the data in the fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("params");
}
}

Updating fragment 1 UI from fragment 2

frag1 calls frag 2 and frag 2 calls a method in frag1 that updates a textview. The code works (doesn't crash) but the frag1 UI (when I return from frag2) is not updated/
Is it a valid approach? Is there a way to update the UI?
here is the frag1 and frag2 code:
public class Frag1 extends android.app.Fragment {
private static TextView txt;
public Frag1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = null;
rootview = inflater.inflate(R.layout.fragment_frag1, container, false);
return rootview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt);
Button btn = (Button) getActivity().findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag2 f2 = new Frag2();
ft.replace(R.id.content_frame, f2);
ft.addToBackStack(null);
ft.commit();
}
});
}
void setTxt(String s){
txt.setText(s);
}
}
and frag2 - the setTxt() method updates the textview in frag1:
public class Frag2 extends Fragment {
private Button btn2;
public Frag2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview;
rootview = inflater.inflate(R.layout.fragment_frag2, container, false);
Log.i("frag2","createdview");
return rootview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Frag1 f1 = new Frag1();
f1.setTxt("msg from frag2");
btn2 = (Button) getActivity().findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag3 f3 = new Frag3();
ft.replace(R.id.content_frame, f3);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
You can Broadcast Intent from the frag2
Intent intent = new Intent("key_to_identify_the_broadcast");
Bundle bundle = new Bundle();
bundle.putString("edttext", json.toString());
intent.putExtra("bundle_key_for_intent", bundle);
context.sendBroadcast(intent);
and then you can receive the bundle in your frag 1 by using the BroadcastReceiver class
private final BroadcastReceiver mHandleMessageReceiver = new
BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle =
intent.getExtras().getBundle("bundle_key_for_intent");
if(bundle!=null){
String edttext = bundle.getString("edttext");
}
//you can call any of your methods for using this bundle for your use case
}
};
in onCreateView() of your fragment you need to register the broadcast receiver first otherwise this broadcast receiver will not be triggered
IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
getActivity().getApplicationContext().
registerReceiver(mHandleMessageReceiver, filter);
Finally you can unregister the receiver to avoid any exceptions
#Override
public void onDestroy() {
try {
getActivity().getApplicationContext().
unregisterReceiver(mHandleMessageReceiver);
} catch (Exception e) {
Log.e("UnRegister Error", "> " + e.getMessage());
}
super.onDestroy();
}
You can create separate broadcast receivers in all of your fragments and use the same broadcast to broadcast the data to all of your fragments. You can also use different keys for different fragments and then broadcast using particular key for particular fragment.

Launch fragment map with address to search

Im having a issue I dont know how to resolve.
I have a fragment with a editText and a button.
The button launches a fragment map like this:
public void onClick(View view) {
//Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
Home activity = (Home) getActivity();
if(activity != null)activity.openMapFragment();
break;
}
and the function openMapFragment():
public void openMapFragment(){
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
How would i do to send the text inserted on editText field as a address to look for on map fragment?
You should use bundle to pass data to a fragment :
public void openMapFragment(String args){
Fragment fragment = new gMapFragment();
Bundle bundle = new Bundle();
bundle.putString("foo", args);
fragment.setArguments(bundle);
replaceFragment(fragment);
}
And to retrieve data :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
String foo = getArguments() != null ? getArguments().getString("foo") : "";
//...
}

Getting arguments from a bundle

I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);
DetailActivityFragment fragment = new DetailActivityFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_EXTRA, message);
fragment.setArguments(bundle);
}
I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments() from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
} else if (bundle == null) {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
The upper method displays a Toast message "Error" when I run the app...
The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:
public static myFragment newInstance(String param1, String param2) {
myFragment fragment = new myFragment ();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
And then on create set your global arguments:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
on your main activity you will create the fragment like
myFragment __myFragment = myFragment.newInstance("test","test");
That should work
This is a correct approach
Send (in the Activity):
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
final DetailActivityFragment frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);
final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);
ft.commit();
Receive (in the Fragment):
final Bundle bdl = getArguments();
String str = "";
try
{
str = bdl.getString("yourKey");
}
catch(final Exception e)
{
// Do nothing
}

Android: NullPointerException when communicating between fragments

Android newbie here. My app crashes when trying to send text from one fragment to another. It says:
java.lang.NullPointerException
at com.example.hang.camera.Camera.sendResults(Camera.java:57)
at com.example.hang.camera.PageOneFragment.sendMethod(PageOneFragment.java:320)
at com.example.hang.camera.PageOneFragment$1.onClick(PageOneFragment.java:104)
Here is my code:
// Activity that implements the interface from fragment A
Camera.java:
public class Camera extends ActionBarActivity implements PageOneFragment.OnComputeResultListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mViewPager = (CustomViewPager)findViewById(R.id.pager);
mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
mTabsAdapter.addTab(mTabHost.newTabSpec("one").setIndicator("One"), PageOneFragment.class, null);
mTabsAdapter.addTab(mTabHost.newTabSpec("two").setIndicator("Two"), PageTwoFragment.class, null);
if (savedInstanceState != null)
{
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
mViewPager.setPagingEnabled(false);
}
#Override
public void sendResults(String text){
PageTwoFragment fragmentTwo = (PageTwoFragment)getSupportFragmentManager().findFragmentById(R.id.second_fragment);
fragmentTwo.updateText(text);
}
// fragment A:
PageOneFragment.java
OnComputeResultListener mCallback;
public interface OnComputeResultListener{
public void sendResults(String text);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mCallback = (OnComputeResultListener) activity;
} catch(ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement OnComputeResultListener");
}
}
public void sendMethod(){
mCallback.sendResults("the results");
}
// in onCreateView, I have this onclicklistener, and I call "sendMethod" here
lengthButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
double length ;
line_x = imageview.x_getter();
line_y = imageview.y_getter();
length = Math.sqrt(Math.pow((line_x[0]-line_x[1]),2) + Math.pow((line_y[0]-line_y[1]),2));
line_length.setText("Length of the line is: " + String.format("%.2f",length) + "dp");
sendMethod();
}
}
);
// fragment B
PageTwoFragment.java
private TextView resultText = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.pagetwo_fragment, container, false);
resultText = (TextView) view.findViewById(R.id.resultText);
return view;
}
public void updateText(String text){
resultText.setText(text);
}
I finally solved the problem. In my camera.java where I implemented "sendResults" method of the interface, I changed the parameter of "findFragmentById" to the id of the viewPager instead of the id of the fragment's xml file.
However, from Android developer doc, for findFragmentById, it does say:
Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction.
So, I don't know why the xml id didn't work.
You can save your Fragment as an object in your Activity class.
In the activity class before doing the fragment transaction, do the following:
PageTwoFragment fragmentTwo = new PageTwoFragment();
// do the transaction:
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, fragmentTwo);
ft.commit();
then later in code, just call
fragmentTwo.updateText(...);

Categories

Resources