Android Calling objects from fragments - android

I'm not sure the best way to go about what I intend to do. I have an app that involves three fragments, each navigated to by a single activity that has a navigation drawer.
I have a text to speech class that initialises the text to speech engine. The problem is, is that it needs to be used by multiple different fragments. My idea was to create an object of the TTS class in the main Activity and extend functions so that they can be called by the fragments, like so:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTextToSpeechService = ((NavigationActivity)this.getActivity()).GetTextToSpeechService();
}
The problem I see here is, what if I need to do something such as change the language within one fragment. That would mean I'd have to expose another function to set the TTS class within the activity, which doesn't seem right.
What is the best way to go about this?

There are three options:
Inherit from application and store singleton there. You can see how to do that here.
Create started service and use it from activity.(not bounded) See the link.
Store language setting in SharedPreferences and apply them to textspeech engine in activity lifecycle methods (onResume method).
Services are designed for tasks which are not connected to UI. If it's too much work to be done you may find third option to be a candidate for this particular problem.

Related

Having an a fragment communicate via interface to activity that did not launch it

I have a fragment that communicates to an activity via an interface. This is cool and all but, is it possible to have the fragment communicate with an activity that did not launch it?
The reason why is I don't want one activity to be a million lines long of code implementing all interface methods for the fragments when I could just create "helper" activities to implement all the interfaces.
Currently I am using the Google Navigation drawer template so, maybe I could create new activities and group fragments around them. Im not sure if it will break my navigation drawer if I try to launch new activites.
Because of the activity lifecycle parameters of an activity are usually separated of the activity. You can store them in the savedInstancestate and retrieve them back. This way you make sure that your activity has the right information when it is restored.
If content changes somewhere during the app lifecycle it is good to store that content somewhere permanently (SharedPreferences, Database, File).
If you want to notify several parts of your app of an event a good way to go is a Local Broadcast.
Having said that it seems strange to me that another activity than the currently running one (and the one containing your fragment) should be notified of an event. When it is resumed it would collect the necessary information and update itself.
You're breaking android development practices. Fragments are encapsulated within an Activity. And an Activity is encapsulated within itself. An Activity should not communicate with another Activity via references.
Activities are communicating via references here, so I totally would not recommend doing this. But here's how you can do what you're asking.
class HelperActivity { // implement here
public static HelperActivity context = this;
public MyFragment myFragment = new MyFragment(this); // cast to implementation
}
class NormalActivity {
void onCreate {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_attach, HelperActivity.myFragment)
.commit();
}
}

Best way to access a parent Activity's data

This is a stylistic question more than an actual "how can this be done," but the basic situation is this: I have an Activity MyActivity which contains a MapFragment, as well as a List of Renderers which are my own class that takes care of displaying some data. The Renderers also have ViewPagers which get their content views from yet another class, let's call it ViewPagerTab. Sometimes, something happens in some of these ViewPagerTabs that necessitates the update of the map in the top level Activity. There are, as I see it, a few approaches:
1) Both my Renderers and my ViewPagerTabs contain a reference to the context. If I cast the context as MyActivity I can access its map parameter.
2) By using the reference to the context, I can call getSupportFragmentManager().findFragmentById(R.id.map)).getMap() on it and get the map that way.
3) I can pass the map down from the Activity to the Renderers to the ViewPagerTabs as they are created so the map is accessible in each as a class variable.
4) Use a BroadcastReceiver in my Activity and send a message to it when the map needs updating from my ViewPagerTab.
Have I missed anything? What's the best/cleanest way of doing this?
This lesson may give you some ideas:
Communicating with other Fragments
Basically, the idea is to define an interface in a subunit such as a Fragment, then implement it in the parent Activity. Then, actually call the methods in the interface in the Fragment.
Another alternative is to create a class that extends Application. There, you can "share and declare" a number of non-context specific variables (like a glorified container, but where you don't have to create multiple instances of, or do look ups).
Requires some setup in your manifest but then all your activities can call MyApp app = (MyApp) this.getApplication(); (or in fragments, via the onAttach activity's .getApplication() )
The standard way is to define a listener interface, but I've found this to be cumbersome. Otto is a really nice alternative that you should at least look into before making your decision.
I think this is a bit over my head but what about parcel.I think it wouldn't work because of the dynamic nature of your data however it is one way to communicate between activities.

How to make a core of activity on android?

I am new to Android development. After learning from many tutorials I got many Activities and many Fragments. How can I make a core engine to check what Activity is running and what Fragment is showing on a container?
Assume that I have:
Acivity01, Activity02, ... , Activity10
Fragment01, Fragment02, ... , Fragment10
I want to make a class that filters the Activity where Activity is on runtime and what Fragment is embeded to that activity.
How can I do this?
If I understand you correctly, you may want to store some references within your Application class to an Activity and to Fragment instance(-s), which are currently in foreground (by this I mean that user can instantly interact with Activity/Fragment).
As for Activity
Create some Activity field in your Application class and getter/setter methods for it (e.g., setCurrentActivity(), getCurrentActivity()). Then call setCurrentActivity() from onResume() method for each of your Activity instances. Don't forget to call setCurrentActivity, supplying null reference to ir in order to properly handle a case, when there are no foreground activities, but application is stll working.
As for Fragment
The general idea is similar to the first item, but there can be more than one Fragment instance in foreground state at time. So you need to store something like List, where you add your resumed fragments and remove paused.
You may also want to implement something similar for dialogs, for example. Then use the same strategy. Hope it will help.

Android: is better to do many activities, or 1 activity that changes on the fly?

If I need to do 10 similar activities, is it better I do:
10 activities and 10 layout?
1 activity and 10 layout?
1 activity and change the UI with visibility gone/visible?
I need an answer for:
performance
formality
If you use multiple activities, you will get the advantage of using the android activity stack mechanism. So if you want your users to be able to navigate with the back button, then it's the best bet.
Also, if your activities are very similar, then you can implement common code in an abstract class, and make your 10 activities extend this common class, thus sharing some code.
public abstract class CommonBehaviorActivity extends Activity {
protected void buildCommonThings() {
((TextView)findViewById(R.id.title)).setText(getTitle());
((ImageView)findViewById(R.id.image)).setDrawable(...);
}
abstract protected String getTitle();
}
public class MyActivity1 extends CommonBehaviorActivity {
...
protected String getTitle() {
return "Title 1";
}
}
and so on...
Edit : Added some sample code to show how to share things that you want to see in every sub-activity. For example, if you have a list in each activity, then you can define a specific adapter in the sub-activities in a getAdapter() method, and bind your list to this adapter in the CommonBehaviorActivity as well as configure it (bind listeners, and so on...)
On the other side, if you want to have a very fast switch between your activities, and you don't need to be able to go "back" with the button, then visible/gone view is maybe better.
Making several activities will make your code more readable and easier to debug as you won't deal with excessive if and else conditions. There will be no performance overhead: Activities load fast and Android manages the backstack and free up memories by killing paused activities when needed (which won't be the case with a single one).
If your activities are similar, you can put features in separate classes and re-use them across activities. Idem for layouts, you can design them so you can re-use common parts.
You can also use fragments if you want to for display dynamic UI. You can change content in fragment dynamically or you can change the fragment itself. You can always keep certain fragment visible and others inactive. In this case you will only need one activity and multiple fragments.
It will depend how you want draw UI of your app. Fragments examples are available is Here

Do I need to implement the onCreate(), onResume, etc methods in every activity I write?

I have started to explore the android world just some days ago, and I am doing it via the book by Mario Zechner, "Beginning Android Games".
I might have a ton of questions about the platform and the few things I have seen so far but I know it's going to get better. All I want to ask at the moment is about activities: I saw the activity life cycle. I know that activities are something like screens. The thing I don't know is that whether I have to specify the onCreate(), onResume() etc. methods in every activity I code.
As far as I know onCreate() is compulsory and the other methods depends on how you use the activity
The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). So onCreate(Bundle) should have be there in activity.
Use of onResume() depends upon your application requirement.
for more details go to http://developer.android.com/reference/android/app/Activity.html
Welcome to the world of Android.
In general, it is good practice to flesh out all the methods such as onPause(), onResume() but when you create an android program, generally you only need to flesh out the onCreate() method for activities.
Besides the onCreate, and pardon if my terminology is incorrect, the other methods follow a "default" behavior if you do not override them. So if you need the application to do something specific when it is paused, that would be a good time to add your version of onPause(), otherwise you can leave it left out.
It is not mandatory that you have to specify all those methods or any of them. It depends on what type of implementation you want
Example
I have created my Activity (A) as it extends Activity I donot override any of methods like onCreate() but I have created some variables and created some of methods.
Let us assume I created second activity there I want to shoe some view I have used onCreate() method also If I want variables and methods which I have defined in activity A I can get those variables and methods If I write class B extends A
So it is not mandatory to use all those methods from activity. If you donot write your own implementation then the default implementation will come to play.
Short answer will be NO
You don't need to specify in code of each Activity onCreate and so on. Anyway in parent Activity there will be onCreate
But long answer says: good practice is not rely on implicit/invisible code, but to have code under your control (even if it's dummy). I used to code all onCreate/onDestroy, etc in this way:
public static final boolean DEBUG=true;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if(DEBUG)
Log.d(TAG, "Creating "+this.toString());
}
You should write onCreate() method by overriding it from the base class Activity to set the view. View should be generated here itself using setContentView() method in onCreate() method.
Regarding onResume(), onPause() and other methods, it is not mandatory to write these but are useful when you need to achieve specific functionality.
Also, being a beginner please have a look at the table 1 in this document: http://developer.android.com/guide/topics/fundamentals/activities.html

Categories

Resources