1. Download our Official Android App: Forums for Android!

Calling Singleton from Fragment

Discussion in 'Android Development' started by Sriram Shanmugasundaram, Sep 2, 2017.

  1. Sriram Shanmugasundaram

    Thread Starter
    Rank:
    None
    Points:
    26
    Posts:
    10
    Joined:
    Aug 24, 2017

    Aug 24, 2017
    10
    1
    26
    How to call a singleton class from fragment in android studio?


    This is my code.
    MySingleton is the class here.

    MySingleton.getInstance(MapsFragment.this).addToRequestque(jsObjRequest);


    The compiler shows "get instance in MySingleton cannot be applied to MapsFragment.

    How to solve this?
     

    Advertisement

  2. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,879
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,879
    11,523
    1,988
    Male
    Software developer
    South West of England
    Move to Application Development Forum.

    Please show the code for class MySingleton.
     
  3. Sriram Shanmugasundaram

    Thread Starter
    Rank:
    None
    Points:
    26
    Posts:
    10
    Joined:
    Aug 24, 2017

    Aug 24, 2017
    10
    1
    26
    import android.content.Context;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.Volley;
    import android.content.Context;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.Volley;


    public class MySingleton {

    private static MySingleton mInstance;
    private RequestQueue requestQueue;
    private static Context mCtx;

    private MySingleton(Context context){
    mCtx = context;
    requestQueue = getRequestQueue();
    }


    public RequestQueue getRequestQueue(){
    if(requestQueue==null){
    requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());

    }
    return requestQueue;
    }
    public static synchronized MySingleton getInstance(Context context)
    {
    if(mInstance==null)
    {
    mInstance = new MySingleton(context);
    }
    return mInstance;
    }

    public<T> void addToRequestque(Request<T> request){
    requestQueue.add(request);
    }
    }
     
  4. Sriram Shanmugasundaram

    Thread Starter
    Rank:
    None
    Points:
    26
    Posts:
    10
    Joined:
    Aug 24, 2017

    Aug 24, 2017
    10
    1
    26
    Please tell me how to call this from fragment.

    I am using the following code to call.

    MySingleton.getInstance(
    ProductFragment.this).addToRequestque(jsObjRequest);
    }
     
  5. Sriram Shanmugasundaram

    Thread Starter
    Rank:
    None
    Points:
    26
    Posts:
    10
    Joined:
    Aug 24, 2017

    Aug 24, 2017
    10
    1
    26


    And it shows cannot resolve get Instance
     

Share This Page

Loading...