How to get the name of the activity from the fragment? - android

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.

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

The first Ans is great but it's in java so i translate this in koltin
activity?.javaClass?.simpleName

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

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.

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

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.

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...

Related

How to get data from First Fragment to Last Fragment?

I have multiple fragments in ViewPager. How can i get fragment first EditText Data to last Fragment?
I have set value in my first fragment like below -
txtConsAcNo.setText(account_no);
txtMeterSrMo.setText(mtr_serial_no);
Now i am getting this txtConsAcNo, txtMeterSrMo value on my last fragment like below-
ConDetFirstFragment f1 = new ConDetFirstFragment();
txtConsAcNo = f1.txtConsAcNo.getText().toString();
txtMeterSrMo = f1.txtMeterSrMo.getText().toString();
Now what i want that i am getting Null value and my app get unfortunately stopped. i want to get this data to my last fragment without bundle. how can i achieve this ?
Very Easy to Achieve this without Creating Interface, Bundle or intent -
I have declared all the variables in all the fragment "Public Static" like Below -
public static EditText txtConsAcNo, txtMeterSrMo;
After on any fragment i have declared variable to get data like below-
public static String txtConsAcNo,txtMeterSrMo;
Now i have created function to get value from first fragment in above variable below-
public static void getalldata(){
ConDetFirstFragment f1 = new ConDetFirstFragment();
txtConsAcNo = f1.txtConsAcNo.getText().toString();
txtMeterSrMo = f1.txtMeterSrMo.getText().toString();
}
Happy Coding...
There are a couple of problems here:
The first fragment may have been destroyed by the Android system to conserve memory.
Your fragments should not talk to each other directly
To achieve what you need, you need to jump through a few hoops.
Assuming that the source texts are EditText objects (ie. editable by the user), then add a TextWatcher to each of the EditText objects.
Create an Interface:
public interface TextPurveyor {
void setText1(String t);
String getText1();
void setText2(String t);
String getText1();
}
Implement this interface in the host Activity; and save the text values locally in the activity. Don't forget to save/restore them with the rest of the Activity state.
Make the TextWatcher objects call the appropriate setText(..) methods on the host activity:
((TextPurveyor)getActivity()).setText1(...);
Make each fragment check that the host activity implements this method.
When the second fragment wants a string, ask the activity for it:
((TextPurveyor)getActivity()).getText1();
To avoid coupling your project code tightly, try to use the design patterns that have been proven to work best like the Publisher/Subscriber as I will show you below:
There is a popular library I have always used in my projects called EventBus - just add the following to your build.gradle (module-level) file under dependencies :
compile 'org.greenrobot:eventbus:3.0.0'
Secondly, create a simple Plain Old Java Object (POJO) to represent your Event:
public class FragmentAToLastEvent{
private String txtConsAcNo;
private String txtMeterSrMo;
FragmentAToLastEvent(String acNo, String srMO){
this.txtConsAcNo = acNO;
this.txtMeterSrMo = srMO;
}
//getters and setters if needed
public String gettxtConsAcNo(){
return txtConsAcNo;
}
public String gettxtMeterSrMo(){
return txtMeterSrMo;
}
}
Next step is to actually use your Event class here:
So, in your fragment that you want to send text from EditText, simply do this:
String txtConsAcNo = f1.txtConsAcNo.getText().toString();
String txtMeterSrMo = f1.txtMeterSrMo.getText().toString();
EventBus.getDefault().post(new FragmentAToLastEvent(txtConsAcNo, txtMeterSrMo));
In your last fragment, simply do this to complete:
Inside onCreate or onAttach of your Fragment:
//register your event - making this class a subscriber
EventBus.getDefault().register(this)
//next, override a single method to receive the values you passed from above code (Fragment 1?)
public void onEvent(FragmentAToLastEvent event){
String txtConsAcNo = event.gettxtConsAcNo();
String txtMeterSrMo = event.gettxtMeterSrMo();
//now you can use your text here without problems!
}
Finally, remember to unregister inside onDestroy:
#Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
This is what I have always done and it is cleaner, without using interfaces that your fragments MUST implement and do all that!
I hope you find it helpful to you and good luck!

getActivity() vs this.getActivity() in Fragment

I am new in Android, and I'd like to know if there is a difference between getActivity() and this.getActivity() in Fragment clases.
For exemple we have a method in a siple class(doesn't extend Activity or Fragment) like:
public static void method(Context context){
... some code
}
If we want to use it, just call it in our fragment class:
MyMethodClass.method(getActivity());
or
MyMethodClass.method(this.getActivity());
I know both are working but I need a proffesional opinion.
Thanks.
They are the same. The this keyword refers to the current object.
public class Car {
int speed = 10;
public void move() {
//using this.speed or speed makes no difference here
}
}
If you are extending from Fragment, both getActivity() and this.getActivity() will call Fragment#getActivity(), so as others said, it makes no difference. Both will lookup for the method in the parent class.
A small correction: tha sample code that you provided:
MyMethodClass.method(getActivity());
would work if method() was a static method. Otherwise you should call it like this:
MyMethodClass.this.method(getActivity());
But that's just basic Java ;)
Use getActivity() keyword instead of 'this' keyword in Fragments

Android, where to put my own Bluetooth class

Well, I'm at a dilemma here. I made my own class that uses the Bluetooth class from android but I'm not sure where to put it. Extending the android Bluetooth class seems like a good idea but I need to override the onActivityResult() which is only available to an activity class. So, where would I put my class so that I have access to onActivityResult() (keeping in mind the idea here is to use as few dependencies as possible)?
In other words, I want to move the Bluetooth code from the main activity to a separate class.
You should to use separate file for each class. You can create a folder "engine". For example: com.mycorp.myapp.engine. You can get access to onActivityResult() very simple. For example: MainActivity.onActivityResult(). Note: function should be public.
Or you can pass your activity to your CustomBluetooth's constructor.
public class CustomBluetooth {
private Activity mActivity;
/* Constructor */
public CustomBluetooth (Activity pActivity ) {
super();
this.mActivity = pActivity;
}
/* Your functions */
public int getResult() {
return this.mActivity.onActivityResult();
}
}
Alex. P.S. Sorry for my English:)
Add an interface to your Bluetooth class and implement the interface in your activity.

Dynamically change ViewpagerIndicator Fragment Content Android

I am working on an application using viewpagerindicator.
In my main activity that has the viewpagerindicator, I spin off a thread that does some computation and updates a an instance variable mString of the activity. I want to update a fragment in the viewpagerindicator with the mString. However, I can't seem to figure out the best way to reach the fragment.
Does anyone know of any good samples that do something similar to this?
Create a callback object in your Fragment, register it with your FragmentActivity. If mString is already set in FragmentActivity then you can return it immediately via the callback, otherwise, when the computation thread finishes, it can return the string via the callback. The callback method should do whatever the Fragment needs to do with the string, e.g. set the text of a TextView.
E.g. create an interface called DynamicDataResponseHandler as follows:
public interface DynamicDataResponseHandler {
public void onUpdate(Object data);
}
Then in your Fragment, implement that interface as follows:
private class MyStringDataResponseHandler implements DynamicDataResponseHandler {
#Override
public void onUpdate(Object object) {
mYourTextView.setText((String)object);
}
}
Your Fragment can then instantiate a MyStringDataResponseHandler object in its onCreate, pass that to the FragmentActivity via a method in the FragmentActivity like:
private MyStringDataResponseHandler mMyStringDataResponseHandler;
public void registerMyStringDataResponseHandler (DynamicDataResponseHandler callback) {
mMyStringDataResponseHandler = callback;
if(mString != null) {
mMyStringDataResponseHandler.onUpdate(mString);
}
}
And wherever in your Handler you obtain the value for mString, do something like this:
if(mMyStringDataResponseHandler != null) {
mMyStringDataResponseHandler.onUpdate(mString);
}
Do some reading on the concept of Callbacks to get a better understanding of what I'm doing above and other ways you can use them.
You want to update the UI of a Fragment in ViewPager after it is started, do i make it clear?
Ok, in this situation
You should add a public method in your custom Fragment.
Find the Fragment in your Activity.
Invoke the method after your calculation is done.
The question is same with this one.

call static void

How do I call my function?
public static void dial(Activity call)
{
Intent intent = new Intent(Intent.ACTION_DIAL);
call.startActivity(intent);
}
Obviously not with:
dial(); /*Something should be within the brackets*/
You should try
ClassName.dial();
The reason is that static methods belong the class itself, not to an individual instance of it. The call to instance.dial() is legal, but discouraged.
you should use your ClassName.StaticMethod.... to call a static method of a class
You can't pass null. You have to send a context object.
Where is your function located? If it's inside an Activity or the such, simply pass "this" as the parameter.
If it's inside an BroadcastListener, or a Service, just change the parameter to Context and pass "this".
What exaclty is the Problem?
If you've got a class like
public class Test {
public void nonStaticFct() {
staticFct();
}
public static void staticFct() {
//do something
}
}
Works perfectly (even if you should call static functions always by Classname.FctName (Test.staticFct())
I guess the problem here is the missing argument.
[Edit] Obviously I am wrong, according to the Java Code Conventions you may use a Classmethod by simply calling it, without using the classname (even if it seems odd, since I would expect an implicit this.staticFct() - but possibly the Java compiler is smart enough)

Categories

Resources