Skip to content Skip to sidebar Skip to footer

Using Nested Interfaces For Communication Between Two Classes In Java / Android

can anyone tell me if I am right or wrong? I am really getting confused in solving my problem. What I have is (or what I want to do Or am thinking is:) I have: Class B{ ....

Solution 1:

It seems that what you are trying to figure out is communication between Fragments. Here it is well explained. If you want to communicate between Activities then you should read about Intents.


Solution 2:

I'm not completely sure I understand but it sounds like you just need to implement a DB class. For this you can find many good examples such as Here. In ActivityA you can do your DB stuff in an AsyncTask so that these operations are done in the background and don't hold up your UI thread. Then use a separate AyncTask in ActivityB to access your DB class to retrieve the info

As far as using OnClickListeners, you can do this in different ways. You can define them in a separate class but it is usually easier and just as efficient to do them in the class that utilizes them.You can define them in your xml with

<Button
android:id="@+id/btn1"
// button attributes
android:onClick=methodName/>

then in your java code

public void methodName(View v)
    {
     //do stuff here
    }

or use something like

   button1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // do more stuff
    }
});

in your java code after defining button1

Without seeing code and knowing your specific question, this is what it sounds like you might be looking for. If not, please be more specific as to what you want and maybe we can better assist you


Solution 3:

Interfaces are meant to define a type of behavior in Java. If a class implements an interface, it is reassuring the compiler that it can do all the methods in that interface.

For example, you could have a Printable interface with methods required of objects that can be printed (e.g. a getStringRepresentation method). Any class that implements Printable must implement all its methods, and so you must be able to print objects of that class.

You can read more about interfaces here.

If you just want to pass data from class A to class B, you don't necessarily need an interface as you don't have multiple class which can do the same thing, which is when you may need to define their common behavior by using an interface.

Why couldn't you just pass the data from class A to and object of class B using a parameter of one of B's methods?

e.g.

// somewhere in the methods of A
B b = new B();
b.giveData(theData);

Post a Comment for "Using Nested Interfaces For Communication Between Two Classes In Java / Android"