user3227070 user3227070 - 4 months ago 18
Android Question

Pass data from activity to a non-fragment/activity class without using an interface

public boolean getFavourite(Winkel winkel){
boolean isFavourite = false;
MyDBHandler dbHandler = new MyDBHandler(context,null,null,1);
User user = dbHandler.loggedIn(); //This method isn't usable anymore
isFavourite = dbHandler.isFavourite(user,winkel);
return isFavourite;
}


I want to change this code to:

public boolean getFavourite(Winkel winkel){
boolean isFavourite = false;
MyDBHandler dbHandler = new MyDBHandler(context,null,null,1);
isFavourite = dbHandler.isFavourite(user,winkel);
return isFavourite;
}


I was using my database to keep track of which user was logged in at first, but it was really easy to change this by simply sending the data from my first activity to my second.

@Override
public void login(User user){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Username",user.getUserName());
startActivity(intent);
}


Then, in my second activity, I could call all the database functions by using this:

user.setUserName(intent.getStringExtra("Username"));


(Because I need the username as a key for my database.

However, my activity has three fragments, two of which use my adaptor for a recyclerview. These fragments implement the interface that is provided in my adaptor class, which is this one (just showing this to be complete, what the interface is is irrelevant, fact is that my fragments have to implement this interface).

public interface ItemCLickCallback {
void onItemClick(int p);
void onSecItemClick(int p);
}


Now, I need the username in my adaptor class. It has to come from my activity (because thats where its stored), and I can't use an interface because I'm already using one and I would have to override the methods in every fragment.

I could pass the data from my activity to all the fragments using a Bundle, then pass that along to the adaptor when creating it in my fragments. But that seems like a lot of excessive code. Any simpler way to do this? Thank you

Answer

:) You can use multiple inheritance. To be able to make a class implement multiple interfaces we need can have something like this:

public class MyClass extends MyOtherClass implements MyInterface1, MyInterface2, ... , MyInterfaceN {

    // Need to implement all interface methods here

}
Comments