I used the Volley library to upload an image using the Singleton class.
Problem:
If I used a plain-colored class, I could successfully load the image at a time, and I also noticed that the image was loaded successfully without using the plain-colored class.
Could you tell me what are the advantages of the singleton class in my code?
--------------------- Code with class Singleton --------------------
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); }
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 am writing code to upload an image without using the Singleton class. Please check this code also.
One thing to keep in mind here: without using the Singleton class, I also did my job without errors.
--- --------------------- Code Without the 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); }
source share