Finished removing coupling between classes around the getInstance() method.

This commit is contained in:
Paul Hawke 2017-08-25 21:40:50 -05:00 committed by Paul Hawke
parent dbcbeed822
commit ed1ae98d8e
18 changed files with 154 additions and 125 deletions

View file

@ -79,7 +79,6 @@ public class CommonsApplication extends DaggerApplication {
public static final String FEEDBACK_EMAIL = "commons-app-android@googlegroups.com";
public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App (%s) Feedback";
private static CommonsApplication instance = null;
private MediaWikiApi api = null;
private LruCache<String, String> thumbnailUrlCache = new LruCache<>(1024);
private CacheController cacheData = null;
@ -87,21 +86,6 @@ public class CommonsApplication extends DaggerApplication {
private NearbyPlaces nearbyPlaces = null;
private CommonsApplicationComponent component;
/**
* 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 getInstance() {
if (instance == null) {
instance = new CommonsApplication();
}
return instance;
}
public MediaWikiApi getMWApi() {
if (api == null) {
api = new ApacheHttpClientMediaWikiApi(API_URL);

View file

@ -40,11 +40,12 @@ public class MediaWikiImageView extends SimpleDraweeView {
return;
}
if (CommonsApplication.getInstance().getThumbnailUrlCache().get(media.getFilename()) != null) {
setImageUrl(CommonsApplication.getInstance().getThumbnailUrlCache().get(media.getFilename()));
CommonsApplication app = (CommonsApplication) getContext().getApplicationContext();
if (app.getThumbnailUrlCache().get(media.getFilename()) != null) {
setImageUrl(app.getThumbnailUrlCache().get(media.getFilename()));
} else {
setImageUrl(null);
MediaWikiApi mediaWikiApi = CommonsApplication.getInstance().getMWApi();
MediaWikiApi mediaWikiApi = app.getMWApi();
currentThumbnailTask = new ThumbnailFetchTask(media, mediaWikiApi);
currentThumbnailTask.execute(media.getFilename());
}
@ -87,7 +88,8 @@ public class MediaWikiImageView extends SimpleDraweeView {
} else {
// only cache meaningful thumbnails received from network.
try {
CommonsApplication.getInstance().getThumbnailUrlCache().put(media.getFilename(), result);
CommonsApplication app = (CommonsApplication) getContext().getApplicationContext();
app.getThumbnailUrlCache().put(media.getFilename(), result);
} catch (NullPointerException npe) {
Timber.e("error when adding pic to cache " + npe);

View file

@ -30,8 +30,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.data.Category;
@ -48,7 +51,7 @@ import static fr.free.nrw.commons.category.CategoryContentProvider.AUTHORITY;
/**
* Displays the category suggestion and selection screen. Category search is initiated here.
*/
public class CategorizationFragment extends Fragment {
public class CategorizationFragment extends DaggerFragment {
public static final int SEARCH_CATS_LIMIT = 25;
@ -63,6 +66,8 @@ public class CategorizationFragment extends Fragment {
@BindView(R.id.categoriesExplanation)
TextView categoriesSkip;
@Inject CommonsApplication application;
private RVRendererAdapter<CategoryItem> categoriesAdapter;
private OnCategoriesSaveHandler onCategoriesSaveHandler;
private HashMap<String, ArrayList<String>> categoriesCache;
@ -202,7 +207,7 @@ public class CategorizationFragment extends Fragment {
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
s -> categoriesAdapter.add(s),
throwable -> Timber.e(throwable),
Timber::e,
() -> {
categoriesAdapter.notifyDataSetChanged();
categoriesSearchInProgress.setVisibility(View.GONE);
@ -248,7 +253,7 @@ public class CategorizationFragment extends Fragment {
SharedPreferences titleDesc = PreferenceManager.getDefaultSharedPreferences(getActivity());
String title = titleDesc.getString("Title", "");
return CommonsApplication.getInstance().getMWApi()
return application.getMWApi()
.searchTitles(title, SEARCH_CATS_LIMIT)
.map(name -> new CategoryItem(name, false));
}
@ -271,7 +276,7 @@ public class CategorizationFragment extends Fragment {
}
//otherwise, search API for matching categories
return CommonsApplication.getInstance().getMWApi()
return application.getMWApi()
.allCategories(term, SEARCH_CATS_LIMIT)
.map(name -> new CategoryItem(name, false));
}
@ -282,7 +287,7 @@ public class CategorizationFragment extends Fragment {
return Observable.empty();
}
return CommonsApplication.getInstance().getMWApi()
return application.getMWApi()
.searchCategories(term, SEARCH_CATS_LIMIT)
.map(s -> new CategoryItem(s, false));
}

View file

@ -1,8 +1,6 @@
package fr.free.nrw.commons.contributions;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
@ -23,8 +21,11 @@ import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.nearby.NearbyActivity;
@ -33,7 +34,7 @@ import timber.log.Timber;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.app.Activity.RESULT_OK;
public class ContributionsListFragment extends Fragment {
public class ContributionsListFragment extends DaggerFragment {
public interface SourceRefresher {
void refreshSource();
@ -43,6 +44,8 @@ public class ContributionsListFragment extends Fragment {
@BindView(R.id.waitingMessage) TextView waitingMessage;
@BindView(R.id.emptyMessage) TextView emptyMessage;
@Inject CommonsApplication application;
private ContributionController controller;
@Override
@ -193,7 +196,7 @@ public class ContributionsListFragment extends Fragment {
menu.clear(); // See http://stackoverflow.com/a/8495697/17865
inflater.inflate(R.menu.fragment_contributions_list, menu);
if (!CommonsApplication.getInstance().deviceHasCamera()) {
if (!application.deviceHasCamera()) {
menu.findItem(R.id.menu_from_camera).setEnabled(false);
}
}

View file

@ -10,6 +10,7 @@ import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.auth.WikiAccountAuthenticatorService;
import fr.free.nrw.commons.contributions.ContributionsSyncAdapter;
import fr.free.nrw.commons.modifications.ModificationsSyncAdapter;
import fr.free.nrw.commons.upload.UploadService;
@Singleton
@Component(modules = {
@ -24,6 +25,8 @@ public interface CommonsApplicationComponent extends AndroidInjector<CommonsAppl
void inject(WikiAccountAuthenticatorService service);
void inject(UploadService service);
void inject(ContributionsSyncAdapter syncAdapter);
void inject(ModificationsSyncAdapter syncAdapter);

View file

@ -22,6 +22,9 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.License;
import fr.free.nrw.commons.LicenseList;
@ -34,7 +37,7 @@ import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.ui.widget.CompatTextView;
import timber.log.Timber;
public class MediaDetailFragment extends Fragment {
public class MediaDetailFragment extends DaggerFragment {
private boolean editable;
private MediaDetailPagerFragment.MediaDetailProvider detailProvider;
@ -54,6 +57,8 @@ public class MediaDetailFragment extends Fragment {
return mf;
}
@Inject CommonsApplication application;
private MediaWikiImageView image;
private MediaDetailSpacer spacer;
private int initialListTop = 0;
@ -70,7 +75,7 @@ public class MediaDetailFragment extends Fragment {
private boolean categoriesPresent = false;
private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once!
private ViewTreeObserver.OnScrollChangedListener scrollListener;
DataSetObserver dataObserver;
private DataSetObserver dataObserver;
private AsyncTask<Void,Void,Boolean> detailFetchTask;
private LicenseList licenseList;
@ -189,7 +194,7 @@ public class MediaDetailFragment extends Fragment {
@Override
protected void onPreExecute() {
extractor = new MediaDataExtractor(media.getFilename(), licenseList, CommonsApplication.getInstance().getMWApi());
extractor = new MediaDataExtractor(media.getFilename(), licenseList, application.getMWApi());
}
@Override

View file

@ -27,6 +27,9 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Media;
import fr.free.nrw.commons.R;
@ -34,7 +37,7 @@ import fr.free.nrw.commons.contributions.Contribution;
import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.mwapi.EventLog;
public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPageChangeListener {
public class MediaDetailPagerFragment extends DaggerFragment implements ViewPager.OnPageChangeListener {
public interface MediaDetailProvider {
Media getMediaAtPosition(int i);
@ -48,9 +51,10 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
void unregisterDataSetObserver(DataSetObserver observer);
}
@Inject CommonsApplication application;
private ViewPager pager;
private Boolean editable;
private CommonsApplication app;
public MediaDetailPagerFragment() {
this(false);
@ -120,7 +124,6 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
if (savedInstanceState != null) {
editable = savedInstanceState.getBoolean("editable");
}
app = CommonsApplication.getInstance();
setHasOptionsMenu(true);
}
@ -131,8 +134,8 @@ public class MediaDetailPagerFragment extends Fragment implements ViewPager.OnPa
switch(item.getItemId()) {
case R.id.menu_share_current_image:
// Share - this is just logs it, intent set in onCreateOptionsMenu, around line 252
EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("filename", m.getFilename())
.log();
return true;

View file

@ -31,7 +31,6 @@ import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.location.LatLng;
@ -95,7 +94,7 @@ public class NearbyActivity extends NavigationBaseActivity {
locationManager = new LocationServiceManager(this);
locationManager.registerLocationManager();
curLatLang = locationManager.getLatestLocation();
nearbyAsyncTask = new NearbyAsyncTask(this, application);
nearbyAsyncTask = new NearbyAsyncTask(this, new NearbyController(application));
nearbyAsyncTask.execute();
}
@ -234,7 +233,7 @@ public class NearbyActivity extends NavigationBaseActivity {
}
private void refreshView() {
nearbyAsyncTask = new NearbyAsyncTask(this, application);
nearbyAsyncTask = new NearbyAsyncTask(this, new NearbyController(application));
nearbyAsyncTask.execute();
}
@ -249,11 +248,11 @@ public class NearbyActivity extends NavigationBaseActivity {
private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> {
private final Context mContext;
private final CommonsApplication application;
private final NearbyController nearbyController;
private NearbyAsyncTask(Context context, CommonsApplication application) {
mContext = context;
this.application = application;
private NearbyAsyncTask(Context context, NearbyController nearbyController) {
this.mContext = context;
this.nearbyController = nearbyController;
}
@Override
@ -263,8 +262,7 @@ public class NearbyActivity extends NavigationBaseActivity {
@Override
protected List<Place> doInBackground(Void... params) {
return NearbyController
.loadAttractionsFromLocation(curLatLang, application);
return nearbyController.loadAttractionsFromLocation(curLatLang, application);
}
@Override

View file

@ -10,7 +10,6 @@ import com.mapbox.mapboxsdk.annotations.IconFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
@ -29,18 +28,24 @@ import static fr.free.nrw.commons.utils.LengthUtils.formatDistanceBetween;
public class NearbyController {
private static final int MAX_RESULTS = 1000;
private final CommonsApplication application;
public NearbyController(CommonsApplication application) {
this.application = application;
}
/**
* Prepares Place list to make their distance information update later.
* @param curLatLng current location for user
* @param context context
* @return Place list without distance information
*/
public static List<Place> loadAttractionsFromLocation(LatLng curLatLng, Context context) {
public List<Place> loadAttractionsFromLocation(LatLng curLatLng, Context context) {
Timber.d("Loading attractions near %s", curLatLng);
if (curLatLng == null) {
return Collections.emptyList();
}
NearbyPlaces nearbyPlaces = CommonsApplication.getInstance().getNearbyPlaces();
NearbyPlaces nearbyPlaces = application.getNearbyPlaces();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
List<Place> places = prefs.getBoolean("useWikidata", true)
? nearbyPlaces.getFromWikidataQuery(curLatLng, Locale.getDefault().getLanguage())

View file

@ -1,6 +1,7 @@
package fr.free.nrw.commons.settings;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
@ -11,11 +12,22 @@ import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.Utils;
public class SettingsFragment extends PreferenceFragment {
@Inject CommonsApplication application;
@Override
public void onAttach(Context context) {
AndroidInjection.inject(this);
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -41,7 +53,7 @@ public class SettingsFragment extends PreferenceFragment {
final EditTextPreference uploadLimit = (EditTextPreference) findPreference("uploads");
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(CommonsApplication.getInstance());
.getDefaultSharedPreferences(application);
int uploads = sharedPref.getInt(Prefs.UPLOADS_SHOWING, 100);
uploadLimit.setText(uploads + "");
uploadLimit.setSummary(uploads + "");

View file

@ -1,14 +1,12 @@
package fr.free.nrw.commons.upload;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import java.io.IOException;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.contributions.ContributionsActivity;
import fr.free.nrw.commons.mwapi.MediaWikiApi;
@ -19,6 +17,7 @@ import timber.log.Timber;
* Displays a warning to the user if the file already exists on Commons
*/
public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
interface Callback {
void onResult(Result result);
}
@ -29,14 +28,16 @@ public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
DUPLICATE_CANCELLED
}
private final MediaWikiApi api;
private final String fileSha1;
private final Context context;
private final Callback callback;
public ExistingFileAsync(String fileSha1, Context context, Callback callback) {
public ExistingFileAsync(String fileSha1, Context context, Callback callback, MediaWikiApi mwApi) {
this.fileSha1 = fileSha1;
this.context = context;
this.callback = callback;
this.api = mwApi;
}
@Override
@ -46,7 +47,6 @@ public class ExistingFileAsync extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... voids) {
MediaWikiApi api = CommonsApplication.getInstance().getMWApi();
// https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=xml&aisha1=801957214aba50cb63bb6eb1b0effa50188900ba
boolean fileExists;

View file

@ -154,7 +154,7 @@ public class FileUtils {
}
/**
* Check if the URI is owned by the current app.
* Check if the URI is owned by the current application.
*/
public static boolean isSelfOwned(Context context, Uri uri) {
return uri.getAuthority().equals(context.getPackageName() + ".provider");

View file

@ -26,6 +26,7 @@ import timber.log.Timber;
*/
public class GPSExtractor {
private final CommonsApplication application;
private ExifInterface exif;
private double decLatitude;
private double decLongitude;
@ -38,26 +39,30 @@ public class GPSExtractor {
/**
* Construct from the file descriptor of the image (only for API 24 or newer).
* @param fileDescriptor the file descriptor of the image
* @param application the application
*/
@RequiresApi(24)
public GPSExtractor(@NonNull FileDescriptor fileDescriptor) {
public GPSExtractor(@NonNull FileDescriptor fileDescriptor, CommonsApplication application) {
try {
exif = new ExifInterface(fileDescriptor);
} catch (IOException | IllegalArgumentException e) {
Timber.w(e);
}
this.application = application;
}
/**
* Construct from the file path of the image.
* @param path file path of the image
* @param application the application
*/
public GPSExtractor(@NonNull String path) {
public GPSExtractor(@NonNull String path, CommonsApplication application) {
try {
exif = new ExifInterface(path);
} catch (IOException | IllegalArgumentException e) {
Timber.w(e);
}
this.application = application;
}
/**
@ -66,7 +71,7 @@ public class GPSExtractor {
*/
private boolean gpsPreferenceEnabled() {
SharedPreferences sharedPref
= PreferenceManager.getDefaultSharedPreferences(CommonsApplication.getInstance());
= PreferenceManager.getDefaultSharedPreferences(application);
boolean gpsPref = sharedPref.getBoolean("allowGps", false);
Timber.d("Gps pref set to: %b", gpsPref);
return gpsPref;
@ -76,7 +81,7 @@ public class GPSExtractor {
* Registers a LocationManager to listen for current location
*/
protected void registerLocationManager() {
locationManager = (LocationManager) CommonsApplication.getInstance()
locationManager = (LocationManager) application
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);

View file

@ -24,6 +24,8 @@ import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Media;
@ -47,7 +49,9 @@ public class MultipleShareActivity
FragmentManager.OnBackStackChangedListener,
MultipleUploadListFragment.OnMultipleUploadInitiatedHandler,
OnCategoriesSaveHandler {
private CommonsApplication app;
@Inject
CommonsApplication application;
private ArrayList<Contribution> photosList = null;
private MultipleUploadListFragment uploadsList;
@ -133,7 +137,7 @@ public class MultipleShareActivity
if (uploadCount == photosList.size()) {
dialog.dismiss();
Toast startingToast = Toast.makeText(
CommonsApplication.getInstance(),
application,
R.string.uploading_started,
Toast.LENGTH_LONG
);
@ -176,9 +180,9 @@ public class MultipleShareActivity
}
// FIXME: Make sure that the content provider is up
// This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin
ContentResolver.setSyncAutomatically(app.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("categories-count", categories.size())
.param("files-count", photosList.size())
.param("source", Contribution.SOURCE_EXTERNAL)
@ -202,10 +206,9 @@ public class MultipleShareActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uploadController = new UploadController();
uploadController = new UploadController(application);
setContentView(R.layout.activity_multiple_uploads);
app = CommonsApplication.getInstance();
ButterKnife.bind(this);
initDrawer();
@ -245,7 +248,7 @@ public class MultipleShareActivity
@Override
protected void onAuthCookieAcquired(String authCookie) {
app.getMWApi().setAuthCookie(authCookie);
application.getMWApi().setAuthCookie(authCookie);
Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
@ -288,16 +291,16 @@ public class MultipleShareActivity
public void onBackPressed() {
super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount())
.param("files-count", photosList.size())
.param("source", Contribution.SOURCE_EXTERNAL)
.param("result", "cancelled")
.log();
} else {
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE))
.param("multiple", true)
.param("result", "cancelled")
@ -307,11 +310,7 @@ public class MultipleShareActivity
@Override
public void onBackStackChanged() {
if(mediaDetails != null && mediaDetails.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(mediaDetails != null && mediaDetails.isVisible());
}
}

View file

@ -33,13 +33,15 @@ public class MwVolleyApi {
private static RequestQueue REQUEST_QUEUE;
private static final Gson GSON = new GsonBuilder().create();
protected static Set<String> categorySet;
private static Set<String> categorySet;
private static List<String> categoryList;
private static final String MWURL = "https://commons.wikimedia.org/";
private final CommonsApplication application;
public MwVolleyApi() {
public MwVolleyApi(CommonsApplication application) {
categorySet = new HashSet<>();
this.application = application;
}
public static List<String> getGpsCat() {
@ -93,7 +95,7 @@ public class MwVolleyApi {
private synchronized RequestQueue getQueue() {
if (REQUEST_QUEUE == null) {
REQUEST_QUEUE = Volley.newRequestQueue(CommonsApplication.getInstance());
REQUEST_QUEUE = Volley.newRequestQueue(application);
}
return REQUEST_QUEUE;
}

View file

@ -30,6 +30,8 @@ import java.io.InputStream;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R;
@ -63,7 +65,7 @@ public class ShareActivity
private static final int REQUEST_PERM_ON_SUBMIT_STORAGE = 4;
private CategorizationFragment categorizationFragment;
private CommonsApplication app;
@Inject CommonsApplication application;
private String source;
private String mimeType;
@ -114,7 +116,7 @@ public class ShareActivity
@RequiresApi(16)
private boolean needsToRequestStoragePermission() {
// We need to ask storage permission when
// the file is not owned by this app, (e.g. shared from the Gallery)
// the file is not owned by this application, (e.g. shared from the Gallery)
// and permission is not obtained.
return !FileUtils.isSelfOwned(getApplicationContext(), mediaUri)
&& (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
@ -125,7 +127,7 @@ public class ShareActivity
getFileMetadata(locationPermitted);
Toast startingToast = Toast.makeText(
CommonsApplication.getInstance(),
application,
R.string.uploading_started,
Toast.LENGTH_LONG
);
@ -133,7 +135,7 @@ public class ShareActivity
if (!cacheFound) {
//Has to be called after apiCall.request()
app.getCacheData().cacheCategory();
application.getCacheData().cacheCategory();
Timber.d("Cache the categories found");
}
@ -165,10 +167,10 @@ public class ShareActivity
// FIXME: Make sure that the content provider is up
// This is the wrong place for it, but bleh - better than not having it turned on by default for people who don't go throughl ogin
ContentResolver.setSyncAutomatically(app.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
ContentResolver.setSyncAutomatically(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, true); // Enable sync by default!
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("categories-count", categories.size())
.param("files-count", 1)
.param("source", contribution.getSource())
@ -189,16 +191,16 @@ public class ShareActivity
public void onBackPressed() {
super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount())
.param("files-count", 1)
.param("source", contribution.getSource())
.param("result", "cancelled")
.log();
} else {
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("source", getIntent().getStringExtra(UploadService.EXTRA_SOURCE))
.param("multiple", true)
.param("result", "cancelled")
@ -208,7 +210,7 @@ public class ShareActivity
@Override
protected void onAuthCookieAcquired(String authCookie) {
app.getMWApi().setAuthCookie(authCookie);
application.getMWApi().setAuthCookie(authCookie);
}
@ -222,11 +224,10 @@ public class ShareActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uploadController = new UploadController();
uploadController = new UploadController(application);
setContentView(R.layout.activity_share);
ButterKnife.bind(this);
initBack();
app = CommonsApplication.getInstance();
backgroundImageView = (SimpleDraweeView)findViewById(R.id.backgroundImage);
backgroundImageView.setHierarchy(GenericDraweeHierarchyBuilder
.newInstance(getResources())
@ -384,7 +385,7 @@ public class ShareActivity
Timber.d("%s duplicate check: %s", mediaUri.toString(), result);
duplicateCheckPassed = (result == DUPLICATE_PROCEED
|| result == NO_DUPLICATE);
});
}, application.getMWApi());
fileAsyncTask.execute();
} catch (IOException e) {
Timber.d(e, "IO Exception: ");
@ -448,12 +449,12 @@ public class ShareActivity
= getContentResolver().openFileDescriptor(mediaUri, "r");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (descriptor != null) {
imageObj = new GPSExtractor(descriptor.getFileDescriptor());
imageObj = new GPSExtractor(descriptor.getFileDescriptor(), application);
}
} else {
String filePath = getPathOfMediaOrCopy();
if (filePath != null) {
imageObj = new GPSExtractor(filePath);
imageObj = new GPSExtractor(filePath, application);
}
}
}
@ -480,12 +481,12 @@ public class ShareActivity
if (imageObj.imageCoordsExists) {
double decLongitude = imageObj.getDecLongitude();
double decLatitude = imageObj.getDecLatitude();
app.getCacheData().setQtPoint(decLongitude, decLatitude);
application.getCacheData().setQtPoint(decLongitude, decLatitude);
}
MwVolleyApi apiCall = new MwVolleyApi();
MwVolleyApi apiCall = new MwVolleyApi(application);
List<String> displayCatList = app.getCacheData().findCategory();
List<String> displayCatList = application.getCacheData().findCategory();
boolean catListEmpty = displayCatList.isEmpty();
// If no categories found in cache, call MediaWiki API to match image coords with nearby Commons categories

View file

@ -26,14 +26,14 @@ import timber.log.Timber;
public class UploadController {
private UploadService uploadService;
private final CommonsApplication app;
private final CommonsApplication application;
public interface ContributionUploadProgress {
void onUploadStarted(Contribution contribution);
}
public UploadController() {
app = CommonsApplication.getInstance();
public UploadController(CommonsApplication application) {
this.application = application;
}
private boolean isUploadServiceConnected;
@ -52,15 +52,15 @@ public class UploadController {
};
public void prepareService() {
Intent uploadServiceIntent = new Intent(app, UploadService.class);
Intent uploadServiceIntent = new Intent(application, UploadService.class);
uploadServiceIntent.setAction(UploadService.ACTION_START_SERVICE);
app.startService(uploadServiceIntent);
app.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);
application.startService(uploadServiceIntent);
application.bindService(uploadServiceIntent, uploadServiceConnection, Context.BIND_AUTO_CREATE);
}
public void cleanup() {
if(isUploadServiceConnected) {
app.unbindService(uploadServiceConnection);
application.unbindService(uploadServiceConnection);
}
}
@ -68,7 +68,7 @@ public class UploadController {
Contribution contribution;
//TODO: Modify this to include coords
contribution = new Contribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, decimalCoords);
contribution = new Contribution(mediaUri, null, title, description, -1, null, null, application.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, decimalCoords);
contribution.setTag("mimeType", mimeType);
contribution.setSource(source);
@ -79,11 +79,11 @@ public class UploadController {
public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(application);
//Set creator, desc, and license
if(TextUtils.isEmpty(contribution.getCreator())) {
contribution.setCreator(app.getCurrentAccount().name);
contribution.setCreator(application.getCurrentAccount().name);
}
if(contribution.getDescription() == null) {
@ -104,12 +104,12 @@ public class UploadController {
long length;
try {
if(contribution.getDataLength() <= 0) {
length = app.getContentResolver()
length = application.getContentResolver()
.openAssetFileDescriptor(contribution.getLocalUri(), "r")
.getLength();
if(length == -1) {
// Let us find out the long way!
length = Utils.countBytes(app.getContentResolver()
length = Utils.countBytes(application.getContentResolver()
.openInputStream(contribution.getLocalUri()));
}
contribution.setDataLength(length);
@ -126,7 +126,7 @@ public class UploadController {
Boolean imagePrefix = false;
if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
mimeType = app.getContentResolver().getType(contribution.getLocalUri());
mimeType = application.getContentResolver().getType(contribution.getLocalUri());
}
if (mimeType != null) {
@ -137,7 +137,7 @@ public class UploadController {
if (imagePrefix && contribution.getDateCreated() == null) {
Timber.d("local uri " + contribution.getLocalUri());
Cursor cursor = app.getContentResolver().query(contribution.getLocalUri(),
Cursor cursor = application.getContentResolver().query(contribution.getLocalUri(),
new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null);
if (cursor != null && cursor.getCount() != 0 && cursor.getColumnCount() != 0) {
cursor.moveToFirst();

View file

@ -22,6 +22,8 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.HandlerService;
import fr.free.nrw.commons.R;
@ -45,12 +47,11 @@ public class UploadService extends HandlerService<Contribution> {
public static final String EXTRA_SOURCE = EXTRA_PREFIX + ".source";
public static final String EXTRA_CAMPAIGN = EXTRA_PREFIX + ".campaign";
@Inject CommonsApplication application;
private NotificationManager notificationManager;
private ContentProviderClient contributionsProviderClient;
private CommonsApplication app;
private NotificationCompat.Builder curProgressNotification;
private int toUpload;
// The file names of unfinished uploads, used to prevent overwriting
@ -115,10 +116,11 @@ public class UploadService extends HandlerService<Contribution> {
@Override
public void onCreate() {
((CommonsApplication)getApplicationContext()).injector().inject(this);
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
app = CommonsApplication.getInstance();
contributionsProviderClient = this.getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
}
@ -180,7 +182,7 @@ public class UploadService extends HandlerService<Contribution> {
@SuppressLint("StringFormatInvalid")
private void uploadContribution(Contribution contribution) {
MediaWikiApi api = app.getMWApi();
MediaWikiApi api = application.getMWApi();
InputStream file = null;
@ -222,7 +224,7 @@ public class UploadService extends HandlerService<Contribution> {
}
if (!api.validateLogin()) {
// Need to revalidate!
if (app.revalidateAuthToken()) {
if (application.revalidateAuthToken()) {
Timber.d("Successfully revalidated token!");
} else {
Timber.d("Unable to revalidate :(");
@ -247,8 +249,8 @@ public class UploadService extends HandlerService<Contribution> {
String resultStatus = uploadResult.getResultStatus();
if (!resultStatus.equals("Success")) {
showFailedNotification(contribution);
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("source", contribution.getSource())
.param("multiple", contribution.getMultiple())
.param("result", uploadResult.getErrorCode())
@ -261,8 +263,8 @@ public class UploadService extends HandlerService<Contribution> {
contribution.setDateUploaded(uploadResult.getDateUploaded());
contribution.save();
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, CommonsApplication.getInstance())
.param("username", app.getCurrentAccount().name)
EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT, application)
.param("username", application.getCurrentAccount().name)
.param("source", contribution.getSource()) //FIXME
.param("filename", contribution.getFilename())
.param("multiple", contribution.getMultiple())
@ -279,7 +281,7 @@ public class UploadService extends HandlerService<Contribution> {
toUpload--;
if (toUpload == 0) {
// Sync modifications right after all uplaods are processed
ContentResolver.requestSync((CommonsApplication.getInstance()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
ContentResolver.requestSync(application.getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle());
stopForeground(true);
}
}
@ -302,7 +304,7 @@ public class UploadService extends HandlerService<Contribution> {
}
private String findUniqueFilename(String fileName) throws IOException {
MediaWikiApi api = app.getMWApi();
MediaWikiApi api = application.getMWApi();
String sequenceFileName;
for (int sequenceNumber = 1; true; sequenceNumber++) {
if (sequenceNumber == 1) {