2015-11-28 26 views
0

我想我有與Java的「對象化傾向」如何保持請求queu的單個實例在我的整個應用

所以在這裏我有一個列表適配器調用凌空

public class MyList extends ArrayAdapter<> { 

// .... 

VolleyClass vc = new VolleyClass(getContext()); 
vc.runVolley(); 

// ... 

} 

麻煩但我不想在列表適配器的每次迭代中實例化另一個請求隊列。

所以在VolleyClass我加入這個方法

/** 
* @return The Volley Request queue, the queue will be created if it is null 
*/ 
public RequestQueue getRequestQueue() { 
    // lazy initialize the request queue, the queue instance will be 
    // created when it is accessed for the first time 
    if (mRequestQueue == null) { 
     mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
    } 

    return mRequestQueue; 
} 

但由於我在列表中的適配器使得VolleyClass的新實例,我還總是請求隊列的新實例。

如何在使用Java語言的整個應用程序中維護請求隊列的一個實例?

回答

0

使mRequestQueue靜態。 這樣,

public static RequestQueue mRequestQueue; 

public static RequestQueue getRequestQueue() { 
    if (mRequestQueue == null) { 
     mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
    } 
    return mRequestQueue; 
} 

在Java中,如果你犯了一個靜態變量,只有一個變量的實例可以在內存無論你創建多少個對象可以存在。所有的對象將共享這個單一的實例。

閱讀更多關於單身人士here

相關問題