Cleanup CommonsApplication Singelton

This commit is contained in:
addshore 2017-05-16 10:39:05 +02:00
parent 45a19620b9
commit bdfbdc7579
29 changed files with 116 additions and 83 deletions

View file

@ -62,7 +62,6 @@ import timber.log.Timber;
) )
public class CommonsApplication extends Application { public class CommonsApplication extends Application {
private MWApi api;
private Account currentAccount = null; // Unlike a savings account... private Account currentAccount = null; // Unlike a savings account...
public static final String API_URL = "https://commons.wikimedia.org/w/api.php"; public static final String API_URL = "https://commons.wikimedia.org/w/api.php";
public static final String IMAGE_URL_BASE = "https://upload.wikimedia.org/wikipedia/commons"; public static final String IMAGE_URL_BASE = "https://upload.wikimedia.org/wikipedia/commons";
@ -81,13 +80,35 @@ public class CommonsApplication extends Application {
public static final String FEEDBACK_EMAIL = "commons-app-android@googlegroups.com"; public static final String FEEDBACK_EMAIL = "commons-app-android@googlegroups.com";
public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App (%s) Feedback"; public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App (%s) Feedback";
public RequestQueue volleyQueue; private static CommonsApplication instance = null;
private AbstractHttpClient httpClient = null;
private MWApi api = null;
private CacheController cacheData = null;
private RequestQueue volleyQueue = null;
public CacheController cacheData; /**
* This should not be called by ANY application code (other than the magic Android glue)
* Use CommonsApplication.getInstance() instead to get the singleton.
*/
public CommonsApplication() {
CommonsApplication.instance = this;
}
public static CommonsApplication app; public static CommonsApplication getInstance() {
if(instance == null) {
instance = new CommonsApplication();
}
return instance;
}
public static AbstractHttpClient createHttpClient() { public AbstractHttpClient getHttpClient() {
if(httpClient == null) {
httpClient = newHttpClient();
}
return httpClient;
}
private AbstractHttpClient newHttpClient() {
BasicHttpParams params = new BasicHttpParams(); BasicHttpParams params = new BasicHttpParams();
SchemeRegistry schemeRegistry = new SchemeRegistry(); SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
@ -98,14 +119,36 @@ public class CommonsApplication extends Application {
return new DefaultHttpClient(cm, params); return new DefaultHttpClient(cm, params);
} }
public static MWApi createMWApi() { public MWApi getMWApi() {
return new MWApi(API_URL, createHttpClient()); if(api == null) {
api = newMWApi();
}
return api;
}
private MWApi newMWApi() {
return new MWApi(API_URL, getHttpClient());
}
public CacheController getCacheData() {
if(cacheData == null) {
cacheData = new CacheController();
}
return cacheData;
}
public RequestQueue getVolleyQueue() {
if(volleyQueue == null) {
DiskBasedCache cache = new DiskBasedCache(getCacheDir(), 16 * 1024 * 1024);
volleyQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
volleyQueue.start();
}
return volleyQueue;
} }
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
app = this;
Timber.plant(new Timber.DebugTree()); Timber.plant(new Timber.DebugTree());
@ -116,9 +159,8 @@ public class CommonsApplication extends Application {
} }
// Fire progress callbacks for every 3% of uploaded content // Fire progress callbacks for every 3% of uploaded content
System.setProperty("in.yuvi.http.fluent.PROGRESS_TRIGGER_THRESHOLD", "3.0"); System.setProperty("in.yuvi.http.fluent.PROGRESS_TRIGGER_THRESHOLD", "3.0");
api = createMWApi();
ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(getApplicationContext()) ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this)
.discCache(new TotalSizeLimitedDiscCache(StorageUtils.getCacheDirectory(this), 128 * 1024 * 1024)) .discCache(new TotalSizeLimitedDiscCache(StorageUtils.getCacheDirectory(this), 128 * 1024 * 1024))
.build(); .build();
ImageLoader.getInstance().init(imageLoaderConfiguration); ImageLoader.getInstance().init(imageLoaderConfiguration);
@ -147,13 +189,6 @@ public class CommonsApplication extends Application {
} }
}; };
} }
//For caching area -> categories
cacheData = new CacheController();
DiskBasedCache cache = new DiskBasedCache(getCacheDir(), 16 * 1024 * 1024);
volleyQueue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
volleyQueue.start();
} }
private com.android.volley.toolbox.ImageLoader imageLoader; private com.android.volley.toolbox.ImageLoader imageLoader;
@ -161,7 +196,7 @@ public class CommonsApplication extends Application {
public com.android.volley.toolbox.ImageLoader getImageLoader() { public com.android.volley.toolbox.ImageLoader getImageLoader() {
if(imageLoader == null) { if(imageLoader == null) {
imageLoader = new com.android.volley.toolbox.ImageLoader(volleyQueue, new com.android.volley.toolbox.ImageLoader.ImageCache() { imageLoader = new com.android.volley.toolbox.ImageLoader(getVolleyQueue(), new com.android.volley.toolbox.ImageLoader.ImageCache() {
@Override @Override
public Bitmap getBitmap(String key) { public Bitmap getBitmap(String key) {
return imageCache.get(key); return imageCache.get(key);
@ -176,13 +211,9 @@ public class CommonsApplication extends Application {
} }
return imageLoader; return imageLoader;
} }
public MWApi getApi() {
return api;
}
/** /**
* @return Accout|null * @return Account|null
*/ */
public Account getCurrentAccount() { public Account getCurrentAccount() {
if(currentAccount == null) { if(currentAccount == null) {
@ -203,21 +234,12 @@ public class CommonsApplication extends Application {
return false; // This should never happen return false; // This should never happen
} }
accountManager.invalidateAuthToken(AccountUtil.accountType(), api.getAuthCookie()); accountManager.invalidateAuthToken(AccountUtil.accountType(), getMWApi().getAuthCookie());
try { try {
String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false); String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false);
api.setAuthCookie(authCookie); getMWApi().setAuthCookie(authCookie);
return true; return true;
} catch (OperationCanceledException e) { } catch (OperationCanceledException | NullPointerException | IOException | AuthenticatorException e) {
e.printStackTrace();
return false;
} catch (AuthenticatorException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }

View file

@ -6,6 +6,7 @@ import android.os.Build;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.impl.client.AbstractHttpClient;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -30,10 +31,10 @@ public class EventLog {
boolean allSuccess = true; boolean allSuccess = true;
// Not using the default URL connection, since that seems to have different behavior than the rest of the code // Not using the default URL connection, since that seems to have different behavior than the rest of the code
for(LogBuilder logBuilder: logBuilders) { for(LogBuilder logBuilder: logBuilders) {
HttpURLConnection conn;
try { try {
URL url = logBuilder.toUrl(); URL url = logBuilder.toUrl();
HttpResponse response = Http.get(url.toString()).use(CommonsApplication.createHttpClient()).asResponse(); AbstractHttpClient httpClient = CommonsApplication.getInstance().getHttpClient();
HttpResponse response = Http.get(url.toString()).use(httpClient).asResponse();
if(response.getStatusLine().getStatusCode() != 204) { if(response.getStatusLine().getStatusCode() != 204) {
allSuccess = false; allSuccess = false;

View file

@ -66,7 +66,7 @@ public class MediaDataExtractor {
throw new IllegalStateException("Tried to call MediaDataExtractor.fetch() again."); throw new IllegalStateException("Tried to call MediaDataExtractor.fetch() again.");
} }
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
ApiResult result = api.action("query") ApiResult result = api.action("query")
.param("prop", "revisions") .param("prop", "revisions")
.param("titles", filename) .param("titles", filename)

View file

@ -55,7 +55,7 @@ public class AccountUtil {
@NonNull @NonNull
private static CommonsApplication app() { private static CommonsApplication app() {
return CommonsApplication.app; return CommonsApplication.getInstance();
} }
} }

View file

@ -132,7 +132,7 @@ public abstract class AuthenticatedActivity extends NavigationBaseActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
app = (CommonsApplication)this.getApplicationContext(); app = CommonsApplication.getInstance();
if(savedInstanceState != null) { if(savedInstanceState != null) {
authCookie = savedInstanceState.getString("authCookie"); authCookie = savedInstanceState.getString("authCookie");
} }

View file

@ -40,7 +40,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
app = (CommonsApplication) getApplicationContext(); app = CommonsApplication.getInstance();
setContentView(R.layout.activity_login); setContentView(R.layout.activity_login);
final LoginActivity that = this; final LoginActivity that = this;
@ -199,7 +199,7 @@ public class LoginActivity extends AccountAuthenticatorActivity {
} }
private void showUserToast( int resId ) { private void showUserToast( int resId ) {
Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_LONG).show(); Toast.makeText(this, resId, Toast.LENGTH_LONG).show();
} }
public void showSuccessToastAndDismissDialog() { public void showSuccessToastAndDismissDialog() {

View file

@ -26,7 +26,7 @@ class LoginTask extends AsyncTask<String, String, String> {
this.username = username; this.username = username;
this.password = password; this.password = password;
this.twoFactorCode = twoFactorCode; this.twoFactorCode = twoFactorCode;
app = (CommonsApplication) loginActivity.getApplicationContext(); app = CommonsApplication.getInstance();
} }
@Override @Override
@ -44,9 +44,9 @@ class LoginTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) { protected String doInBackground(String... params) {
try { try {
if (twoFactorCode.isEmpty()) { if (twoFactorCode.isEmpty()) {
return app.getApi().login(username, password); return app.getMWApi().login(username, password);
} else { } else {
return app.getApi().login(username, password, twoFactorCode); return app.getMWApi().login(username, password, twoFactorCode);
} }
} catch (IOException e) { } catch (IOException e) {
// Do something better! // Do something better!

View file

@ -7,6 +7,7 @@ import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
import android.widget.Toast; import android.widget.Toast;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.theme.BaseActivity; import fr.free.nrw.commons.theme.BaseActivity;
import timber.log.Timber; import timber.log.Timber;
@ -39,10 +40,10 @@ public class SignupActivity extends BaseActivity {
//Signup success, so clear cookies, notify user, and load LoginActivity again //Signup success, so clear cookies, notify user, and load LoginActivity again
Timber.d("Overriding URL %s", url); Timber.d("Overriding URL %s", url);
Toast toast = Toast.makeText(getApplicationContext(), "Account created!", Toast.LENGTH_LONG); Toast toast = Toast.makeText(CommonsApplication.getInstance(), "Account created!", Toast.LENGTH_LONG);
toast.show(); toast.show();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class); Intent intent = new Intent(CommonsApplication.getInstance(), LoginActivity.class);
startActivity(intent); startActivity(intent);
return true; return true;
} else { } else {

View file

@ -75,7 +75,7 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator {
} }
private String getAuthCookie(String username, String password) throws IOException { private String getAuthCookie(String username, String password) throws IOException {
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
//TODO add 2fa support here //TODO add 2fa support here
String result = api.login(username, password); String result = api.login(username, password);
if(result.equals("PASS")) { if(result.equals("PASS")) {

View file

@ -79,7 +79,7 @@ public class MethodAUpdater extends AsyncTask<Void, Void, ArrayList<String>> {
protected ArrayList<String> doInBackground(Void... voids) { protected ArrayList<String> doInBackground(Void... voids) {
//otherwise if user has typed something in that isn't in cache, search API for matching categories //otherwise if user has typed something in that isn't in cache, search API for matching categories
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
ApiResult result; ApiResult result;
ArrayList<String> categories = new ArrayList<>(); ArrayList<String> categories = new ArrayList<>();

View file

@ -95,7 +95,7 @@ public class PrefixUpdater extends AsyncTask<Void, Void, ArrayList<String>> {
//otherwise if user has typed something in that isn't in cache, search API for matching categories //otherwise if user has typed something in that isn't in cache, search API for matching categories
//URL: https://commons.wikimedia.org/w/api.php?action=query&list=allcategories&acprefix=filter&aclimit=25 //URL: https://commons.wikimedia.org/w/api.php?action=query&list=allcategories&acprefix=filter&aclimit=25
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
ApiResult result; ApiResult result;
ArrayList<String> categories = new ArrayList<>(); ArrayList<String> categories = new ArrayList<>();
try { try {

View file

@ -34,7 +34,7 @@ public class TitleCategories extends AsyncTask<Void, Void, ArrayList<String>> {
@Override @Override
protected ArrayList<String> doInBackground(Void... voids) { protected ArrayList<String> doInBackground(Void... voids) {
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
ApiResult result; ApiResult result;
ArrayList<String> items = new ArrayList<>(); ArrayList<String> items = new ArrayList<>();

View file

@ -109,7 +109,7 @@ public class ContributionsActivity
@Override @Override
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
// Do a sync everytime we get here! // Do a sync everytime we get here!
ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ContributionsContentProvider.AUTHORITY, new Bundle()); ContentResolver.requestSync(CommonsApplication.getInstance().getCurrentAccount(), ContributionsContentProvider.AUTHORITY, new Bundle());
Intent uploadServiceIntent = new Intent(this, UploadService.class); Intent uploadServiceIntent = new Intent(this, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE); uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
startService(uploadServiceIntent); startService(uploadServiceIntent);
@ -219,7 +219,7 @@ public class ContributionsActivity
@Override @Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPref = SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); PreferenceManager.getDefaultSharedPreferences(this);
int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100); int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100);
return new CursorLoader(this, ContributionsContentProvider.BASE_URI, return new CursorLoader(this, ContributionsContentProvider.BASE_URI,
Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null, Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null,

View file

@ -49,7 +49,7 @@ class ContributionsListAdapter extends CursorAdapter {
if(views.url == null || !views.url.equals(actualUrl)) { if(views.url == null || !views.url.equals(actualUrl)) {
if(actualUrl.startsWith("http")) { if(actualUrl.startsWith("http")) {
MediaWikiImageView mwImageView = views.imageView; MediaWikiImageView mwImageView = views.imageView;
mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); mwImageView.setMedia(contribution, CommonsApplication.getInstance().getImageLoader());
// FIXME: For transparent images // FIXME: For transparent images
} else { } else {
ImageLoader.getInstance().displayImage(actualUrl, views.imageView, contributionDisplayOptions, new SimpleImageLoadingListener() { ImageLoader.getInstance().displayImage(actualUrl, views.imageView, contributionDisplayOptions, new SimpleImageLoadingListener() {
@ -66,7 +66,7 @@ class ContributionsListAdapter extends CursorAdapter {
public void onLoadingFailed(String imageUri, View view, FailReason failReason) { public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason); super.onLoadingFailed(imageUri, view, failReason);
MediaWikiImageView mwImageView = views.imageView; MediaWikiImageView mwImageView = views.imageView;
mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); mwImageView.setMedia(contribution, CommonsApplication.getInstance().getImageLoader());
} }
}); });
} }

View file

@ -159,8 +159,7 @@ public class ContributionsListFragment extends Fragment {
menu.clear(); // See http://stackoverflow.com/a/8495697/17865 menu.clear(); // See http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_contributions_list, menu); inflater.inflate(R.menu.fragment_contributions_list, menu);
CommonsApplication app = (CommonsApplication)getActivity().getApplicationContext(); if (!CommonsApplication.getInstance().deviceHasCamera()) {
if (!app.deviceHasCamera()) {
menu.findItem(R.id.menu_from_camera).setEnabled(false); menu.findItem(R.id.menu_from_camera).setEnabled(false);
} }
} }

View file

@ -61,7 +61,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) { public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
// This code is fraught with possibilities of race conditions, but lalalalala I can't hear you! // This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
String user = account.name; String user = account.name;
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
SharedPreferences prefs = this.getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE); SharedPreferences prefs = this.getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
String lastModified = prefs.getString("lastSyncTimestamp", ""); String lastModified = prefs.getString("lastSyncTimestamp", "");
Date curTime = new Date(); Date curTime = new Date();

View file

@ -15,7 +15,7 @@ public class ContributionsSyncService extends Service {
super.onCreate(); super.onCreate();
synchronized (sSyncAdapterLock) { synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) { if (sSyncAdapter == null) {
sSyncAdapter = new ContributionsSyncAdapter(getApplicationContext(), true); sSyncAdapter = new ContributionsSyncAdapter(this, true);
} }
} }
} }

View file

@ -194,7 +194,7 @@ public class MediaDetailFragment extends Fragment {
if(actualUrl.startsWith("http")) { if(actualUrl.startsWith("http")) {
Timber.d("Actual URL starts with http and is: %s", actualUrl); Timber.d("Actual URL starts with http and is: %s", actualUrl);
ImageLoader loader = ((CommonsApplication)getActivity().getApplicationContext()).getImageLoader(); ImageLoader loader = CommonsApplication.getInstance().getImageLoader();
MediaWikiImageView mwImage = (MediaWikiImageView)image; MediaWikiImageView mwImage = (MediaWikiImageView)image;
mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute
mwImage.setMedia(media, loader); mwImage.setMedia(media, loader);

View file

@ -123,7 +123,7 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
if(savedInstanceState != null) { if(savedInstanceState != null) {
editable = savedInstanceState.getBoolean("editable"); editable = savedInstanceState.getBoolean("editable");
} }
app = (CommonsApplication)getActivity().getApplicationContext(); app = CommonsApplication.getInstance();
setHasOptionsMenu(true); setHasOptionsMenu(true);
} }

View file

@ -61,7 +61,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter {
return; return;
} }
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
api.setAuthCookie(authCookie); api.setAuthCookie(authCookie);
String editToken; String editToken;

View file

@ -15,7 +15,7 @@ public class ModificationsSyncService extends Service {
super.onCreate(); super.onCreate();
synchronized (sSyncAdapterLock) { synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) { if (sSyncAdapter == null) {
sSyncAdapter = new ModificationsSyncAdapter(getApplicationContext(), true); sSyncAdapter = new ModificationsSyncAdapter(this, true);
} }
} }
} }

View file

@ -25,6 +25,7 @@ import java.util.List;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager; import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.theme.NavigationBaseActivity; import fr.free.nrw.commons.theme.NavigationBaseActivity;
@ -184,7 +185,7 @@ public class NearbyActivity extends NavigationBaseActivity {
@Override @Override
protected List<Place> doInBackground(Void... params) { protected List<Place> doInBackground(Void... params) {
return NearbyController return NearbyController
.loadAttractionsFromLocation(curLatLang, getApplicationContext() .loadAttractionsFromLocation(curLatLang, CommonsApplication.getInstance()
); );
} }

View file

@ -11,6 +11,7 @@ import android.preference.Preference;
import android.preference.PreferenceFragment; import android.preference.PreferenceFragment;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.Utils;
@ -46,7 +47,7 @@ public class SettingsFragment extends PreferenceFragment {
final EditTextPreference uploadLimit = (EditTextPreference) findPreference("uploads"); final EditTextPreference uploadLimit = (EditTextPreference) findPreference("uploads");
final SharedPreferences sharedPref = PreferenceManager final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(getActivity().getApplicationContext()); .getDefaultSharedPreferences(CommonsApplication.getInstance());
int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100); int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100);
uploadLimit.setText(uploads + ""); uploadLimit.setText(uploads + "");
uploadLimit.setSummary(uploads + ""); uploadLimit.setSummary(uploads + "");

View file

@ -38,7 +38,7 @@ public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
@Override @Override
protected Boolean doInBackground(Void... voids) { protected Boolean doInBackground(Void... voids) {
MWApi api = CommonsApplication.createMWApi(); MWApi api = CommonsApplication.getInstance().getMWApi();
ApiResult result; ApiResult result;
// https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=xml&aisha1=801957214aba50cb63bb6eb1b0effa50188900ba // https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=xml&aisha1=801957214aba50cb63bb6eb1b0effa50188900ba

View file

@ -132,7 +132,11 @@ public class MultipleShareActivity
dialog.setProgress(uploadCount); dialog.setProgress(uploadCount);
if(uploadCount == photosList.size()) { if(uploadCount == photosList.size()) {
dialog.dismiss(); dialog.dismiss();
Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG); Toast startingToast = Toast.makeText(
CommonsApplication.getInstance(),
R.string.uploading_started,
Toast.LENGTH_LONG
);
startingToast.show(); startingToast.show();
} }
} }
@ -202,9 +206,9 @@ public class MultipleShareActivity
uploadController = new UploadController(this); uploadController = new UploadController(this);
setContentView(R.layout.activity_multiple_uploads); setContentView(R.layout.activity_multiple_uploads);
app = CommonsApplication.getInstance();
ButterKnife.bind(this); ButterKnife.bind(this);
initDrawer(); initDrawer();
app = (CommonsApplication)this.getApplicationContext();
if(savedInstanceState != null) { if(savedInstanceState != null) {
photosList = savedInstanceState.getParcelableArrayList("uploadsList"); photosList = savedInstanceState.getParcelableArrayList("uploadsList");
@ -241,7 +245,7 @@ public class MultipleShareActivity
@Override @Override
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
app.getApi().setAuthCookie(authCookie); app.getMWApi().setAuthCookie(authCookie);
Intent intent = getIntent(); Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {

View file

@ -101,7 +101,7 @@ public class MwVolleyApi {
private static RequestQueue getQueue(Context context) { private static RequestQueue getQueue(Context context) {
if (REQUEST_QUEUE == null) { if (REQUEST_QUEUE == null) {
REQUEST_QUEUE = Volley.newRequestQueue(context.getApplicationContext()); REQUEST_QUEUE = Volley.newRequestQueue(context);
} }
return REQUEST_QUEUE; return REQUEST_QUEUE;
} }

View file

@ -106,12 +106,16 @@ public class ShareActivity
getFileMetadata(false); getFileMetadata(false);
} }
Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG); Toast startingToast = Toast.makeText(
CommonsApplication.getInstance(),
R.string.uploading_started,
Toast.LENGTH_LONG
);
startingToast.show(); startingToast.show();
if (!cacheFound) { if (!cacheFound) {
//Has to be called after apiCall.request() //Has to be called after apiCall.request()
app.cacheData.cacheCategory(); app.getCacheData().cacheCategory();
Timber.d("Cache the categories found"); Timber.d("Cache the categories found");
} }
@ -189,7 +193,7 @@ public class ShareActivity
@Override @Override
protected void onAuthCookieAcquired(String authCookie) { protected void onAuthCookieAcquired(String authCookie) {
app.getApi().setAuthCookie(authCookie); app.getMWApi().setAuthCookie(authCookie);
shareView = (SingleUploadFragment) getSupportFragmentManager().findFragmentByTag("shareView"); shareView = (SingleUploadFragment) getSupportFragmentManager().findFragmentByTag("shareView");
categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization"); categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization");
@ -217,7 +221,7 @@ public class ShareActivity
setContentView(R.layout.activity_share); setContentView(R.layout.activity_share);
ButterKnife.bind(this); ButterKnife.bind(this);
initDrawer(); initDrawer();
app = (CommonsApplication)this.getApplicationContext(); app = CommonsApplication.getInstance();
backgroundImageView = (ImageView)findViewById(R.id.backgroundImage); backgroundImageView = (ImageView)findViewById(R.id.backgroundImage);
//Receive intent from ContributionController.java when user selects picture to upload //Receive intent from ContributionController.java when user selects picture to upload
@ -398,12 +402,12 @@ public class ShareActivity
if (imageObj.imageCoordsExists) { if (imageObj.imageCoordsExists) {
double decLongitude = imageObj.getDecLongitude(); double decLongitude = imageObj.getDecLongitude();
double decLatitude = imageObj.getDecLatitude(); double decLatitude = imageObj.getDecLatitude();
app.cacheData.setQtPoint(decLongitude, decLatitude); app.getCacheData().setQtPoint(decLongitude, decLatitude);
} }
MwVolleyApi apiCall = new MwVolleyApi(this); MwVolleyApi apiCall = new MwVolleyApi(this);
List<String> displayCatList = app.cacheData.findCategory(); List<String> displayCatList = app.getCacheData().findCategory();
boolean catListEmpty = displayCatList.isEmpty(); boolean catListEmpty = displayCatList.isEmpty();
// If no categories found in cache, call MediaWiki API to match image coords with nearby Commons categories // If no categories found in cache, call MediaWiki API to match image coords with nearby Commons categories

View file

@ -36,7 +36,7 @@ public class UploadController {
public UploadController(Activity activity) { public UploadController(Activity activity) {
this.activity = activity; this.activity = activity;
app = (CommonsApplication)activity.getApplicationContext(); app = CommonsApplication.getInstance();
} }
private boolean isUploadServiceConnected; private boolean isUploadServiceConnected;
@ -55,7 +55,7 @@ public class UploadController {
}; };
public void prepareService() { public void prepareService() {
Intent uploadServiceIntent = new Intent(activity.getApplicationContext(), UploadService.class); Intent uploadServiceIntent = new Intent(activity, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE); uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
activity.startService(uploadServiceIntent); activity.startService(uploadServiceIntent);
activity.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE); activity.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);

View file

@ -115,7 +115,7 @@ public class UploadService extends HandlerService<Contribution> {
super.onCreate(); super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
app = (CommonsApplication) this.getApplicationContext(); app = CommonsApplication.getInstance();
contributionsProviderClient = this.getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY); contributionsProviderClient = this.getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
} }
@ -176,7 +176,7 @@ public class UploadService extends HandlerService<Contribution> {
} }
private void uploadContribution(Contribution contribution) { private void uploadContribution(Contribution contribution) {
MWApi api = app.getApi(); MWApi api = app.getMWApi();
ApiResult result; ApiResult result;
InputStream file = null; InputStream file = null;
@ -201,7 +201,7 @@ public class UploadService extends HandlerService<Contribution> {
.setContentText(getResources().getQuantityString(R.plurals.uploads_pending_notification_indicator, toUpload, toUpload)) .setContentText(getResources().getQuantityString(R.plurals.uploads_pending_notification_indicator, toUpload, toUpload))
.setOngoing(true) .setOngoing(true)
.setProgress(100, 0, true) .setProgress(100, 0, true)
.setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, new Intent(this, ContributionsActivity.class), 0)) .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ContributionsActivity.class), 0))
.setTicker(getString(R.string.upload_progress_notification_title_in_progress, contribution.getDisplayTitle())); .setTicker(getString(R.string.upload_progress_notification_title_in_progress, contribution.getDisplayTitle()));
this.startForeground(NOTIFICATION_UPLOAD_IN_PROGRESS, curProgressNotification.build()); this.startForeground(NOTIFICATION_UPLOAD_IN_PROGRESS, curProgressNotification.build());
@ -282,7 +282,7 @@ public class UploadService extends HandlerService<Contribution> {
toUpload--; toUpload--;
if(toUpload == 0) { if(toUpload == 0) {
// Sync modifications right after all uplaods are processed // Sync modifications right after all uplaods are processed
ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle()); ContentResolver.requestSync((CommonsApplication.getInstance()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
stopForeground(true); stopForeground(true);
} }
} }
@ -304,7 +304,7 @@ public class UploadService extends HandlerService<Contribution> {
} }
private String findUniqueFilename(String fileName) throws IOException { private String findUniqueFilename(String fileName) throws IOException {
MWApi api = app.getApi(); MWApi api = app.getMWApi();
String sequenceFileName; String sequenceFileName;
for ( int sequenceNumber = 1; true; sequenceNumber++ ) { for ( int sequenceNumber = 1; true; sequenceNumber++ ) {
if (sequenceNumber == 1) { if (sequenceNumber == 1) {