Fixing some lint issues for #171

This commit is contained in:
Manuel Lorenzo 2018-02-07 11:32:24 +01:00 committed by Suchit Kar
parent 370a13b711
commit 8ef1fb7dd0
30 changed files with 179 additions and 278 deletions

View file

@ -31,7 +31,7 @@ public class AboutActivity extends NavigationBaseActivity {
ButterKnife.bind(this); ButterKnife.bind(this);
String aboutText = getString(R.string.about_license, getString(R.string.trademarked_name)); String aboutText = getString(R.string.about_license);
aboutLicenseText.setHtmlText(aboutText); aboutLicenseText.setHtmlText(aboutText);
versionText.setText(BuildConfig.VERSION_NAME); versionText.setText(BuildConfig.VERSION_NAME);

View file

@ -32,7 +32,6 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.BuildConfig; import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.PageTitle; import fr.free.nrw.commons.PageTitle;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;

View file

@ -1,128 +0,0 @@
package fr.free.nrw.commons.auth;
import android.accounts.AccountAuthenticatorResponse;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import java.io.IOException;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.mwapi.MediaWikiApi;
import timber.log.Timber;
import static android.accounts.AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE;
import static android.accounts.AccountManager.KEY_ACCOUNT_NAME;
import static android.accounts.AccountManager.KEY_ACCOUNT_TYPE;
import static fr.free.nrw.commons.auth.AccountUtil.ACCOUNT_TYPE;
class LoginTask extends AsyncTask<String, String, String> {
private LoginActivity loginActivity;
private String username;
private String password;
private String twoFactorCode = "";
private AccountUtil accountUtil;
private MediaWikiApi mwApi;
public LoginTask(LoginActivity loginActivity, String username, String password,
String twoFactorCode, AccountUtil accountUtil,
MediaWikiApi mwApi, SharedPreferences prefs) {
this.loginActivity = loginActivity;
this.username = username;
this.password = password;
this.twoFactorCode = twoFactorCode;
this.accountUtil = accountUtil;
this.mwApi = mwApi;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loginActivity.progressDialog = new ProgressDialog(loginActivity);
loginActivity.progressDialog.setIndeterminate(true);
loginActivity.progressDialog.setTitle(loginActivity.getString(R.string.logging_in_title));
loginActivity.progressDialog.setMessage(loginActivity.getString(R.string.logging_in_message));
loginActivity.progressDialog.setCanceledOnTouchOutside(false);
loginActivity.progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
try {
if (twoFactorCode.isEmpty()) {
return mwApi.login(username, password);
} else {
return mwApi.login(username, password, twoFactorCode);
}
} catch (IOException e) {
// Do something better!
return "NetworkFailure";
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Timber.d("Login done!");
if (result.equals("PASS")) {
handlePassResult();
} else {
handleOtherResults(result);
}
}
private void handlePassResult() {
loginActivity.showSuccessAndDismissDialog();
AccountAuthenticatorResponse response = null;
Bundle extras = loginActivity.getIntent().getExtras();
if (extras != null) {
Timber.d("Bundle of extras: %s", extras);
response = extras.getParcelable(KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
if (response != null) {
Bundle authResult = new Bundle();
authResult.putString(KEY_ACCOUNT_NAME, username);
authResult.putString(KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
response.onResult(authResult);
}
}
accountUtil.createAccount(response, username, password);
loginActivity.startMainActivity();
}
/**
* Match known failure message codes and provide messages.
* @param result String
*/
private void handleOtherResults(String result) {
if (result.equals("NetworkFailure")) {
// Matches NetworkFailure which is created by the doInBackground method
loginActivity.showMessageAndCancelDialog(R.string.login_failed_network);
} else if (result.toLowerCase().contains("nosuchuser".toLowerCase()) || result.toLowerCase().contains("noname".toLowerCase())) {
// Matches nosuchuser, nosuchusershort, noname
loginActivity.showMessageAndCancelDialog(R.string.login_failed_username);
loginActivity.emptySensitiveEditFields();
} else if (result.toLowerCase().contains("wrongpassword".toLowerCase())) {
// Matches wrongpassword, wrongpasswordempty
loginActivity.showMessageAndCancelDialog(R.string.login_failed_password);
loginActivity.emptySensitiveEditFields();
} else if (result.toLowerCase().contains("throttle".toLowerCase())) {
// Matches unknown throttle error codes
loginActivity.showMessageAndCancelDialog(R.string.login_failed_throttled);
} else if (result.toLowerCase().contains("userblocked".toLowerCase())) {
// Matches login-userblocked
loginActivity.showMessageAndCancelDialog(R.string.login_failed_blocked);
} else if (result.equals("2FA")) {
loginActivity.askUserForTwoFactorAuth();
} else {
// Occurs with unhandled login failure codes
Timber.d("Login failed with reason: %s", result);
loginActivity.showMessageAndCancelDialog(R.string.login_failed_generic);
}
}
}

View file

@ -1,6 +1,5 @@
package fr.free.nrw.commons.category; package fr.free.nrw.commons.category;
import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;

View file

@ -93,10 +93,15 @@ class ContributionController {
shareIntent.putExtra(EXTRA_SOURCE, SOURCE_GALLERY); shareIntent.putExtra(EXTRA_SOURCE, SOURCE_GALLERY);
break; break;
case SELECT_FROM_CAMERA: case SELECT_FROM_CAMERA:
shareIntent.setType("image/jpeg"); //FIXME: Find out appropriate mime type //FIXME: Find out appropriate mime type
// AFAIK this is the right type for a JPEG image
// https://developer.android.com/training/sharing/send.html#send-binary-content
shareIntent.setType("image/jpeg");
shareIntent.putExtra(EXTRA_STREAM, lastGeneratedCaptureUri); shareIntent.putExtra(EXTRA_STREAM, lastGeneratedCaptureUri);
shareIntent.putExtra(EXTRA_SOURCE, SOURCE_CAMERA); shareIntent.putExtra(EXTRA_SOURCE, SOURCE_CAMERA);
break; break;
default:
break;
} }
Timber.i("Image selected"); Timber.i("Image selected");
try { try {

View file

@ -86,7 +86,7 @@ public class ContributionsContentProvider extends CommonsDaggerContentProvider {
public Uri insert(@NonNull Uri uri, ContentValues contentValues) { public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
long id = 0; long id;
switch (uriType) { switch (uriType) {
case CONTRIBUTIONS: case CONTRIBUTIONS:
id = sqlDB.insert(TABLE_NAME, null, contentValues); id = sqlDB.insert(TABLE_NAME, null, contentValues);
@ -158,7 +158,7 @@ public class ContributionsContentProvider extends CommonsDaggerContentProvider {
*/ */
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
int rowsUpdated = 0; int rowsUpdated;
switch (uriType) { switch (uriType) {
case CONTRIBUTIONS: case CONTRIBUTIONS:
rowsUpdated = sqlDB.update(TABLE_NAME, contentValues, selection, selectionArgs); rowsUpdated = sqlDB.update(TABLE_NAME, contentValues, selection, selectionArgs);

View file

@ -20,6 +20,8 @@ import android.widget.ListAdapter;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView; import android.widget.TextView;
import java.util.Arrays;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
@ -45,8 +47,12 @@ public class ContributionsListFragment extends CommonsDaggerSupportFragment {
@BindView(R.id.loadingContributionsProgressBar) @BindView(R.id.loadingContributionsProgressBar)
ProgressBar progressBar; ProgressBar progressBar;
@Inject @Named("prefs") SharedPreferences prefs; @Inject
@Inject @Named("default_preferences") SharedPreferences defaultPrefs; @Named("prefs")
SharedPreferences prefs;
@Inject
@Named("default_preferences")
SharedPreferences defaultPrefs;
private ContributionController controller; private ContributionController controller;
@ -208,7 +214,7 @@ public class ContributionsListFragment extends CommonsDaggerSupportFragment {
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) { @NonNull int[] grantResults) {
Timber.d("onRequestPermissionsResult: req code = " + " perm = " Timber.d("onRequestPermissionsResult: req code = " + " perm = "
+ permissions + " grant =" + grantResults); + Arrays.toString(permissions) + " grant =" + Arrays.toString(grantResults));
switch (requestCode) { switch (requestCode) {
// 1 = Storage allowed when gallery selected // 1 = Storage allowed when gallery selected

View file

@ -23,7 +23,6 @@ import java.util.TimeZone;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.Utils; import fr.free.nrw.commons.Utils;
import fr.free.nrw.commons.di.ApplicationlessInjection; import fr.free.nrw.commons.di.ApplicationlessInjection;
import fr.free.nrw.commons.mwapi.LogEventResult; import fr.free.nrw.commons.mwapi.LogEventResult;

View file

@ -1,7 +1,5 @@
package fr.free.nrw.commons.di; package fr.free.nrw.commons.di;
import android.content.Context;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Component; import dagger.Component;
@ -11,10 +9,7 @@ import dagger.android.support.AndroidSupportInjectionModule;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.MediaWikiImageView; import fr.free.nrw.commons.MediaWikiImageView;
import fr.free.nrw.commons.auth.LoginActivity; import fr.free.nrw.commons.auth.LoginActivity;
import fr.free.nrw.commons.category.CategoryContentProvider;
import fr.free.nrw.commons.contributions.ContributionsContentProvider;
import fr.free.nrw.commons.contributions.ContributionsSyncAdapter; import fr.free.nrw.commons.contributions.ContributionsSyncAdapter;
import fr.free.nrw.commons.modifications.ModificationsContentProvider;
import fr.free.nrw.commons.modifications.ModificationsSyncAdapter; import fr.free.nrw.commons.modifications.ModificationsSyncAdapter;
import fr.free.nrw.commons.settings.SettingsFragment; import fr.free.nrw.commons.settings.SettingsFragment;

View file

@ -14,9 +14,6 @@ import android.support.v4.content.ContextCompat;
import java.util.List; import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import javax.inject.Inject;
import javax.inject.Singleton;
import timber.log.Timber; import timber.log.Timber;
public class LocationServiceManager implements LocationListener { public class LocationServiceManager implements LocationListener {
@ -33,6 +30,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Constructs a new instance of LocationServiceManager. * Constructs a new instance of LocationServiceManager.
*
* @param context the context * @param context the context
*/ */
public LocationServiceManager(Context context) { public LocationServiceManager(Context context) {
@ -42,6 +40,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Returns the current status of the GPS provider. * Returns the current status of the GPS provider.
*
* @return true if the GPS provider is enabled * @return true if the GPS provider is enabled
*/ */
public boolean isProviderEnabled() { public boolean isProviderEnabled() {
@ -50,6 +49,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Returns whether the location permission is granted. * Returns whether the location permission is granted.
*
* @return true if the location permission is granted * @return true if the location permission is granted
*/ */
public boolean isLocationPermissionGranted() { public boolean isLocationPermissionGranted() {
@ -59,6 +59,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Requests the location permission to be granted. * Requests the location permission to be granted.
*
* @param activity the activity * @param activity the activity
*/ */
public void requestPermissions(Activity activity) { public void requestPermissions(Activity activity) {
@ -71,10 +72,8 @@ public class LocationServiceManager implements LocationListener {
} }
public boolean isPermissionExplanationRequired(Activity activity) { public boolean isPermissionExplanationRequired(Activity activity) {
if (activity.isFinishing()) { return !activity.isFinishing() &&
return false; ActivityCompat.shouldShowRequestPermissionRationale(activity,
}
return ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.ACCESS_FINE_LOCATION); Manifest.permission.ACCESS_FINE_LOCATION);
} }
@ -85,7 +84,8 @@ public class LocationServiceManager implements LocationListener {
return LatLng.from(lastLocation); return LatLng.from(lastLocation);
} }
/** Registers a LocationManager to listen for current location. /**
* Registers a LocationManager to listen for current location.
*/ */
public void registerLocationManager() { public void registerLocationManager() {
if (!isLocationManagerRegistered) if (!isLocationManagerRegistered)
@ -95,6 +95,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Requests location updates from the specified provider. * Requests location updates from the specified provider.
*
* @param locationProvider the location provider * @param locationProvider the location provider
* @return true if successful * @return true if successful
*/ */
@ -116,6 +117,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Returns whether a given location is better than the current best location. * Returns whether a given location is better than the current best location.
*
* @param location the location to be tested * @param location the location to be tested
* @param currentBestLocation the current best location * @param currentBestLocation the current best location
* @return true if the given location is better * @return true if the given location is better
@ -172,7 +174,8 @@ public class LocationServiceManager implements LocationListener {
return provider1.equals(provider2); return provider1.equals(provider2);
} }
/** Unregisters location manager. /**
* Unregisters location manager.
*/ */
public void unregisterLocationManager() { public void unregisterLocationManager() {
isLocationManagerRegistered = false; isLocationManagerRegistered = false;
@ -185,6 +188,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Adds a new listener to the list of location listeners. * Adds a new listener to the list of location listeners.
*
* @param listener the new listener * @param listener the new listener
*/ */
public void addLocationListener(LocationUpdateListener listener) { public void addLocationListener(LocationUpdateListener listener) {
@ -195,6 +199,7 @@ public class LocationServiceManager implements LocationListener {
/** /**
* Removes a listener from the list of location listeners. * Removes a listener from the list of location listeners.
*
* @param listener the listener to be removed * @param listener the listener to be removed
*/ */
public void removeLocationListener(LocationUpdateListener listener) { public void removeLocationListener(LocationUpdateListener listener) {

View file

@ -76,7 +76,7 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once! private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once!
private ViewTreeObserver.OnScrollChangedListener scrollListener; private ViewTreeObserver.OnScrollChangedListener scrollListener;
private DataSetObserver dataObserver; private DataSetObserver dataObserver;
private AsyncTask<Void,Void,Boolean> detailFetchTask; private AsyncTask<Void, Void, Boolean> detailFetchTask;
private LicenseList licenseList; private LicenseList licenseList;
@Override @Override
@ -95,7 +95,7 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
detailProvider = (MediaDetailPagerFragment.MediaDetailProvider)getActivity(); detailProvider = (MediaDetailPagerFragment.MediaDetailProvider) getActivity();
if (savedInstanceState != null) { if (savedInstanceState != null) {
editable = savedInstanceState.getBoolean("editable"); editable = savedInstanceState.getBoolean("editable");
@ -156,7 +156,8 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
return view; return view;
} }
@Override public void onResume() { @Override
public void onResume() {
super.onResume(); super.onResume();
Media media = detailProvider.getMediaAtPosition(index); Media media = detailProvider.getMediaAtPosition(index);
if (media == null) { if (media == null) {
@ -238,11 +239,11 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
detailFetchTask.cancel(true); detailFetchTask.cancel(true);
detailFetchTask = null; detailFetchTask = null;
} }
if (layoutListener != null) { if (layoutListener != null && getView() != null) {
getView().getViewTreeObserver().removeGlobalOnLayoutListener(layoutListener); // old Android was on crack. CRACK IS WHACK getView().getViewTreeObserver().removeGlobalOnLayoutListener(layoutListener); // old Android was on crack. CRACK IS WHACK
layoutListener = null; layoutListener = null;
} }
if (scrollListener != null) { if (scrollListener != null && getView() != null) {
getView().getViewTreeObserver().removeOnScrollChangedListener(scrollListener); getView().getViewTreeObserver().removeOnScrollChangedListener(scrollListener);
scrollListener = null; scrollListener = null;
} }
@ -289,7 +290,7 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
private View buildCatLabel(final String catName, ViewGroup categoryContainer) { private View buildCatLabel(final String catName, ViewGroup categoryContainer) {
final View item = LayoutInflater.from(getContext()).inflate(R.layout.detail_category_item, categoryContainer, false); final View item = LayoutInflater.from(getContext()).inflate(R.layout.detail_category_item, categoryContainer, false);
final CompatTextView textView = (CompatTextView)item.findViewById(R.id.mediaDetailCategoryItemText); final CompatTextView textView = (CompatTextView) item.findViewById(R.id.mediaDetailCategoryItemText);
textView.setText(catName); textView.setText(catName);
if (categoriesLoaded && categoriesPresent) { if (categoriesLoaded && categoriesPresent) {
@ -308,7 +309,7 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
// You must face the darkness alone // You must face the darkness alone
int scrollY = scrollView.getScrollY(); int scrollY = scrollView.getScrollY();
int scrollMax = getView().getHeight(); int scrollMax = getView().getHeight();
float scrollPercentage = (float)scrollY / (float)scrollMax; float scrollPercentage = (float) scrollY / (float) scrollMax;
final float transparencyMax = 0.75f; final float transparencyMax = 0.75f;
if (scrollPercentage > transparencyMax) { if (scrollPercentage > transparencyMax) {
scrollPercentage = transparencyMax; scrollPercentage = transparencyMax;
@ -362,7 +363,8 @@ public class MediaDetailFragment extends CommonsDaggerSupportFragment {
} }
private @Nullable String licenseLink(Media media) { private @Nullable
String licenseLink(Media media) {
String licenseKey = media.getLicense(); String licenseKey = media.getLicense();
if (licenseKey == null || licenseKey.equals("")) { if (licenseKey == null || licenseKey.equals("")) {
return null; return null;

View file

@ -43,9 +43,13 @@ import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MediaDetailPagerFragment extends CommonsDaggerSupportFragment implements ViewPager.OnPageChangeListener { public class MediaDetailPagerFragment extends CommonsDaggerSupportFragment implements ViewPager.OnPageChangeListener {
@Inject MediaWikiApi mwApi; @Inject
@Inject SessionManager sessionManager; MediaWikiApi mwApi;
@Inject @Named("default_preferences") SharedPreferences prefs; @Inject
SessionManager sessionManager;
@Inject
@Named("default_preferences")
SharedPreferences prefs;
private ViewPager pager; private ViewPager pager;
private Boolean editable; private Boolean editable;
@ -164,13 +168,19 @@ public class MediaDetailPagerFragment extends CommonsDaggerSupportFragment imple
req.allowScanningByMediaScanner(); req.allowScanningByMediaScanner();
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !(ContextCompat.checkSelfPermission(getContext(), READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(getContext(), READ_EXTERNAL_STORAGE)
!= PERMISSION_GRANTED
&& getView() != null) {
Snackbar.make(getView(), R.string.read_storage_permission_rationale, Snackbar.make(getView(), R.string.read_storage_permission_rationale,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok,
view -> ActivityCompat.requestPermissions(getActivity(), view -> ActivityCompat.requestPermissions(getActivity(),
new String[]{READ_EXTERNAL_STORAGE}, 1)).show(); new String[]{READ_EXTERNAL_STORAGE}, 1)).show();
} else { } else {
((DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE)).enqueue(req); DownloadManager systemService = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
if (systemService != null) {
systemService.enqueue(req);
}
} }
} }

View file

@ -70,7 +70,7 @@ public class ModificationsContentProvider extends CommonsDaggerContentProvider {
public Uri insert(@NonNull Uri uri, ContentValues contentValues) { public Uri insert(@NonNull Uri uri, ContentValues contentValues) {
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
long id = 0; long id;
switch (uriType) { switch (uriType) {
case MODIFICATIONS: case MODIFICATIONS:
id = sqlDB.insert(TABLE_NAME, null, contentValues); id = sqlDB.insert(TABLE_NAME, null, contentValues);
@ -132,7 +132,7 @@ public class ModificationsContentProvider extends CommonsDaggerContentProvider {
*/ */
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();
int rowsUpdated = 0; int rowsUpdated;
switch (uriType) { switch (uriType) {
case MODIFICATIONS: case MODIFICATIONS:
rowsUpdated = sqlDB.update(TABLE_NAME, rowsUpdated = sqlDB.update(TABLE_NAME,

View file

@ -52,7 +52,7 @@ public class ModifierSequenceDao {
ModifierSequence fromCursor(Cursor cursor) { ModifierSequence fromCursor(Cursor cursor) {
// Hardcoding column positions! // Hardcoding column positions!
ModifierSequence ms = null; ModifierSequence ms;
try { try {
ms = new ModifierSequence(Uri.parse(cursor.getString(1)), ms = new ModifierSequence(Uri.parse(cursor.getString(1)),
new JSONObject(cursor.getString(2))); new JSONObject(cursor.getString(2)));

View file

@ -1,6 +1,5 @@
package fr.free.nrw.commons.nearby; package fr.free.nrw.commons.nearby;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
@ -41,8 +40,6 @@ import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import timber.log.Timber; import timber.log.Timber;
import static fr.free.nrw.commons.location.LocationServiceManager.LOCATION_REQUEST;
public class NearbyActivity extends NavigationBaseActivity implements LocationUpdateListener { public class NearbyActivity extends NavigationBaseActivity implements LocationUpdateListener {

View file

@ -39,6 +39,7 @@ public class NearbyController {
/** /**
* Prepares Place list to make their distance information update later. * Prepares Place list to make their distance information update later.
*
* @param curLatLng current location for user * @param curLatLng current location for user
* @param context context * @param context context
* @return Place list without distance information * @return Place list without distance information
@ -51,10 +52,9 @@ public class NearbyController {
List<Place> places = prefs.getBoolean("useWikidata", true) List<Place> places = prefs.getBoolean("useWikidata", true)
? nearbyPlaces.getFromWikidataQuery(curLatLng, Locale.getDefault().getLanguage()) ? nearbyPlaces.getFromWikidataQuery(curLatLng, Locale.getDefault().getLanguage())
: nearbyPlaces.getFromWikiNeedsPictures(); : nearbyPlaces.getFromWikiNeedsPictures();
if (curLatLng != null) {
Timber.d("Sorting places by distance..."); Timber.d("Sorting places by distance...");
final Map<Place, Double> distances = new HashMap<>(); final Map<Place, Double> distances = new HashMap<>();
for (Place place: places) { for (Place place : places) {
distances.put(place, computeDistanceBetween(place.location, curLatLng)); distances.put(place, computeDistanceBetween(place.location, curLatLng));
} }
Collections.sort(places, Collections.sort(places,
@ -64,12 +64,12 @@ public class NearbyController {
return (int) (lhsDistance - rhsDistance); return (int) (lhsDistance - rhsDistance);
} }
); );
}
return places; return places;
} }
/** /**
* Loads attractions from location for list view, we need to return Place data type. * Loads attractions from location for list view, we need to return Place data type.
*
* @param curLatLng users current location * @param curLatLng users current location
* @param placeList list of nearby places in Place data type * @param placeList list of nearby places in Place data type
* @return Place list that holds nearby places * @return Place list that holds nearby places
@ -78,7 +78,7 @@ public class NearbyController {
LatLng curLatLng, LatLng curLatLng,
List<Place> placeList) { List<Place> placeList) {
placeList = placeList.subList(0, Math.min(placeList.size(), MAX_RESULTS)); placeList = placeList.subList(0, Math.min(placeList.size(), MAX_RESULTS));
for (Place place: placeList) { for (Place place : placeList) {
String distance = formatDistanceBetween(curLatLng, place.location); String distance = formatDistanceBetween(curLatLng, place.location);
place.setDistance(distance); place.setDistance(distance);
} }
@ -86,7 +86,8 @@ public class NearbyController {
} }
/** /**
*Loads attractions from location for map view, we need to return BaseMarkerOption data type. * Loads attractions from location for map view, we need to return BaseMarkerOption data type.
*
* @param curLatLng users current location * @param curLatLng users current location
* @param placeList list of nearby places in Place data type * @param placeList list of nearby places in Place data type
* @return BaseMarkerOptions list that holds nearby places * @return BaseMarkerOptions list that holds nearby places
@ -103,12 +104,13 @@ public class NearbyController {
placeList = placeList.subList(0, Math.min(placeList.size(), MAX_RESULTS)); placeList = placeList.subList(0, Math.min(placeList.size(), MAX_RESULTS));
Bitmap icon = UiUtils.getBitmap( VectorDrawableCompat vectorDrawable = VectorDrawableCompat.create(
VectorDrawableCompat.create(
context.getResources(), R.drawable.ic_custom_map_marker, context.getTheme() context.getResources(), R.drawable.ic_custom_map_marker, context.getTheme()
)); );
if (vectorDrawable != null) {
Bitmap icon = UiUtils.getBitmap(vectorDrawable);
for (Place place: placeList) { for (Place place : placeList) {
String distance = formatDistanceBetween(curLatLng, place.location); String distance = formatDistanceBetween(curLatLng, place.location);
place.setDistance(distance); place.setDistance(distance);
@ -124,6 +126,7 @@ public class NearbyController {
baseMarkerOptions.add(nearbyBaseMarker); baseMarkerOptions.add(nearbyBaseMarker);
} }
}
return baseMarkerOptions; return baseMarkerOptions;
} }
} }

View file

@ -19,7 +19,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import dagger.android.support.AndroidSupportInjection; import dagger.android.support.AndroidSupportInjection;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import fr.free.nrw.commons.location.LatLng; import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.utils.UriDeserializer; import fr.free.nrw.commons.utils.UriDeserializer;

View file

@ -9,7 +9,6 @@ import android.view.ViewGroup;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import dagger.android.support.AndroidSupportInjection; import dagger.android.support.AndroidSupportInjection;
import dagger.android.support.DaggerFragment;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;
import timber.log.Timber; import timber.log.Timber;

View file

@ -60,9 +60,7 @@ public class NotificationActivity extends NavigationBaseActivity {
.subscribe(notificationList -> { .subscribe(notificationList -> {
Timber.d("Number of notifications is %d", notificationList.size()); Timber.d("Number of notifications is %d", notificationList.size());
setAdapter(notificationList); setAdapter(notificationList);
}, throwable -> { }, throwable -> Timber.e(throwable, "Error occurred while loading notifications"));
Timber.e(throwable, "Error occurred while loading notifications");
});
} }
private void handleUrl(String url) { private void handleUrl(String url) {

View file

@ -8,13 +8,9 @@ import android.widget.TextView;
import com.pedrogomez.renderers.Renderer; import com.pedrogomez.renderers.Renderer;
import java.util.Calendar;
import java.util.Date;
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.utils.DateUtils;
/** /**
* Created by root on 19.12.2017. * Created by root on 19.12.2017.

View file

@ -25,7 +25,6 @@ import java.io.File;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import dagger.android.AndroidInjection;
import fr.free.nrw.commons.BuildConfig; import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.CommonsApplication;
import fr.free.nrw.commons.R; import fr.free.nrw.commons.R;

View file

@ -1,7 +1,7 @@
package fr.free.nrw.commons.ui.widget; package fr.free.nrw.commons.ui.widget;
/** /*
* Created by mikel on 07/08/2017. *Created by mikel on 07/08/2017.
*/ */
import android.content.Context; import android.content.Context;
@ -23,6 +23,7 @@ public class CompatTextView extends AppCompatTextView {
/** /**
* Constructs a new instance of CompatTextView * Constructs a new instance of CompatTextView
*
* @param context the view context * @param context the view context
*/ */
public CompatTextView(Context context) { public CompatTextView(Context context) {
@ -32,6 +33,7 @@ public class CompatTextView extends AppCompatTextView {
/** /**
* Constructs a new instance of CompatTextView * Constructs a new instance of CompatTextView
*
* @param context the view context * @param context the view context
* @param attrs the set of attributes for the view * @param attrs the set of attributes for the view
*/ */
@ -42,6 +44,7 @@ public class CompatTextView extends AppCompatTextView {
/** /**
* Constructs a new instance of CompatTextView * Constructs a new instance of CompatTextView
*
* @param context * @param context
* @param attrs * @param attrs
* @param defStyleAttr * @param defStyleAttr
@ -53,6 +56,7 @@ public class CompatTextView extends AppCompatTextView {
/** /**
* initializes the view * initializes the view
*
* @param attrs the attribute set of the view, which can be null * @param attrs the attribute set of the view, which can be null
*/ */
private void init(@Nullable AttributeSet attrs) { private void init(@Nullable AttributeSet attrs) {

View file

@ -68,12 +68,18 @@ public class FileUtils {
final String type = split[0]; final String type = split[0];
Uri contentUri = null; Uri contentUri = null;
if ("image".equals(type)) { switch (type) {
case "image":
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) { break;
case "video":
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) { break;
case "audio":
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
break;
default:
break;
} }
final String selection = "_id=?"; final String selection = "_id=?";
@ -198,6 +204,7 @@ public class FileUtils {
/** /**
* Copy content from source file to destination file. * Copy content from source file to destination file.
*
* @param source stream copied from * @param source stream copied from
* @param destination stream copied to * @param destination stream copied to
* @throws IOException thrown when failing to read source or opening destination file * @throws IOException thrown when failing to read source or opening destination file
@ -211,6 +218,7 @@ public class FileUtils {
/** /**
* Copy content from source file to destination file. * Copy content from source file to destination file.
*
* @param source file descriptor copied from * @param source file descriptor copied from
* @param destination file path copied to * @param destination file path copied to
* @throws IOException thrown when failing to read source or opening destination file * @throws IOException thrown when failing to read source or opening destination file

View file

@ -113,11 +113,11 @@ public class GPSExtractor {
*/ */
@Nullable @Nullable
public String getCoords(boolean useGPS) { public String getCoords(boolean useGPS) {
String latitude = ""; String latitude;
String longitude = ""; String longitude;
String latitude_ref = ""; String latitudeRef;
String longitude_ref = ""; String longitudeRef;
String decimalCoords = ""; String decimalCoords;
//If image has no EXIF data and user has enabled GPS setting, get user's location //If image has no EXIF data and user has enabled GPS setting, get user's location
if (exif == null || exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) == null) { if (exif == null || exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) == null) {
@ -150,15 +150,15 @@ public class GPSExtractor {
Timber.d("EXIF data has location info"); Timber.d("EXIF data has location info");
latitude = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE); latitude = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
latitude_ref = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); latitudeRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
longitude = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE); longitude = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
longitude_ref = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); longitudeRef = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
if (latitude!=null && latitude_ref!=null && longitude!=null && longitude_ref!=null) { if (latitude!=null && latitudeRef!=null && longitude!=null && longitudeRef!=null) {
Timber.d("Latitude: %s %s", latitude, latitude_ref); Timber.d("Latitude: %s %s", latitude, latitudeRef);
Timber.d("Longitude: %s %s", longitude, longitude_ref); Timber.d("Longitude: %s %s", longitude, longitudeRef);
decimalCoords = getDecimalCoords(latitude, latitude_ref, longitude, longitude_ref); decimalCoords = getDecimalCoords(latitude, latitudeRef, longitude, longitudeRef);
return decimalCoords; return decimalCoords;
} else { } else {
return null; return null;

View file

@ -72,12 +72,19 @@ public class ShareActivity
private static final int REQUEST_PERM_ON_SUBMIT_STORAGE = 4; private static final int REQUEST_PERM_ON_SUBMIT_STORAGE = 4;
private CategorizationFragment categorizationFragment; private CategorizationFragment categorizationFragment;
@Inject MediaWikiApi mwApi; @Inject
@Inject CacheController cacheController; MediaWikiApi mwApi;
@Inject SessionManager sessionManager; @Inject
@Inject UploadController uploadController; CacheController cacheController;
@Inject ModifierSequenceDao modifierSequenceDao; @Inject
@Inject @Named("default_preferences") SharedPreferences prefs; SessionManager sessionManager;
@Inject
UploadController uploadController;
@Inject
ModifierSequenceDao modifierSequenceDao;
@Inject
@Named("default_preferences")
SharedPreferences prefs;
private String source; private String source;
private String mimeType; private String mimeType;
@ -216,7 +223,7 @@ public class ShareActivity
//Receive intent from ContributionController.java when user selects picture to upload //Receive intent from ContributionController.java when user selects picture to upload
Intent intent = getIntent(); Intent intent = getIntent();
if (intent.getAction().equals(Intent.ACTION_SEND)) { if (Intent.ACTION_SEND.equals(intent.getAction())) {
mediaUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); mediaUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (intent.hasExtra(UploadService.EXTRA_SOURCE)) { if (intent.hasExtra(UploadService.EXTRA_SOURCE)) {
source = intent.getStringExtra(UploadService.EXTRA_SOURCE); source = intent.getStringExtra(UploadService.EXTRA_SOURCE);

View file

@ -6,6 +6,7 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor; import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask; import android.os.AsyncTask;
@ -49,7 +50,7 @@ public class UploadController {
private ServiceConnection uploadServiceConnection = new ServiceConnection() { private ServiceConnection uploadServiceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName componentName, IBinder binder) { public void onServiceConnected(ComponentName componentName, IBinder binder) {
uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService(); uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService();
isUploadServiceConnected = true; isUploadServiceConnected = true;
} }
@ -81,6 +82,7 @@ public class UploadController {
/** /**
* Starts a new upload task. * Starts a new upload task.
*
* @param title the title of the contribution * @param title the title of the contribution
* @param mediaUri the media URI of the contribution * @param mediaUri the media URI of the contribution
* @param description the description of the contribution * @param description the description of the contribution
@ -106,6 +108,7 @@ public class UploadController {
/** /**
* Starts a new upload task. * Starts a new upload task.
*
* @param contribution the contribution object * @param contribution the contribution object
* @param onComplete the progress tracker * @param onComplete the progress tracker
*/ */
@ -134,9 +137,10 @@ public class UploadController {
ContentResolver contentResolver = context.getContentResolver(); ContentResolver contentResolver = context.getContentResolver();
try { try {
if (contribution.getDataLength() <= 0) { if (contribution.getDataLength() <= 0) {
length = contentResolver AssetFileDescriptor assetFileDescriptor = contentResolver
.openAssetFileDescriptor(contribution.getLocalUri(), "r") .openAssetFileDescriptor(contribution.getLocalUri(), "r");
.getLength(); if (assetFileDescriptor != null) {
length = assetFileDescriptor.getLength();
if (length == -1) { if (length == -1) {
// Let us find out the long way! // Let us find out the long way!
length = countBytes(contentResolver length = countBytes(contentResolver
@ -144,6 +148,7 @@ public class UploadController {
} }
contribution.setDataLength(length); contribution.setDataLength(length);
} }
}
} catch (IOException e) { } catch (IOException e) {
Timber.e(e, "IO Exception: "); Timber.e(e, "IO Exception: ");
} catch (NullPointerException e) { } catch (NullPointerException e) {
@ -152,7 +157,7 @@ public class UploadController {
Timber.e(e, "Security Exception: "); Timber.e(e, "Security Exception: ");
} }
String mimeType = (String)contribution.getTag("mimeType"); String mimeType = (String) contribution.getTag("mimeType");
Boolean imagePrefix = false; Boolean imagePrefix = false;
if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) { if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) {
@ -199,6 +204,7 @@ public class UploadController {
/** /**
* Counts the number of bytes in {@code stream}. * Counts the number of bytes in {@code stream}.
*
* @param stream the stream * @param stream the stream
* @return the number of bytes in {@code stream} * @return the number of bytes in {@code stream}
* @throws IOException if an I/O error occurs * @throws IOException if an I/O error occurs

View file

@ -161,7 +161,7 @@ public class UploadService extends HandlerService<Contribution> {
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_START_SERVICE) && freshStart) { if (ACTION_START_SERVICE.equals(intent.getAction()) && freshStart) {
ContentValues failedValues = new ContentValues(); ContentValues failedValues = new ContentValues();
failedValues.put(ContributionDao.Table.COLUMN_STATE, Contribution.STATE_FAILED); failedValues.put(ContributionDao.Table.COLUMN_STATE, Contribution.STATE_FAILED);

View file

@ -11,7 +11,6 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import fr.free.nrw.commons.CommonsApplication;
import timber.log.Timber; import timber.log.Timber;
public class FileUtils { public class FileUtils {
@ -32,7 +31,7 @@ public class FileUtils {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
buffer.append(line + "\n"); buffer.append(line).append("\n");
} }
} finally { } finally {
if (reader != null) { if (reader != null) {

View file

@ -7,11 +7,6 @@ import android.widget.Toast;
public class ViewUtil { public class ViewUtil {
public static void showLongToast(final Context context, @StringRes final int stringResId) { public static void showLongToast(final Context context, @StringRes final int stringResId) {
ExecutorUtils.uiExecutor().execute(new Runnable() { ExecutorUtils.uiExecutor().execute(() -> Toast.makeText(context, context.getString(stringResId), Toast.LENGTH_LONG).show());
@Override
public void run() {
Toast.makeText(context, context.getString(stringResId), Toast.LENGTH_LONG).show();
}
});
} }
} }

View file

@ -15,7 +15,6 @@ import fr.free.nrw.commons.caching.CacheController;
import fr.free.nrw.commons.data.DBOpenHelper; import fr.free.nrw.commons.data.DBOpenHelper;
import fr.free.nrw.commons.di.CommonsApplicationComponent; import fr.free.nrw.commons.di.CommonsApplicationComponent;
import fr.free.nrw.commons.di.CommonsApplicationModule; import fr.free.nrw.commons.di.CommonsApplicationModule;
import fr.free.nrw.commons.di.DaggerCommonsApplicationComponent;
import fr.free.nrw.commons.location.LocationServiceManager; import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.mwapi.MediaWikiApi; import fr.free.nrw.commons.mwapi.MediaWikiApi;
import fr.free.nrw.commons.nearby.NearbyPlaces; import fr.free.nrw.commons.nearby.NearbyPlaces;