Skip to content

Commit 8aa14e7

Browse files
author
Vivek Maskara
authored
Merge pull request commons-app#601 from commons-app/prehackStaticStuff
Cleanup CommonsApplication Singelton
2 parents 45a1962 + 4bda301 commit 8aa14e7

35 files changed

+153
-116
lines changed

app/src/main/java/fr/free/nrw/commons/CommonsApplication.java

+76-37
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import fr.free.nrw.commons.data.DBOpenHelper;
3131
import fr.free.nrw.commons.modifications.ModifierSequence;
3232
import fr.free.nrw.commons.auth.AccountUtil;
33+
import fr.free.nrw.commons.nearby.NearbyPlaces;
3334

3435
import org.acra.ACRA;
3536
import org.acra.ReportingInteractionMode;
@@ -62,7 +63,6 @@
6263
)
6364
public class CommonsApplication extends Application {
6465

65-
private MWApi api;
6666
private Account currentAccount = null; // Unlike a savings account...
6767
public static final String API_URL = "https://commons.wikimedia.org/w/api.php";
6868
public static final String IMAGE_URL_BASE = "https://upload.wikimedia.org/wikipedia/commons";
@@ -81,13 +81,37 @@ public class CommonsApplication extends Application {
8181
public static final String FEEDBACK_EMAIL = "commons-app-android@googlegroups.com";
8282
public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App (%s) Feedback";
8383

84-
public RequestQueue volleyQueue;
84+
private static CommonsApplication instance = null;
85+
private AbstractHttpClient httpClient = null;
86+
private MWApi api = null;
87+
private CacheController cacheData = null;
88+
private RequestQueue volleyQueue = null;
89+
private DBOpenHelper dbOpenHelper = null;
90+
private NearbyPlaces nearbyPlaces = null;
8591

86-
public CacheController cacheData;
92+
/**
93+
* This should not be called by ANY application code (other than the magic Android glue)
94+
* Use CommonsApplication.getInstance() instead to get the singleton.
95+
*/
96+
public CommonsApplication() {
97+
CommonsApplication.instance = this;
98+
}
8799

88-
public static CommonsApplication app;
100+
public static CommonsApplication getInstance() {
101+
if (instance == null) {
102+
instance = new CommonsApplication();
103+
}
104+
return instance;
105+
}
89106

90-
public static AbstractHttpClient createHttpClient() {
107+
public AbstractHttpClient getHttpClient() {
108+
if (httpClient == null) {
109+
httpClient = newHttpClient();
110+
}
111+
return httpClient;
112+
}
113+
114+
private AbstractHttpClient newHttpClient() {
91115
BasicHttpParams params = new BasicHttpParams();
92116
SchemeRegistry schemeRegistry = new SchemeRegistry();
93117
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
@@ -98,14 +122,50 @@ public static AbstractHttpClient createHttpClient() {
98122
return new DefaultHttpClient(cm, params);
99123
}
100124

101-
public static MWApi createMWApi() {
102-
return new MWApi(API_URL, createHttpClient());
125+
public MWApi getMWApi() {
126+
if (api == null) {
127+
api = newMWApi();
128+
}
129+
return api;
130+
}
131+
132+
private MWApi newMWApi() {
133+
return new MWApi(API_URL, getHttpClient());
134+
}
135+
136+
public CacheController getCacheData() {
137+
if (cacheData == null) {
138+
cacheData = new CacheController();
139+
}
140+
return cacheData;
141+
}
142+
143+
public RequestQueue getVolleyQueue() {
144+
if (volleyQueue == null) {
145+
DiskBasedCache cache = new DiskBasedCache(getCacheDir(), 16 * 1024 * 1024);
146+
volleyQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
147+
volleyQueue.start();
148+
}
149+
return volleyQueue;
150+
}
151+
152+
public synchronized DBOpenHelper getDBOpenHelper() {
153+
if (dbOpenHelper == null) {
154+
dbOpenHelper = new DBOpenHelper(this);
155+
}
156+
return dbOpenHelper;
157+
}
158+
159+
public synchronized NearbyPlaces getNearbyPlaces() {
160+
if (nearbyPlaces == null) {
161+
nearbyPlaces = new NearbyPlaces();
162+
}
163+
return nearbyPlaces;
103164
}
104165

105166
@Override
106167
public void onCreate() {
107168
super.onCreate();
108-
app = this;
109169

110170
Timber.plant(new Timber.DebugTree());
111171

@@ -116,9 +176,8 @@ public void onCreate() {
116176
}
117177
// Fire progress callbacks for every 3% of uploaded content
118178
System.setProperty("in.yuvi.http.fluent.PROGRESS_TRIGGER_THRESHOLD", "3.0");
119-
api = createMWApi();
120179

121-
ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(getApplicationContext())
180+
ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this)
122181
.discCache(new TotalSizeLimitedDiscCache(StorageUtils.getCacheDirectory(this), 128 * 1024 * 1024))
123182
.build();
124183
ImageLoader.getInstance().init(imageLoaderConfiguration);
@@ -147,21 +206,14 @@ protected int sizeOf(String key, Bitmap bitmap) {
147206
}
148207
};
149208
}
150-
151-
//For caching area -> categories
152-
cacheData = new CacheController();
153-
154-
DiskBasedCache cache = new DiskBasedCache(getCacheDir(), 16 * 1024 * 1024);
155-
volleyQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
156-
volleyQueue.start();
157209
}
158210

159211
private com.android.volley.toolbox.ImageLoader imageLoader;
160212
private LruCache<String, Bitmap> imageCache;
161213

162214
public com.android.volley.toolbox.ImageLoader getImageLoader() {
163215
if(imageLoader == null) {
164-
imageLoader = new com.android.volley.toolbox.ImageLoader(volleyQueue, new com.android.volley.toolbox.ImageLoader.ImageCache() {
216+
imageLoader = new com.android.volley.toolbox.ImageLoader(getVolleyQueue(), new com.android.volley.toolbox.ImageLoader.ImageCache() {
165217
@Override
166218
public Bitmap getBitmap(String key) {
167219
return imageCache.get(key);
@@ -176,13 +228,9 @@ public void putBitmap(String key, Bitmap bitmap) {
176228
}
177229
return imageLoader;
178230
}
179-
180-
public MWApi getApi() {
181-
return api;
182-
}
183231

184232
/**
185-
* @return Accout|null
233+
* @return Account|null
186234
*/
187235
public Account getCurrentAccount() {
188236
if(currentAccount == null) {
@@ -203,21 +251,12 @@ public Boolean revalidateAuthToken() {
203251
return false; // This should never happen
204252
}
205253

206-
accountManager.invalidateAuthToken(AccountUtil.accountType(), api.getAuthCookie());
254+
accountManager.invalidateAuthToken(AccountUtil.accountType(), getMWApi().getAuthCookie());
207255
try {
208256
String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false);
209-
api.setAuthCookie(authCookie);
257+
getMWApi().setAuthCookie(authCookie);
210258
return true;
211-
} catch (OperationCanceledException e) {
212-
e.printStackTrace();
213-
return false;
214-
} catch (AuthenticatorException e) {
215-
e.printStackTrace();
216-
return false;
217-
} catch (IOException e) {
218-
e.printStackTrace();
219-
return false;
220-
} catch (NullPointerException e) {
259+
} catch (OperationCanceledException | NullPointerException | IOException | AuthenticatorException e) {
221260
e.printStackTrace();
222261
return false;
223262
}
@@ -248,7 +287,7 @@ public void clearApplicationData(Context context) {
248287
}
249288

250289
//TODO: fix preference manager
251-
PreferenceManager.getDefaultSharedPreferences(app).edit().clear().commit();
290+
PreferenceManager.getDefaultSharedPreferences(getInstance()).edit().clear().commit();
252291
SharedPreferences preferences = context
253292
.getSharedPreferences("fr.free.nrw.commons", MODE_PRIVATE);
254293
preferences.edit().clear().commit();
@@ -263,7 +302,7 @@ public void clearApplicationData(Context context) {
263302
* @param context context
264303
*/
265304
public void updateAllDatabases(Context context) {
266-
DBOpenHelper dbOpenHelper = DBOpenHelper.getInstance(context);
305+
DBOpenHelper dbOpenHelper = CommonsApplication.getInstance().getDBOpenHelper();
267306
dbOpenHelper.getReadableDatabase().close();
268307
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
269308

app/src/main/java/fr/free/nrw/commons/EventLog.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import android.preference.PreferenceManager;
77

88
import org.apache.http.HttpResponse;
9+
import org.apache.http.impl.client.AbstractHttpClient;
910
import org.json.JSONException;
1011
import org.json.JSONObject;
1112

@@ -30,10 +31,10 @@ protected Boolean doInBackground(LogBuilder... logBuilders) {
3031
boolean allSuccess = true;
3132
// Not using the default URL connection, since that seems to have different behavior than the rest of the code
3233
for(LogBuilder logBuilder: logBuilders) {
33-
HttpURLConnection conn;
3434
try {
3535
URL url = logBuilder.toUrl();
36-
HttpResponse response = Http.get(url.toString()).use(CommonsApplication.createHttpClient()).asResponse();
36+
AbstractHttpClient httpClient = CommonsApplication.getInstance().getHttpClient();
37+
HttpResponse response = Http.get(url.toString()).use(httpClient).asResponse();
3738

3839
if(response.getStatusLine().getStatusCode() != 204) {
3940
allSuccess = false;

app/src/main/java/fr/free/nrw/commons/MediaDataExtractor.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public void fetch() throws IOException {
6666
throw new IllegalStateException("Tried to call MediaDataExtractor.fetch() again.");
6767
}
6868

69-
MWApi api = CommonsApplication.createMWApi();
69+
MWApi api = CommonsApplication.getInstance().getMWApi();
7070
ApiResult result = api.action("query")
7171
.param("prop", "revisions")
7272
.param("titles", filename)

app/src/main/java/fr/free/nrw/commons/auth/AccountUtil.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ private static AccountManager accountManager() {
5555

5656
@NonNull
5757
private static CommonsApplication app() {
58-
return CommonsApplication.app;
58+
return CommonsApplication.getInstance();
5959
}
6060

6161
}

app/src/main/java/fr/free/nrw/commons/auth/AuthenticatedActivity.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ protected void requestAuthToken() {
132132
@Override
133133
protected void onCreate(Bundle savedInstanceState) {
134134
super.onCreate(savedInstanceState);
135-
app = (CommonsApplication)this.getApplicationContext();
135+
app = CommonsApplication.getInstance();
136136
if(savedInstanceState != null) {
137137
authCookie = savedInstanceState.getString("authCookie");
138138
}

app/src/main/java/fr/free/nrw/commons/auth/LoginActivity.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
4040
public void onCreate(Bundle savedInstanceState) {
4141
super.onCreate(savedInstanceState);
4242

43-
app = (CommonsApplication) getApplicationContext();
43+
app = CommonsApplication.getInstance();
4444

4545
setContentView(R.layout.activity_login);
4646
final LoginActivity that = this;
@@ -199,7 +199,7 @@ public void showUserToastAndCancelDialog( int resId ) {
199199
}
200200

201201
private void showUserToast( int resId ) {
202-
Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_LONG).show();
202+
Toast.makeText(this, resId, Toast.LENGTH_LONG).show();
203203
}
204204

205205
public void showSuccessToastAndDismissDialog() {

app/src/main/java/fr/free/nrw/commons/auth/LoginTask.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public LoginTask(LoginActivity loginActivity, String username, String password,
2626
this.username = username;
2727
this.password = password;
2828
this.twoFactorCode = twoFactorCode;
29-
app = (CommonsApplication) loginActivity.getApplicationContext();
29+
app = CommonsApplication.getInstance();
3030
}
3131

3232
@Override
@@ -44,9 +44,9 @@ protected void onPreExecute() {
4444
protected String doInBackground(String... params) {
4545
try {
4646
if (twoFactorCode.isEmpty()) {
47-
return app.getApi().login(username, password);
47+
return app.getMWApi().login(username, password);
4848
} else {
49-
return app.getApi().login(username, password, twoFactorCode);
49+
return app.getMWApi().login(username, password, twoFactorCode);
5050
}
5151
} catch (IOException e) {
5252
// Do something better!

app/src/main/java/fr/free/nrw/commons/auth/SignupActivity.java

+7-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import android.webkit.WebViewClient;
88
import android.widget.Toast;
99

10+
import fr.free.nrw.commons.CommonsApplication;
1011
import fr.free.nrw.commons.theme.BaseActivity;
1112
import timber.log.Timber;
1213

@@ -39,10 +40,14 @@ public boolean shouldOverrideUrlLoading(WebView view, String url) {
3940
//Signup success, so clear cookies, notify user, and load LoginActivity again
4041
Timber.d("Overriding URL %s", url);
4142

42-
Toast toast = Toast.makeText(getApplicationContext(), "Account created!", Toast.LENGTH_LONG);
43+
Toast toast = Toast.makeText(
44+
CommonsApplication.getInstance(),
45+
"Account created!",
46+
Toast.LENGTH_LONG
47+
);
4348
toast.show();
4449

45-
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
50+
Intent intent = new Intent(CommonsApplication.getInstance(), LoginActivity.class);
4651
startActivity(intent);
4752
return true;
4853
} else {

app/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticator.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public Bundle editProperties(AccountAuthenticatorResponse response, String accou
7575
}
7676

7777
private String getAuthCookie(String username, String password) throws IOException {
78-
MWApi api = CommonsApplication.createMWApi();
78+
MWApi api = CommonsApplication.getInstance().getMWApi();
7979
//TODO add 2fa support here
8080
String result = api.login(username, password);
8181
if(result.equals("PASS")) {

app/src/main/java/fr/free/nrw/commons/category/CategoryContentProvider.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import android.net.Uri;
1010
import android.text.TextUtils;
1111

12+
import fr.free.nrw.commons.CommonsApplication;
1213
import fr.free.nrw.commons.data.DBOpenHelper;
1314
import timber.log.Timber;
1415

@@ -36,7 +37,7 @@ public static Uri uriForId(int id) {
3637
private DBOpenHelper dbOpenHelper;
3738
@Override
3839
public boolean onCreate() {
39-
dbOpenHelper = DBOpenHelper.getInstance(getContext());
40+
dbOpenHelper = CommonsApplication.getInstance().getDBOpenHelper();
4041
return false;
4142
}
4243

app/src/main/java/fr/free/nrw/commons/category/MethodAUpdater.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ private ArrayList<String> filterYears(ArrayList<String> items) {
7979
protected ArrayList<String> doInBackground(Void... voids) {
8080

8181
//otherwise if user has typed something in that isn't in cache, search API for matching categories
82-
MWApi api = CommonsApplication.createMWApi();
82+
MWApi api = CommonsApplication.getInstance().getMWApi();
8383
ApiResult result;
8484
ArrayList<String> categories = new ArrayList<>();
8585

app/src/main/java/fr/free/nrw/commons/category/PrefixUpdater.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ protected ArrayList<String> doInBackground(Void... voids) {
9595

9696
//otherwise if user has typed something in that isn't in cache, search API for matching categories
9797
//URL: https://commons.wikimedia.org/w/api.php?action=query&list=allcategories&acprefix=filter&aclimit=25
98-
MWApi api = CommonsApplication.createMWApi();
98+
MWApi api = CommonsApplication.getInstance().getMWApi();
9999
ApiResult result;
100100
ArrayList<String> categories = new ArrayList<>();
101101
try {

app/src/main/java/fr/free/nrw/commons/category/TitleCategories.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ protected void onPreExecute() {
3434
@Override
3535
protected ArrayList<String> doInBackground(Void... voids) {
3636

37-
MWApi api = CommonsApplication.createMWApi();
37+
MWApi api = CommonsApplication.getInstance().getMWApi();
3838
ApiResult result;
3939
ArrayList<String> items = new ArrayList<>();
4040

app/src/main/java/fr/free/nrw/commons/contributions/ContributionsActivity.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ protected void onPause() {
109109
@Override
110110
protected void onAuthCookieAcquired(String authCookie) {
111111
// Do a sync everytime we get here!
112-
ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ContributionsContentProvider.AUTHORITY, new Bundle());
112+
ContentResolver.requestSync(CommonsApplication.getInstance().getCurrentAccount(), ContributionsContentProvider.AUTHORITY, new Bundle());
113113
Intent uploadServiceIntent = new Intent(this, UploadService.class);
114114
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
115115
startService(uploadServiceIntent);
@@ -219,7 +219,7 @@ public boolean onCreateOptionsMenu(Menu menu) {
219219
@Override
220220
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
221221
SharedPreferences sharedPref =
222-
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
222+
PreferenceManager.getDefaultSharedPreferences(this);
223223
int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100);
224224
return new CursorLoader(this, ContributionsContentProvider.BASE_URI,
225225
Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null,

0 commit comments

Comments
 (0)