public class MainActivity extends fragment
public class MainActivity extends Activity
The issue I have is that I need to extend Fragment to be able to use the 'pager_title_strip' but to use a list view that can read json, it also needs to be extended.
How can I extend both within the same class?
You can't, a class can only extend one other class.
It can however implement multiple interfaces, maybe that can help you in your design.
Abstractly spoken, multiple inheritance is not the only answer to such design problems, and in Java it was excluded by designers of Java (Gosling et.al.) because they saw it as inherently unsafe. Still in Java 8 multiple inheritance is only allowed for behaviour (see interface inheritance and new "default" methods), but not in state.
Alternatively, you can also think about composition or delegate patterns. From Joshua Bloch we know his recommendation "Favor composition for inheritance". I think this should be possible in your case.
There is FragmentActivity or ActionBarActivity class which may solve your problem!
http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html
The issue I have is that I need to extend Fragment to be able to use the 'pager_title_strip'
There is no requirement to use fragments at all with a ViewPager, let alone with a PagerTitleStrip or PagerTabStrip.
so saying that does this mean you aren't able to use a listview box that reads json and the pager title strip at the same time?
It is perfectly possible to "use a listview box that reads json and the pager title strip at the same time". However, you will need to create more than one Java class, in all likelihood, such as an Activity and a Fragment.
Related
Total beginner here.
As I understand, fragments should communicate with each other through their hosting activities as a way to stay independent and reusable in other situations.
I’ve read that should be done by declaring interfaces in the fragment and implementing them in the activity.
Is that the best way to go about it “just” because you can make sure the activity is ready for that communication (it really has that method to deal with the communication)?
As I’m having a hard time wrapping my head around interfaces (and lots of others things in java/android, for that matter), could this be done without the interface? Could I get a reference to the hosting activity in the fragment and just call the activity’s method?
(fragment class)
Activity activity = getActivity();
activity.doThatThingToOtherFrag(String myString);
(activity class)
Fragment otherFragment = getSupportFragmentManager().findFragmentById(R.id.myOtherFrag);
public void doThatThingToOtherFrag(String string) {
//do something to myOtherFrag
}
Or is there something else about implementing an interface in this case that I’m not getting?
* EDIT *
Let’s say I reuse that fragment in another activity. As long as that activity also has a doThatThingToOtherFrag(String myString) method, I can get a reference to it through getActivity() and still call activity.doThatThingToOtherFrag(String myString) from my fragment, right? I wouldn’t have to change anything in my fragment code -- or am I’m missing something here?
I guess my question should be: is the interface there only to MAKE SURE the/any hosting activity implements a doThatThingToOtherFrag method? Or is there something else I don’t know about interfaces in this situation? Thanks for the help!
"Program to the interface." is a common maxim of object oriented programming. You can certainly just communicate with the activity directly without using the interface. However, this create a tight coupling between the fragment and the activity.
Consider a situation where you want to reuse the same fragment in two different activities. Using interface allows the flexibility to do this.
Answer to edit:
As long as that activity also has a doThatThingToOtherFrag(String myString) method, I can get a reference to it through getActivity() and still call activity.doThatThingToOtherFrag(String myString) from my fragment, right?
I assume you mean something like this:
Activity activity = getActivity();
activity.doThatThingToOtherFrag(String myString);
This won't compile because Activity doesn't have a method named doThatThingToOtherFrag(). However, if you do
FragmentCommunicationInterface activity = (FragmentCommunicationInterface) getActivity();
activity.doThatThingToOtherFrag(String myString);
now it will compile. This has yet another problem: what if the fragment where this is called was added to an Activity which doesn't implement FragmentCommunicationInterface. Now you will get a run-time error when you do the case.
One possible solution to this is to take a FragmentCommunicationInterface as an argument to the fragment's constructor:
public class MyFragment extends Fragment {
private FragmentCommunicationInterface communication;
public MyFragment(FragmentCommunicationInterface communication) {
this.communication = communication;
}
}
Now you create a fragment with
MyFragment frag = new MyFragment(this);
Another advantage to using an interface is that the interface can be implemented by any class not just classes which extend Activity. This allows even more flexibility than I hinted above. It allows you to organize the code to communicate with the activity or other fragments in any way you want.
It's not really necessary, but it may be desirable.
In general, interfaces help code not depend on the class whose code you call. You don't really care which Fragment class you're invoking, what you really care is that whatever you're invoking, it needs to have the ability to doThisOrThat() -- so that's what you put in your interface.
This decoupling is actually about helping to use polymorphism. Say your code may use two Fragment classes where you now use one, and both ca n doThisOrThat(). In that case using an interface will help you write cleaner code, because you won't need to write duplicate code to invoke the same method, except for changing what you cast it to.
Anyway, in order to really decouple you classes, you might want to learn about EventBus (doesn't matter which implementation).
This way you can make your fragment work with any activity that implements the interface. This completely adds to the independence and reusability you pointed out in your question.
If you would use the activity class's method to 'communicate' you would not be able to make it work (interface with) other activities because they are of a different class.
One good reason not to do the way you implemented as above is loose coupling. It is a program design pattern to create well-designed software. I am not gonna create a new discussion of it here since a lot of other discussions are available in StackOverflow.
What is "loose coupling?" Please provide examples
Please take time to understand this concept as this will save you a lot of time as a programmer.
Cheers!
Interfaces are best for communicating two fragments, 2 activities or communicate with any class, because interface triggered at same time when other want to communicate.
There are methods and attributes I would like to share across activities. E.g.
public class BaseActivity extends Activity
would be the parent for another activity
public class MainActivity extends BaseActivity
BUT if the child activity is a e.g. ListActivity this is not possible, right? Do I need a base class for ListActivity, too? This would be redundant code.
I could transform the ListActivity to an Activity, but this would be more code then necessary.
Any suggestions?
Yes, you're right. As java does not support multiple inheritance, a class can only have one base class.
But you can work via delegation instead of inheritance: Put your methods into a separate class (which does NOT inherit Activity) and use instances of it in your activities. Then you can reduce the redundant code (creating and holding the instance) to a minimum.
See also:
http://sourcemaking.com/refactoring/replace-inheritance-with-delegation
How do I implement multiple inheritence in Java
For the ListActivity case I would create a BaseListActivity that extends from BaseActivity. The BaseListActivity would contain a getListView() that returns the ListView if you really-really need it, a protected method setAdapter() that receives an Adapter/ListAdapter. You could also create some protected methods for enabling to show the empty view, to enable this behavior and to return the ids for your empty view and ListView. By default these should point to android.R.id.list/android.R.id.empty. But you can override that in your child activity.
In the end it's a matter of OOP and not that much of Android specific. If you check the implementation of ListActivity you'll see how simple it is to make your own BaseListActivity implementation. In the end it's more important to have a consistent and robust class hierarchy.
I am using my Activities this way, and I'm really happy I'm doing it. Of course you have to make some changes (like the ListActivity you mentioned in your question), but it has more advantages then disadvantages in my opinion.
In my app I don't have to worry about sending Analytics data every time I create a new Activity, and I also don't have to worry about setting up BroadcastReceivers I need in every class, I just made my BaseActivity abstract and have an abstract function what I call every time my BaseActivity gets a broadcast.
if you want to share some methods the best way it to impelement an interface or make an abstract class for baseactivty.
As others have pointed out, you need to use composition, since multiple inheritance is not possible in Java. This answer to a related question explains how to do this in the case of Android Activities.
The question doesn't really make sense, but this should help explain it better.
I'm currently using the IOIO, and it works like this:
public class MainActivity extends CustomIOIOActivity {}
From there I can call classes I've made in CustomIOIOActivity, which extends Activity.
The problem I'm running into now is that I have to inherit classes different from just Activity. For example, FragmentActivity.
Is there a way for me to create a custom IOIO activity which I can use for when I extend Activity and FragmentActivity? I don't want to have to make two essentially identical classes, which is what I am doing right now--seems silly. I'm not very familiar with Java, perhaps this is easy to do.
In Java you can't inherit class from more than one superclass. In order to achive your purpose, I would advise you to move all common logic to another class(IOIOHolder, for example), which would take an Activity parameter in constructor. Later you can create two different classes extending Activity and FragmentActivity, each containing an exemplar of IOIOHolder and using it for it's own tasks. By using this approach you can write IOIO code once and use it in any activity you want.
I have two ListFragments which needs to share some code. This was very basic by just creating a abstract fragment extending ListFragment and then let my two fragments both extend my abstract fragment.
However, now I need a third fragment to use the code from my abstract fragment. However, this third fragment is not a ListFragment but a GridFragment.
Is there a good way to solve this problem?
As java won't support multiple inheritance either seperate your generic code in to Fragment Super class or make static methods.
or
Simply write a FragmentUtil class.
I would suggest you put your shared code in class that dont extends any Fragments. In your fragments classes you make calls to your SharedCode.class .
I am attempting to add the same action bar compatibility found in the Google "ActionBarCompat" sample code to one of my projects.
My problem is that I already extend MapActivity in my main class, but the main class of ActionBarCompat seems to require that you extend ActionBarActivity.
Here's my Java 101 question: I know enough about Java to know that I can't have multiple inheritance, but not enough to know the ideal way to handle this situation. My solution was to extend ActionBarActivity in my main class, but then make ActionBarActivity extend MapActivity. Is this the correct way to do this? If so, wouldn't I have to make a duplicate ActionBarActivity if I want it to extend other things?
Thanks for your consideration of this question!
Yes, that's a totally valid way of doing this. If you want an ActionBarActivity class that doesn't extend the MapActivity, you'll have to create another class. I don't think this will lead to a lot of code-duplication (which I'm guessing is what you're afraid of). Shame on the android developers though for making you need to code your own ActionBarHelper class.
Look at the example you provided - ActionBarActivity is only having an ActionBarHelper field and calling methods on it. Try doin the same in you MapActivity.
Use "Peter Knego"'s solution, and link to this library:
https://github.com/lvillani/android-compat-actionbar
or if your using Eclipse and svn :
https://svn.github.com/lvillani/android-compat-actionbar