So basically i am going to use one Fragment in two different activities.Except one method of fragment in which I want to change something.So how do i get the name of activity which is using the Fragment so that I can do things depending upon the name of which activity is current.
-
1Use getAcctivity().getClass() – Dec 24 '15 at 05:43
-
@Mohammed Gadiwala: u can get the hosting Activity instance using getActivity() mth inside hosted fragment. – kevz Dec 24 '15 at 05:43
-
Thanks @JawadLeWywadi i used getclass.getname and it showed up,Thanks again – sharin gan Dec 24 '15 at 05:56
7 Answers
in Java
try:
getActivity().getClass().getSimpleName()
- But be careful when you're using
getActivity()
method from fragment. If your fragment is not attached to activity getActivity() will return null.
in Kotlin
try:
activity?.javaClass?.simpleName
- It's null safe

- 11,736
- 4
- 55
- 80
The first Ans is great but it's in java so i translate this in koltin
activity?.javaClass?.simpleName

- 2,017
- 1
- 19
- 40
Firstly check if the fragment is still attached to activity, then you can check for activity name:
if(isAdded()) {
getActivity().getClass().getSimpleName();
}

- 450
- 5
- 12
Create your own interface and implement it in both of your activity and finally pass this instance to your fragment.
public interface ActivityListener
{
void onClick();
}
write your code into onClick() method and call this method from fragment.

- 653
- 4
- 13
Use this.getClass().getSimpleName()
to get the name of the Activity.
if you're in the context of an OnClickListener (or other inner class), specify the class manually:
MainActivity.class.getSimpleName()
for more details check this link

- 1
- 1

- 22,772
- 22
- 86
- 142
I think an better solution will be to create an enum which differentiate your cases and sent that enum through the arguments of the fragment. In this way your cases will be very clear and you will know why there is a difference in the flow of your fragment.

- 6,186
- 4
- 48
- 78
If you're in another class and you're trying to get the name of the "initiating class" then you can use Context to access it, like so: getContext().getClass().getSimpleName();
Example:
public String getMyActivityName() {
String myActivityName;
myActivityName = getContext().getClass().getSimpleName();
return myActivityName;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Toast.makeText(this.getContext(), "myActiveParentClass: "+getMyActivityName(), Toast.LENGTH_SHORT).show();
}
I hope it helps someone...

- 71
- 1
- 4