javaandroidandroid-fragmentsodooandroid-webservice

How to persist authentication to web service in all fragments on Android?


I'm using a Odoo service. And I have 3 fragments in my application.

In each fragment I need log to service:

OdooClient odoo;
odoo = new OdooClient.Builder(getActivity()).setHost(host).build();

odoo.setOnConnectListener(new OdooConnectListener() {
   @Override
   public void onConnected(OdooVersion version) {
     Log.i(TAG,"onConnected");
     Log.i(TAG,odoo.getDatabases().toString());
     odoo.authenticate(username,password,db,loginCallback);
   }
 });

There are a way to authenticate just one time for all fragments? I can authenticate on MainActivity, but I can't take the reference of the object.


Solution

  • You can do the authentication in a singleton, init in the main Activity (pass context and host) and then only get the reference in Fragments

    EDIT

    public class Odoo {
    public static OdooClient CLIENT;
    public static void init(Context context,String host) {
         CLIENT=new OdooClient.Builder(context).setHost(host).build();
    }
    

    Now you can call init in Main Activity

    Odoo.init(this,host);
    

    And then get the reference in fragments

    Odoo.CLIENT.setOnConnectedListener(...);