Pass Data From Activity To Fragment Class Cast Exception
There are so many ways but i am using this one: Activity:(Main2Activity) public class Main2Activity extends AppCompatActivity{ private String myString = 'hello'; @Override protec
Solution 1:
You create your Fragment in MainActivity and it belongs to it, so you get MainActivity instead of Main2Activity when you use getAcitvity().
Solution 2:
Try making your getMyData()
static
publicstaticStringgetMyData() {
return myString;
}
and then access it in fragment like
Main2Activity.getMyData();
Solution 3:
In your Activity, do the following
MyFragment fragmentObj=newMyFragment();
Bundleargs=newBundle();
args.putString("Data_Key", string_value);
fragmentObj.setArguments(args);
Now add this Fragment to stack using FragmentTransaction
.
After this, in your Fragment class's onCreateView
do the following
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewrootView= inflater.inflate(R.layout.fragment_xml_view, container, false);
if (getArguments() != null)
{
StringvalueReceived= getArguments().getString("Data_Key");
}
return rootView;
}
Solution 4:
Create an object of MainActivity2
and access the method as follow:
MainActivity2 mn2=newManiActivity2();
mn2.getMyData();
Solution 5:
If you want to done this work you must have to keep your myFragment into Main2Activity instead of MainActivity.
Post a Comment for "Pass Data From Activity To Fragment Class Cast Exception"