Android. Instantiating a interface? - android

I don't actually have a question, just want to ask you to explain me this code
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
is this about a class object which implements interface's method ?
even if it is, please explain it
thanks

The code creates interface OnHeadlineSelectedListener and requires that any activity to which the fragment is attached must implement this interface. (OnHeadlineSelectedListener) activity tries to cast an activity to that interface, i.e. checks whether the activity implements it. If it does not, ClassCastException is thrown.

First, when you want to communicate between your activity and a fragment, for instance; if you have an application that lets users selected a headline and then open a details for it, you can use an interface as you show above.
Interface definition
An interface is a contract that whoever implements it must respect/adhere to. Just like any other contract in real life.
Now, in your Fragment, when you are ready to notify your activity of something - considering they implemented the interface for exactly this reason (to be notified), you ensure to cast the interface to your activity and throw a ClassCastException to let the class know that it must implement the interface.
Type
When you cast an interface to the activity, it implies that when an activity implements an interface, it becomes of that type (interface type).
Subscriber/Publisher Design Pattern
If you think about it, this sounds like the popular Subscriber/Publisher design pattern.
How?
The Fragment is the publisher in this case.
The activity is the subscriber here
So, in essence, in order to obey the rules of a contract, the activity MUST implement the interface that helps the two classes communicate!
I hope this helps.
By the way, this sounds and looks really similar to my demo application currently published on PlayStore.

Related

What's the use of Interface class in the Fragment?

i have a created a fragment and can't find what is the use of Interface class in this Fragment...i google it but can't find the right documentation?
Thank you for your concern!
public class SongListFragment extends Fragment {
public SongListFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
songIds = getArguments().getIntArray(SONG_IDS);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
//what's the use?
public interface OnFragmentInteractionListener {
public void onSongSelected(int songId);
}
}
OnFragmentInteractionListener could be use to communicate between fragments
To allow a Fragment to communicate up to its Activity, you can define
an interface in the Fragment class and implement it within the
Activity. The Fragment captures the interface implementation during
its onAttach() lifecycle method and can then call the Interface
methods in order to communicate with the Activity.
Find another SO example here
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
You might have a brief idea over here Feel free to ask if any confusion rises! :)
So in your particular case your Activity must implement that interface OnFragmentInteractionListener otherwise the fragments which are attached in the Activity cannot communicate with each other. Your activity should look like
public class YourActivity extends Activity implements OnFragmentInteractionListener
Then in your Activity you implement the method onSongSelected(int songId)
You might get help from here. Hope this helps!
#Tahmid Rahman explains what an interface is in there answer.
In this specific case the interface should be implemented in the Activity that your fragment is attaching to. That will allow the fragment to call onSongSelected() on the activity. Then the activity can in turn properly handle the users requested action.
Without the interface, there would not be a well defined way for the fragment to tell its parent activity that the user had clicked on a song.
Interface is used to communicate between fragment and activity or between multiple fragments when an event occurs.
See the Documentation
in your case:
public static class MainActivity extends Activity
implements SongListFragment.OnFragmentInteractionListener{
...
public void onSongSelected(int songId) { //this method must be implemented
// The user selected the song from the list in SongListFragment
// Do something here to display that song..in your activity
}
}
you can implement the interface in your activity and write the onSongSelected method with the song id passed as parameter.
So basically it is used to pass selected song list information to other activity or fragment when a selection occurs

public Interface for Android

I need a little help with my Interface. I think that i doesn't understand them at all.
So i created this interface to notify every classes that implements it when a certain event occurs.
public interface OnColorsChangeListener {
void onColorsChangeListener(ColorsProp colorsProp);
}
My class that hold the interface:
private OnColorsChangeListener mCallback;
... // other code
// the event occurs here so i call:
mCallback.onColorsChangeListener(mProps);
// but of course here i get an NPE becouse this is undefined in this class.. well, with some replies here i'll understand better how to use that for reach my point
The class that implements it:
public class ClassTest implements OnColorsChangeListener {
... // other code
#Override
public void onColorsChangeListener(ColorsProp colorsProp) {
Log.d(TAG, "Color changed! " + colorsProp.color);
}
i put this in 4/5 classes to be notified in the same time for the color change. I'm quite sure the reason is that I didn't understand very well how them works, so can anyone point me to the right direction? Thank you!
Explanation by example:
You have to instantiate your callback, & it has to be an instance of your class
private OnColorsChangeListener mCallback;
mCallback = new ClassTest();
mCallback.onColorsChangeListener(mProps);
However if you want multiple callbacks you will need to use the Observer pattern.
Simple example:
private List<OnColorsChangeListener> mCallbacks = new ArrayList<OnColorsChangeListener>();
mCallbacks.add(new ClassTest());
mCallbacks.add(new OtherClass());
for(OnColorsChangeListener listener : mCallbacks) {
listener.onColorsChangeListener(mProps);
}
Obviously if you have the class, somewhere else you would not new it up, you would use that reference:
mCallbacks.add(mClassTest);
Observer Pattern Wikipedia
An interface is just a way to group together a bunch of related methods. Implementing this interface then requires you to implement all the methods grouped together by the interface.
The Java Tutorials has a good read on the subject:
What is an interface?
Here's a Stackoverflow thread regarding listener interfaces in android:
How to create our own Listener interface in android?
In short, you don't use the interface directly since it only specifies which methods implementing classes are supposed to implement.

Name technique for passing data from fragment/activity to fragment/activity with interfaces

At school we're now learning on how to make fragments more universal by using interfaces.
This technique is still kinda abstract and I don't really know when/how to use it.
Can anybody point me to some resources on how to use that technique (Could it be called interface callbacks?)
All help is very appreciated!
The callback approach, as you would call it, is as simple as Listener interface found in many parts of Java or Android. You may check the Observer pattern if you want to learn about a very general description. But if you already understand how to work with Listener, you will easily get the point about callbacks.
NOTE: Do not mix it with Callback term - these are not the same.
Suppose we have Activity MyActivity and Fragment MyFragment. We want to post some data from Fragment to Activity. Then let us create an interface within MyFragment:
public class MyFragment extends Fragment{
private PostDataCallback mCallback;//our Activity will implement this
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (PostDataCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
public interface PostDataCallback{
public void onPostData(Object data);
}
/*
we trigger this method when we calculated
data or something like that and want to post it*/
public void onSomeEvent(Object data){
mCallback.onPostData(data);
}
}
Our MyActivity will look like this:
public class MyActivity extends Activity implements MyFragment.PostDataCallback{
private Object data;
#Override
protected void onCreate(Bundle savedInstanceState){
getFragmentManager().beginTransaction().add(R.id.some_container_id, new MyFragment(), "my fragment");
}
#Override
public void onPostData(Object data){
this.data = data;
//some operations
}
}
So, MyFragment knows nothing about the implementation of it's callback. But it knows, that it can call the method onPostData(Object o) on the instance of PostDataCallback, which is held in the variable mCallback.
Thus, when MyFragment triggers it's mCallback.onPostData(data), MyActivity get's the result.
Exactly the same approach would work if we wanted to send message from MyActivity to MyFragment, but we would do it do it vice versa: the trigger method, callback interface definition and instance would reside in MyActivity, and MyFragment would implement the interface.
Here are steps:
Download sample data from http://developer.android.com/training/basics/fragments/index.html(given in right side) and also look at url to how to add fragments from xml or dynamically to performing fragment transaction operations..
Then would recommend you to go through with fragment guide..http://developer.android.com/guide/components/fragments.html
Once you understand complete life cycle and its fragment callback methods then would be easy to understand example given by Google as sample.
To defining interface in fragment to calling interface or passing callback to activity..
Let’s say you have two fragments which shows list as article titles and article details.
In your article list extends fragment list public class Fragment1 extends ListFragment
Set your list view using list adapter in oncreateview method.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, Array);
setListAdapter(adapter);
Now we need to display article details when user click on article, so we need to pass position to activity to it can call back corresponding article details to show in fragment2.
So when user click on article, system call onListItemClick callback method.
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Call interface here and pass article position
Define interface and pass position in method which activity will override.
public interface OnArticleSelectedListener {
public void onArticleSelected(int position);
}
In on attach method instantiates an instance of interface by casting the Activity, If the activity has not implemented the interface, then the fragment throws a ClassCastException. On success.
Override interface method to display article details by passing position as bundle data to Fragment2.
Hope it will help you to understand sample code.
You can simple create new Android Application project in eclipse.
Then create Android Object (Fragment) with callback methods. This will give you an idea for interfaces.
And then the same you can apply for activity to fragment.

Android communication between activity and fragment

I have an activity which contains a ViewPager inside it.The ViewPager's Adapter is FragmentStatePagerAdapter. Each page is Fragment.The Fragment contains a number of Threads. My problem is, I have to stop all the threads inside the fragment when ViewPager's page is changed.How can I do this ?
you have asked about communication between activity and fragment that you achieve using interface:
Your Fragment:
public class YourFragment
extends Fragment{
private OnListener listener;
public interface OnListener
{
void onChange();
}
void initialize( OnListener listener)
{
this.listener = listener;
}
//onview pager change call your interface method that will go to the activity as it has the listener for interface.
listener.onChange();
}
Your Activity:
public class yourActivity
extends Activity
implements yourFragment.OnListener
{
// intialize the method of fragment to set listener for interface where you define fragment.
yourFragment.initialize( this );
// implement what you want to do in interface method.
#Override
public void onChange()
{
// implement what you want to do
}
}
hope it will help.
Android's philosophy with applications is to kill processes, so maybe following the same idea you could kill your Threads. Be aware though that this can lead to deadlocks if your Threads own locks, or monitors.
A more serious approach to me seems to use Thread.interrupt() from your Activity. Then your Threads in your Fragment have to check Thread.interrupted for interruption, and finish gracefully if they've been interrupted.
You can use Thread.join() if you want some synchronous behavior
In addition, you can wait for a certain amount of time for your Thread to finish gracefully using a Timer, then kill them on timeout.
Please have a look at java.lang.Thread
To let this be more easy to implement, you could use a ThreadPoolExecutor or some other helper of java.util.concurrent package.

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.

Categories

Resources