Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of Singleton class in Volley

I used Volley library to download a image with the help of Singleton class.
Problem :

If I used a single ton class I can download a image successfully with in a time and also I noticed that image is downloaded successfully with out using the single ton class also.

Will you please any one tell me what are the benefits with the singleton class into my code .

---------------------Code With Singleton Class --------------------

MainActivity.java

public class MainActivity extends AppCompatActivity {
    Button response_click;
    TextView text_response;
    RequestQueue requestQueue;
    String server_url="http://i.imgur.com/7spzG.png";
    ImageView imageView;
    ImageRequest imageRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        response_click=(Button) findViewById(R.id.click_response);
        text_response=(TextView) findViewById(R.id.text_response);
        imageView=(ImageView) findViewById(R.id.image_download);
    }//onCreate Ending
    public void response_click(View view){
   
        final ImageRequest imageRequest=new ImageRequest(server_url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                imageView.setImageBitmap(response);
            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),"You Got an Error....",Toast.LENGTH_LONG).show();

            }
        });
MySingleTon.getInstance(MainActivity.this).addToRequestQue(imageRequest);

    }//Button Click Ending
}//Main Activity Ending

MySingleTon.java

public class MySingleTon {
    private static MySingleTon mySingleTon;
    private RequestQueue requestQueue;
    private static Context mctx;
    private MySingleTon(Context context){
        this.mctx=context;
        this.requestQueue=getRequestQueue();

    }
    public RequestQueue getRequestQueue(){
        if (requestQueue==null){
            requestQueue= Volley.newRequestQueue(mctx.getApplicationContext());
        }
        return requestQueue;
    }
   public static synchronized MySingleTon getInstance(Context context){
       if (mySingleTon==null){
           mySingleTon=new MySingleTon(context);
       }
       return mySingleTon;
   }
    public<T> void addToRequestQue(Request<T> request){
        requestQueue.add(request);

    }
}

Here, I write a code for downloading the image with out using the Singleton class. Please Check this code also.
Here remember one thing, With out using the Singleton class also I done my job with out any errors.

------------------------code With Out Singleton class -----------------------

MainActivity.java

public class MainActivity extends AppCompatActivity {
    Button response_click;
    TextView text_response;
    RequestQueue requestQueue;
    String server_url="http://i.imgur.com/7spzG.png";
    ImageView imageView;
    ImageRequest imageRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        response_click=(Button) findViewById(R.id.click_response);
        text_response=(TextView) findViewById(R.id.text_response);
        imageView=(ImageView) findViewById(R.id.image_download);
    }//onCreate Ending
    public void response_click(View view){
        requestQueue=Volley.newRequestQueue(this.getApplicationContext());
        final ImageRequest imageRequest=new ImageRequest(server_url, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                imageView.setImageBitmap(response);
            }
        }, 0, 0, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),"You Got an Error....",Toast.LENGTH_LONG).show();

            }
        });

        requestQueue.add(imageRequest);
        
    }//Button Click Ending
}//Main Activity Ending
like image 307
sreeku24 Avatar asked Dec 13 '16 11:12

sreeku24


People also ask

What is volley Singleton in Android?

Your singleton class contains a static reference to the context which can cause a memory leak. Instead of this, you can use an application instance like this public class AppController extends Application { public static final String TAG = AppController.

What is requestQueue in volley?

requestQueue is used to stack your request and handles your cache. You need to create this RequestQueue in your application class or in a Singleton class. Then only you can use the same requestQueue from multiple activities.

Why do we use volley?

Advantages of Using VolleyAll the tasks that need to be done with Networking in Android, can be done with the help of Volley. Automatic scheduling of network requests. Multiple concurrent network connections. Cancelling request API.

How does volley work?

Volley automatically schedules all network requests such as fetching responses for image from web. Volley provides transparent disk and memory caching. Volley provides powerful cancellation request API for canceling a single request or you can set blocks of requests to cancel.


1 Answers

If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality. Another approach is to subclass Application and set up the RequestQueue in Application.onCreate(). But this approach is discouraged; a static singleton can provide the same functionality in a more modular way.

A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).

Read the documentation https://developer.android.com/training/volley/requestqueue.html#singleton

like image 59
Tiwa Babalola Avatar answered Nov 05 '22 17:11

Tiwa Babalola