My activity extends AppCompatActivity, and I started a Fragment there with support library fragment manager:
public MyActivity extends AppCompatActivity {
...
#Override
public void onResume() {
super.onResume();
// show my fragment
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myFragment, TAG).commit();
}
}
My question is, in MyFragment, how can I get the instance of MyActivity who started it?
//NOTE: it extends android.support.v4.app.Fragment
public class MyFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// How to get the instance of MyActivity here?
// I tried: getActivity() but it returns FragmentActivity
//& MyActivity is AppCompatActivity
}
}
I know there is getActivity() function in Fragment, but it returns FragmentActivity:
Try this
((MyActivity) getActivity()).
then access anything from activity class
Related
I find it very difficult to call the InsertSlider in the MainFragment from the BottomSheetDialog.
Any help and thanks
In the BottomSheet :
public class AdminBottomSheetMainSave extends BottomSheetDialogFragment
{
// One Method I don.t Know How To Work
//((MainFragment)getContext()).InsertSliders(new ImageSlider(0,Name,Image,Price,Description));
// Not Work Too
MainFragment fragment = new MainFragment();
fragment.InsertSliders(new ImageSlider(0,Name,Image,Price,Description));
}
In the Fragment :
public class MainFragment extends Fragment
{
public void InsertSliders(ImageSlider imageSlider)
{
imageSliderViewModel.insert(imageSlider);
Toast.makeText(getActivity(), "Done Insert"+imageSlider, Toast.LENGTH_SHORT).show();
}
What is the contact method how do I get to InsertSliders
you should use interface to communicate between two fragments and you need an activity to implement the interface.
define interface in your bottomsheetdialogfragment:
public class AdminBottomSheetMainSave extends BottomSheetDialogFragment
{
public Callback mCallback;
public interface Callback{
void insertSlider(ImageSlider slider);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
mCallback = (Callback) activity;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//...
mCallback.insertSlider(new ImageSlider(0,Name,Image,Price,Description));
}
}
then in your activity in our case MainActivity implement Callback interface and override inserSlider method:
public class MainActivity extends AppCompatActivity implements Callback{
MainFragment mainFragment;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//...
if(savedInstanceState == null){
mainFragment = MainFragment.newInstance(new Bundle()); // use real bundle here
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, mainFragment, "FragMain").commit();
}
}
// Interface method
#Override
public void insertSlider(ImageSlider slider){
if(mainFragment != null){
mainFragment.insertSlider(slider);
}
}
now in your MainFragment:
public class MainFragment extends Fragment{
public static MainFragment newInstance(Bundle args){
MainFragment fragment = new MainFragment();
fragment.setArguments(args);
return fragment;
}
//... Class overrides here onCreateView etc..
// define insertSlider method
public void insertSlider(ImageSlider slider){
imageSliderViewModel.insert(slider);
Toast.makeText(getActivity(), "Done Insert"+slider, Toast.LENGTH_SHORT).show();
}
I have an app which has one MainActivity and two Fragments. These fragments send argument to MainActivity this way:
Bundle args = new Bundle();
args.putLong("id",id);
sf.setArguments(args);
And then MainActivity takes argument in onCreate() method
protected void onCreate(Bundle savedInstanceState) {
private long wayId = getArguments().getLong("id");
}
How can I determine which fragment sent this argument to MainActivity ?
You can add another argument into the bundle like the tag of the fragment.
Bundle args = new Bundle();
args.putLong("id",id);
args.putString("fragmentTag", fragmentTag);
sf.setArguments(args);
and retrive the tag in your onCreate()
You can define a separate inrterface for every fragment
public class FragmentA extends Fragment {
public static interface FragmentAInterface {
void doSomething(String data);
}
}
public class FragmentB extends Fragment {
public static interface FragmentBInterface {
void doSomething(String data);
}
}
And then in your activity:
public class MyActivity extends AppCompatActivity implements FragmentA.FragmentAInterface, FragmentB.FragmentBInterface{
#Override
public void doSomething(String data) {
//Guaranteed to come from Fragment A
}
#Override
public void doOtherThing(String data) {
//Guaranteed to come from Fragment B
}
}
I am new in Fragment and I am trying use Activity method in Fragment class. So please help me how I use Activity method in Fragment. And also how I use List<NameValuePair>, SharedPreferences in Fragment.
public class DashboardFragment extends Fragment {
public DashboardFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
return rootView;
}
This is Fragment code and I want to use Activity method in this. So please help I am new in this section. If there is another method, please tell me.
After the fragment's onAttach method is called (see Fragment lifecycle), you can obtain a reference to the activity through fragment's getActivity() method. Then you can cast this reference to the type of your activity and call the method:
((MyActivity)getActivity()).method();
Your activity method needs to be static and public. Then you could do following in your Fragment:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof MyActivity) {
this.activity = activity;
sharedPreferences = activity.getSharedPreferences(...);
}
}
Declare MyActivity activity in your Fragment.
then you can call activity.yourMethod() in another place. Dont forget to check if activity is null.
Use an interface implementation for this. Somethings like this:
Activity:
MyActivity extends AppCompatActivity implements CallBack {
#Override
public void onCallBack() {
// do something
}
}
And Fragment:
MyFragment extends Fragment {
public interface CallBack {
void onCallBack();
}
private CallBack callBack;
#Override
public void onAttach(Activity context) {
callBack = (CallBack) activity;
}
// when clicking or whatever it takes to call
callBack.onCallBack();
}
1) You can get Activity instance with getActivity() method in Fragment:
Activity activity = getActivity();
Then you can call any Activity method with the instance:
activity.method();
2) About SharedPreferences, you can also get Context instance with getContext() method in Fragment.
Context context = getContext();
So you can call getSharedPreferences() method with the instance:
SharedPreferences sharedPreferences = context.getSharedPreferences(String name, int mode);
3) List<T> is a pure Java class. So you can use it in Fragment without any limitation.
I have a main activity class, and a private inner class within the main activity. The private inner class has methods that when called will display fragments. This inner class implements an interface defined in the Fragment's class, to be used as a sort of callback. It is probably easiest to show through code.
public class MainActivity extends FragmentActivity {
//on a button clicked
EditItemManger em = new EditItemManager();
em.begin();
private class EditItemManager implements on EditItemFragment.EditedItemClickedListener{
//consructor, other stuff. no onCreate method because this inner class does not (explicity??) extend activty
public void begin(){
EditItemFragment editItemFrag = new EditItemFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(editItemFrag, EDIT_FRAG_TAG)
fragmentTransaction.commit();
}
#Override
public void onEditItemClicked() {
editFinish();
}
public void editFinish()
{
// other stuff
}
}
}
My EditItemFragment class, where the onAttach method always has a null activity parameter
public class EditItemFragment extends DialogFragment {
protected EditedItemClickedListener editedItemClickedListener;
protected ImageButton button;
public EditItemFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.edit_name_fragment, container, false);
button = (ImageButton) view.findViewById(R.id.submit_new_item_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editedItemClickedListener.onEditedItemButtonClicked();
}
});
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
editedItemClickedListener= (EditedItemClickedListener) activity;
} catch (ClassCastException e) {
e.printStackTrace();
}
}
public interface OnEditNameButtonClickedListener {
public void onEditNameButtonClicked();
}
So because the parameter in onAttach() in my Fragment class is always null, it eventually causes a null pointer exception. I am wondering if it is because the fragment is called from a class that is not extending activity. The problem is that if this class extends activity, there will be an issue with trying to commit the Fragment Transaction
I guest your onAttach returns nullpointer exception. Its because your parent Activity the main activity doesnt implement your custom interface so it return null. See the code below let me know if it help you:
public class MainActivity extends FragmentActivity implements EditItemFragment.EditedItemClickedListener{
private DialogFragment editItemDialog;
//Do your code here
#Override
public void onEditItemClicked() {
editFinish();
}
public void showDialog(){
//this is for showing your custom dialog fragment
editItemDialog = EditItemFragment.newInstance();
editItemDialog.show(getSupportFragmentManager(),"editItemDialog");
}
}
this is for your EditItemFragment:
public class EditItemFragment extends DialogFragment{
//Do your code here
public static EditItemFragment newInstance(){
EditItemFragment editItemDialog = new EditItemFragment();
return editItemDialog;
}
}
I am working on an android application,
and I have number of activities that extend from a custom activity.
Now I created a new FragmentActivity and I need the same functions that I have implemented in my custom activity.
How can I do that?
Edit
This is an simple example
public class BaseActivity extends Activity
{
protected void someFunction()
{
Log.i("TEST","This is a test");
}
}
public class MainActivity extends BaseActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
someFunction();
}
}
this is my FragmentActivity:
public class MyFragmentActivity extends FragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// here I want to use someFunction()..
}
}
In Java you can't extend more than one class.
So I guess you should extend BaseActivity from FragmentActivity instead of Activity