Reformat code

This commit is contained in:
Phillip Thelen 2016-06-21 13:36:51 +02:00
parent 88f343b9d0
commit bbf3728b03
148 changed files with 2136 additions and 2033 deletions

View file

@ -107,15 +107,13 @@ public class APIHelper implements Action1<Throwable> {
// I think we don't need the APIHelper anymore we could just use ApiService
public final ApiService apiService;
final Observable.Transformer apiCallTransformer =
observable -> ((Observable) observable).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(this);
private final GsonConverterFactory gsonConverter;
private final HostConfig hostConfig;
private final Retrofit retrofitAdapter;
final Observable.Transformer apiCallTransformer =
observable -> ((Observable)observable).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(this);
private AlertDialog displayedAlert;
//private OnHabitsAPIResult mResultListener;
@ -186,18 +184,30 @@ public class APIHelper implements Action1<Throwable> {
}
public static GsonConverterFactory createGsonFactory() {
Type taskTagClassListType = new TypeToken<List<TaskTag>>() {}.getType();
Type skillListType = new TypeToken<List<Skill>>() {}.getType();
Type customizationListType = new TypeToken<List<Customization>>() {}.getType();
Type tutorialStepListType = new TypeToken<List<TutorialStep>>() {}.getType();
Type faqArticleListType = new TypeToken<List<FAQArticle>>() {}.getType();
Type itemDataListType = new TypeToken<List<ItemData>>() {}.getType();
Type eggListType = new TypeToken<List<Egg>>() {}.getType();
Type foodListType = new TypeToken<List<Food>>() {}.getType();
Type hatchingPotionListType = new TypeToken<List<HatchingPotion>>() {}.getType();
Type questContentListType = new TypeToken<List<QuestContent>>() {}.getType();
Type petListType = new TypeToken<HashMap<String, Pet>>() {}.getType();
Type mountListType = new TypeToken<HashMap<String, Mount>>() {}.getType();
Type taskTagClassListType = new TypeToken<List<TaskTag>>() {
}.getType();
Type skillListType = new TypeToken<List<Skill>>() {
}.getType();
Type customizationListType = new TypeToken<List<Customization>>() {
}.getType();
Type tutorialStepListType = new TypeToken<List<TutorialStep>>() {
}.getType();
Type faqArticleListType = new TypeToken<List<FAQArticle>>() {
}.getType();
Type itemDataListType = new TypeToken<List<ItemData>>() {
}.getType();
Type eggListType = new TypeToken<List<Egg>>() {
}.getType();
Type foodListType = new TypeToken<List<Food>>() {
}.getType();
Type hatchingPotionListType = new TypeToken<List<HatchingPotion>>() {
}.getType();
Type questContentListType = new TypeToken<List<QuestContent>>() {
}.getType();
Type petListType = new TypeToken<HashMap<String, Pet>>() {
}.getType();
Type mountListType = new TypeToken<HashMap<String, Mount>>() {
}.getType();
//Exclusion strategy needed for DBFlow https://github.com/Raizlabs/DBFlow/issues/121
Gson gson = new GsonBuilder()
@ -258,15 +268,15 @@ public class APIHelper implements Action1<Throwable> {
return this.apiService.connectLocal(auth);
}
public Observable<UserAuthResponse> connectSocial(String userId, String accessToken) {
UserAuthSocial auth = new UserAuthSocial();
auth.setNetwork("facebook");
public Observable<UserAuthResponse> connectSocial(String userId, String accessToken) {
UserAuthSocial auth = new UserAuthSocial();
auth.setNetwork("facebook");
UserAuthSocialTokens authResponse = new UserAuthSocialTokens();
authResponse.setClient_id(userId);
authResponse.setAccess_token(accessToken);
auth.setAuthResponse(authResponse);
return this.apiService.connectSocial(auth);
}
return this.apiService.connectSocial(auth);
}
@Override
public void call(Throwable throwable) {
@ -276,7 +286,7 @@ public class APIHelper implements Action1<Throwable> {
} else if (throwableClass.equals(SocketTimeoutException.class) || throwableClass.equals(UnknownHostException.class)) {
this.showConnectionProblemDialog(R.string.network_error_no_network_body);
} else if (throwableClass.equals(HttpException.class)) {
HttpException error = (HttpException)throwable;
HttpException error = (HttpException) throwable;
retrofit2.Response<?> response = error.response();
ErrorResponse res = null;
@ -291,7 +301,7 @@ public class APIHelper implements Action1<Throwable> {
int status = error.code();
if (status == 401) {
if(res != null && res.message != null && !res.message.isEmpty()) {
if (res != null && res.message != null && !res.message.isEmpty()) {
showConnectionProblemDialog("", res.message);
} else {
showConnectionProblemDialog(R.string.authentication_error_title, R.string.authentication_error_body);
@ -300,7 +310,7 @@ public class APIHelper implements Action1<Throwable> {
} else if (status >= 500 && status < 600) {
this.showConnectionProblemDialog(R.string.internal_error_api);
} else if (status == 400) {
if(res != null && res.message != null && !res.message.isEmpty()) {
if (res != null && res.message != null && !res.message.isEmpty()) {
showConnectionProblemDialog("", res.message);
}
} else {
@ -327,7 +337,7 @@ public class APIHelper implements Action1<Throwable> {
return userObservable;
}
private List<Task> sortTasks(Map<String, Task> taskMap, List<String> taskOrder){
private List<Task> sortTasks(Map<String, Task> taskMap, List<String> taskOrder) {
List<Task> taskList = new ArrayList<>();
int position = 0;
for (String taskId : taskOrder) {
@ -345,10 +355,6 @@ public class APIHelper implements Action1<Throwable> {
return this.hostConfig.getUser() != null;
}
public class ErrorResponse{
public String message;
}
private void showConnectionProblemDialog(final int resourceMessageString) {
showConnectionProblemDialog(R.string.network_error_title, resourceMessageString);
}
@ -360,7 +366,7 @@ public class APIHelper implements Action1<Throwable> {
}
}
private void showConnectionProblemDialog(final String resourceTitleString, final String resourceMessageString){
private void showConnectionProblemDialog(final String resourceTitleString, final String resourceMessageString) {
HabiticaApplication.currentActivity.runOnUiThread(() -> {
if (!(HabiticaApplication.currentActivity).isFinishing() && displayedAlert == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(HabiticaApplication.currentActivity)
@ -380,7 +386,7 @@ public class APIHelper implements Action1<Throwable> {
}
public PurchaseValidationResult validatePurchase(PurchaseValidationRequest request) throws IOException {
Call<PurchaseValidationResult> response = apiService.validatePurchase(request);
Call<PurchaseValidationResult> response = apiService.validatePurchase(request);
return response.execute().body();
}
@ -396,4 +402,8 @@ public class APIHelper implements Action1<Throwable> {
Crashlytics.getInstance().core.setUserName(this.hostConfig.getUser());
Amplitude.getInstance().setUserId(this.hostConfig.getUser());
}
public class ErrorResponse {
public String message;
}
}

View file

@ -18,15 +18,6 @@ import rx.schedulers.Schedulers;
public class ContentCache {
public interface GotContentEntryCallback<T extends Object> {
void GotObject(T obj);
}
public interface QuestContentCallback {
void GotQuest(QuestContent content);
}
private ApiService apiService;
public ContentCache(ApiService apiService) {
@ -120,7 +111,8 @@ public class ContentCache {
break;
}
}
}, throwable -> {});
}, throwable -> {
});
}
private void getContentAndSearchForList(final String typeOfSearch, final List<String> searchKeys, final GotContentEntryCallback<List<ItemData>> gotEntry) {
@ -135,6 +127,15 @@ public class ContentCache {
.filter(item -> searchKeys.contains(item.key))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resultList::add, throwable -> {}, () -> gotEntry.GotObject(resultList));
.subscribe(resultList::add, throwable -> {
}, () -> gotEntry.GotObject(resultList));
}
public interface GotContentEntryCallback<T extends Object> {
void GotObject(T obj);
}
public interface QuestContentCallback {
void GotQuest(QuestContent content);
}
}

View file

@ -50,15 +50,73 @@ public class HabiticaApplication extends MultiDexApplication {
public static HabitRPGUser User;
public static APIHelper ApiHelper;
public static Activity currentActivity = null;
private AppComponent component;
@Inject
Lazy<APIHelper> lazyApiHelper;
private AppComponent component;
/**
* For better performance billing class should be used as singleton
*/
@NonNull
private Billing billing;
/**
* Application wide {@link org.solovyev.android.checkout.Checkout} instance (can be used
* anywhere in the app).
* This instance contains all available products in the app.
*/
@NonNull
private Checkout checkout;
public static HabiticaApplication getInstance(Context context) {
return (HabiticaApplication) context.getApplicationContext();
}
public static boolean exists(@NonNull Context context) {
try {
File dbFile = context.getDatabasePath(String.format("%s.db", HabitDatabase.NAME));
return dbFile.exists();
} catch (Exception exception) {
Log.e("DbExists", "Database %s doesn't exist.", exception);
return false;
}
}
private static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException {
field.setAccessible(true);
field.set(null, newValue);
}
public static void logout(Context context) {
getInstance(context).deleteDatabase(HabitDatabase.NAME);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean use_reminder = preferences.getBoolean("use_reminder", false);
String reminder_time = preferences.getString("reminder_time", "19:00");
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putBoolean("use_reminder", use_reminder);
editor.putString("reminder_time", reminder_time);
editor.apply();
getInstance(context).lazyApiHelper.get().updateAuthenticationCredentials(null, null);
startActivity(LoginActivity.class, context);
}
public static boolean checkUserAuthentication(Context context, HostConfig hostConfig) {
if (hostConfig == null || hostConfig.getApi() == null || hostConfig.getApi().equals("") || hostConfig.getUser() == null || hostConfig.getUser().equals("")) {
startActivity(IntroActivity.class, context);
return false;
}
return true;
}
private static void startActivity(Class activityClass, Context context) {
Intent intent = new Intent(context, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
// region SQLite overrides
@Override
public void onCreate() {
super.onCreate();
@ -136,14 +194,12 @@ public class HabiticaApplication extends MultiDexApplication {
@Override
public void onActivityDestroyed(Activity activity) {
if(currentActivity == activity)
if (currentActivity == activity)
currentActivity = null;
}
});
}
// region SQLite overrides
@Override
public SQLiteDatabase openOrCreateDatabase(String name,
int mode, SQLiteDatabase.CursorFactory factory) {
@ -182,6 +238,10 @@ public class HabiticaApplication extends MultiDexApplication {
return deleted;
}
// endregion
// region IAP - Specific
// Hack for DBFlow - Not deleting Database
// https://github.com/kaeawc/dbflow-sample-app/blob/master/app/src/main/java/io/kaeawc/flow/app/ui/MainActivityFragment.java#L201
private void reflectionHack(@NonNull Context context) {
@ -204,60 +264,11 @@ public class HabiticaApplication extends MultiDexApplication {
}
}
public static boolean exists(@NonNull Context context) {
try {
File dbFile = context.getDatabasePath(String.format("%s.db", HabitDatabase.NAME));
return dbFile.exists();
} catch (Exception exception) {
Log.e("DbExists", "Database %s doesn't exist.", exception);
return false;
}
}
private static void setFinalStatic(Field field, Object newValue) throws NoSuchFieldException, IllegalAccessException {
field.setAccessible(true);
field.set(null, newValue);
}
@Override
public File getDatabasePath(String name) {
return new File(getExternalFilesDir(null), "HabiticaDatabase/" + name);
}
public static void logout(Context context) {
getInstance(context).deleteDatabase(HabitDatabase.NAME);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean use_reminder = preferences.getBoolean("use_reminder", false);
String reminder_time = preferences.getString("reminder_time", "19:00");
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putBoolean("use_reminder", use_reminder);
editor.putString("reminder_time", reminder_time);
editor.apply();
getInstance(context).lazyApiHelper.get().updateAuthenticationCredentials(null, null);
startActivity(LoginActivity.class, context);
}
public static boolean checkUserAuthentication(Context context, HostConfig hostConfig) {
if (hostConfig == null || hostConfig.getApi() == null || hostConfig.getApi().equals("") || hostConfig.getUser() == null || hostConfig.getUser().equals("")) {
startActivity(IntroActivity.class, context);
return false;
}
return true;
}
private static void startActivity(Class activityClass, Context context) {
Intent intent = new Intent(context, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
// endregion
// region IAP - Specific
private void createBillingAndCheckout() {
billing = new Billing(this, new Billing.DefaultConfiguration() {
@NonNull
@ -281,20 +292,6 @@ public class HabiticaApplication extends MultiDexApplication {
checkout = Checkout.forApplication(billing, Products.create().add(ProductTypes.IN_APP, Arrays.asList(Purchase20Gems)));
}
/**
* For better performance billing class should be used as singleton
*/
@NonNull
private Billing billing;
/**
* Application wide {@link org.solovyev.android.checkout.Checkout} instance (can be used anywhere in the app).
* This instance contains all available products in the app.
*/
@NonNull
private Checkout checkout;
@NonNull
public Checkout getCheckout() {
return checkout;

View file

@ -23,8 +23,8 @@ import java.util.Set;
*/
public class HabiticaPurchaseVerifier extends BasePurchaseVerifier {
private Set<String> purchasedOrderList = new HashSet<>();
private static final String PURCHASED_PRODUCTS_KEY = "PURCHASED_PRODUCTS";
private Set<String> purchasedOrderList = new HashSet<>();
private SharedPreferences preferences;
public HabiticaPurchaseVerifier(Context context) {

View file

@ -7,6 +7,7 @@ import android.preference.PreferenceManager;
/**
* The configuration of the host<br />
* Currently, the Port isn't used at all.
*
* @author MagicMicky
*/
public class HostConfig {
@ -25,10 +26,11 @@ public class HostConfig {
/**
* Create a new HostConfig
*
* @param address the address of the server
* @param port the port of the server
* @param api the API token of the user
* @param user the user ID
* @param port the port of the server
* @param api the API token of the user
* @param user the user ID
*/
public HostConfig(String address, String port, String api, String user) {
this.setAddress(address);

View file

@ -48,7 +48,7 @@ public class NotificationPublisher extends BroadcastReceiver {
}
}
if (show_notification) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
@ -77,9 +77,9 @@ public class NotificationPublisher extends BroadcastReceiver {
builder.setColor(ContextCompat.getColor(context, R.color.brand_300));
}
if (currentapiVersion >= Build.VERSION_CODES.JELLY_BEAN){
if (currentapiVersion >= Build.VERSION_CODES.JELLY_BEAN) {
notification = builder.build();
} else{
} else {
notification = builder.getNotification();
}
notification.defaults |= Notification.DEFAULT_LIGHTS;

View file

@ -4,7 +4,8 @@ import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser;
import rx.functions.Action1;
/**r
/**
* r
* Created by magicmicky on 18/02/15.
*/
public class HabitRPGUserCallback implements Action1<HabitRPGUser> {

View file

@ -33,7 +33,7 @@ public class TaskScoringCallback implements Action1<TaskDirectionData> {
.querySingle(new TransactionListener<Task>() {
@Override
public void onResultReceived(Task task) {
if(task != null && task.type != null && !task.type.equals("reward")) {
if (task != null && task.type != null && !task.type.equals("reward")) {
task.value = task.value + taskDirectionData.getDelta();
task.save();
@ -76,8 +76,8 @@ public class TaskScoringCallback implements Action1<TaskDirectionData> {
@Override
public void onResultReceived(Object result) {
if (result != null) {
Item item = (Item)result;
item.setOwned(item.getOwned()+1);
Item item = (Item) result;
item.setOwned(item.getOwned() + 1);
item.save();
}
}

View file

@ -16,10 +16,6 @@ public class TagsHelper {
}
public void setTags(List<String> tagsId) {
this.tagsId = tagsId;
}
public void addTags(String tags) {
this.tagsId.add(tags);
}
@ -32,6 +28,10 @@ public class TagsHelper {
return this.tagsId;
}
public void setTags(List<String> tagsId) {
this.tagsId = tagsId;
}
public boolean isTagChecked(String tagID) {
return this.tagsId.contains(tagID);
}

View file

@ -29,17 +29,20 @@ public class AppModule {
return application;
}
@Provides @Singleton
@Provides
@Singleton
public SharedPreferences provideSharedPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
@Provides @Named("UserID")
@Provides
@Named("UserID")
public String providesUserID(SharedPreferences sharedPreferences) {
return sharedPreferences.getString(application.getString(R.string.SP_userID), null);
}
@Provides @Singleton
@Provides
@Singleton
public TagsHelper providesTagsHelper() {
return new TagsHelper();
}

View file

@ -8,6 +8,13 @@ import android.util.AttributeSet;
public class TimePreference extends DialogPreference {
private String timeval;
public TimePreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
public static int getHour(String timeval) {
String[] pieces = timeval.split(":");
return (Integer.parseInt(pieces[0]));
@ -18,14 +25,6 @@ public class TimePreference extends DialogPreference {
return (Integer.parseInt(pieces[1]));
}
public TimePreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return (a.getString(index));
@ -47,6 +46,18 @@ public class TimePreference extends DialogPreference {
setSummary(timeval);
}
public int getLastHour() {
return getHour(timeval);
}
public int getLastMinute() {
return getMinute(timeval);
}
public String getText() {
return timeval;
}
public void setText(String text) {
final boolean wasBlocking = shouldDisableDependents();
@ -59,16 +70,4 @@ public class TimePreference extends DialogPreference {
notifyDependencyChange(isBlocking);
}
}
public int getLastHour() {
return getHour(timeval);
}
public int getLastMinute() {
return getMinute(timeval);
}
public String getText() {
return timeval;
}
}

View file

@ -34,24 +34,29 @@ import java.util.List;
import java.util.Map;
/**
* <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
* way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
* <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is
* a simple
* way to invoke barcode scanning and receive the result, without any need to integrate, modify, or
* learn the
* project's source code.</p>
* <p/>
* <h2>Initiating a barcode scan</h2>
* <p/>
* <p>To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
* <p>To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()}
* and wait
* for the result in your app.</p>
* <p/>
* <p>It does require that the Barcode Scanner (or work-alike) application is installed. The
* {@link #initiateScan()} method will prompt the user to download the application, if needed.</p>
* <p/>
* <p>There are a few steps to using this integration. First, your {@link Activity} must implement
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p>
* the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like
* this:</p>
* <p/>
* <pre>{@code
* public void onActivityResult(int requestCode, int resultCode, Intent intent) {
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
* IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode,
* intent);
* if (scanResult != null) {
* // handle scan result
* }
@ -70,31 +75,42 @@ import java.util.Map;
* }</pre>
* <p/>
* <p>Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
* user was prompted to download the application. This lets the calling app potentially manage the dialog.
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
* user was prompted to download the application. This lets the calling app potentially manage the
* dialog.
* In particular, ideally, the app dismisses the dialog if it's still active in its {@link
* Activity#onPause()}
* method.</p>
* <p/>
* <p>You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
* <p>You can use {@link #setTitle(String)} to customize the title of this download prompt dialog
* (or, use
* {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message,
* and
* yes/no button labels can be changed.</p>
* <p/>
* <p>Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
* <p>Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent
* used
* to invoke the scanner. This can be used to set additional options not directly exposed by this
* simplified API.</p>
* <p/>
* <p>By default, this will only allow applications that are known to respond to this intent correctly
* do so. The apps that are allowed to response can be set with {@link #setTargetApplications(List)}.
* For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.</p>
* <p>By default, this will only allow applications that are known to respond to this intent
* correctly
* do so. The apps that are allowed to response can be set with {@link
* #setTargetApplications(List)}.
* For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app
* itself.</p>
* <p/>
* <h2>Sharing text via barcode</h2>
* <p/>
* <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.</p>
* <p>To share text, encoded as a QR Code on-screen, similarly, see {@link
* #shareText(CharSequence)}.</p>
* <p/>
* <p>Some code, particularly download integration, was contributed from the Anobiit application.</p>
* <p>Some code, particularly download integration, was contributed from the Anobiit
* application.</p>
* <p/>
* <h2>Enabling experimental barcode formats</h2>
* <p/>
* <p>Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such as
* <p>Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such
* as
* PDF417. Use {@link #initiateScan(java.util.Collection)} with
* a collection containing the names of formats to scan for explicitly, like "PDF_417", to use such
* formats.</p>
@ -108,17 +124,11 @@ import java.util.Map;
public class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
@ -126,10 +136,11 @@ public class IntentIntegrator {
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
private static final String TAG = IntentIntegrator.class.getSimpleName();
private static final String BS_PACKAGE = "com.google.zxing.client.android";
public static final List<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE);
private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
public static final List<String> TARGET_ALL_KNOWN = list(
BS_PACKAGE, // Barcode Scanner
BSPLUS_PACKAGE, // Barcode Scanner+
@ -138,12 +149,12 @@ public class IntentIntegrator {
);
private final Activity activity;
private final Map<String, Object> moreExtras;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private List<String> targetApplications;
private final Map<String, Object> moreExtras;
public IntentIntegrator(Activity activity) {
this.activity = activity;
@ -155,6 +166,39 @@ public class IntentIntegrator {
moreExtras = new HashMap<String, Object>(3);
}
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled
* scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
public String getTitle() {
return title;
}
@ -318,36 +362,6 @@ public class IntentIntegrator {
return downloadDialog.show();
}
/**
* <p>Call this from your {@link Activity}'s
* {@link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* @return null if the event handled here was not related to this class, or
* else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Defaults to type "TEXT_TYPE".
*
@ -362,7 +376,8 @@ public class IntentIntegrator {
* scan the text off the screen of the device.
*
* @param text the text string to encode as a barcode
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type}
* constants.
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
* if a prompt was needed, or null otherwise
*/
@ -384,10 +399,6 @@ public class IntentIntegrator {
return null;
}
private static List<String> list(String... values) {
return Collections.unmodifiableList(Arrays.asList(values));
}
private void attachMoreExtras(Intent intent) {
for (Map.Entry<String, Object> entry : moreExtras.entrySet()) {
String key = entry.getKey();

View file

@ -52,7 +52,8 @@ public final class IntentResult {
}
/**
* @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
* @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format
* names.
*/
public String getFormatName() {
return formatName;

View file

@ -15,7 +15,7 @@ import android.os.Bundle;
/**
* Created by keithholliday on 5/29/16.
*/
public class TaskReceiver extends BroadcastReceiver {
public class TaskReceiver extends BroadcastReceiver {
private Context context;

View file

@ -69,6 +69,27 @@ public class AvatarWithBarsViewModel implements View.OnClickListener {
gemsText.setOnClickListener(this);
}
public static void setHpBarData(ValueBarBinding valueBar, Stats stats, Context ctx) {
Integer maxHP = stats.getMaxHealth();
if (maxHP == null || maxHP == 0) {
maxHP = 50;
}
setValueBar(valueBar, (float) Math.ceil(stats.getHp().floatValue()), maxHP, ctx.getString(R.string.HP_default), ContextCompat.getColor(ctx, R.color.hpColor), R.drawable.ic_header_heart);
}
// Layout_Weight don't accepts 0.7/0.3 to have 70% filled instead it shows the 30% , so I had to switch the values
// but on a 1.0/0.0 which switches to 0.0/1.0 it shows the blank part full size...
private static void setValueBar(ValueBarBinding valueBar, float value, float valueMax, String description, int color, int icon) {
double percent = Math.min(1, value / valueMax);
valueBar.setWeightToShow((float) percent);
valueBar.setText((int) value + "/" + (int) valueMax);
valueBar.setDescription(description);
valueBar.setBarForegroundColor(color);
valueBar.icHeader.setImageResource(icon);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void updateData(HabitRPGUser user) {
userObject = user;
@ -132,16 +153,7 @@ public class AvatarWithBarsViewModel implements View.OnClickListener {
gemsText.setText(String.valueOf(gems.intValue()));
}
public static void setHpBarData(ValueBarBinding valueBar, Stats stats, Context ctx) {
Integer maxHP = stats.getMaxHealth();
if (maxHP == null || maxHP == 0) {
maxHP = 50;
}
setValueBar(valueBar, (float) Math.ceil(stats.getHp().floatValue()), maxHP, ctx.getString(R.string.HP_default), ContextCompat.getColor(ctx, R.color.hpColor), R.drawable.ic_header_heart);
}
public void setHpBarData(float value, int valueMax){
public void setHpBarData(float value, int valueMax) {
if (valueMax == 0) {
valueMax = cachedMaxHealth;
} else {
@ -150,7 +162,7 @@ public class AvatarWithBarsViewModel implements View.OnClickListener {
setValueBar(hpBar, (float) Math.ceil(value), valueMax, context.getString(R.string.HP_default), ContextCompat.getColor(context, R.color.hpColor), R.drawable.ic_header_heart);
}
public void setXpBarData(float value, int valueMax){
public void setXpBarData(float value, int valueMax) {
if (valueMax == 0) {
valueMax = cachedMaxExp;
} else {
@ -159,7 +171,7 @@ public class AvatarWithBarsViewModel implements View.OnClickListener {
setValueBar(xpBar, (float) Math.floor(value), valueMax, context.getString(R.string.XP_default), ContextCompat.getColor(context, R.color.xpColor), R.drawable.ic_header_exp);
}
public void setMpBarData(float value, int valueMax){
public void setMpBarData(float value, int valueMax) {
if (valueMax == 0) {
valueMax = cachedMaxMana;
} else {
@ -168,20 +180,8 @@ public class AvatarWithBarsViewModel implements View.OnClickListener {
setValueBar(mpBar, (float) Math.floor(value), valueMax, context.getString(R.string.MP_default), ContextCompat.getColor(context, R.color.mpColor), R.drawable.ic_header_magic);
}
// Layout_Weight don't accepts 0.7/0.3 to have 70% filled instead it shows the 30% , so I had to switch the values
// but on a 1.0/0.0 which switches to 0.0/1.0 it shows the blank part full size...
private static void setValueBar(ValueBarBinding valueBar, float value, float valueMax, String description, int color, int icon) {
double percent = Math.min(1, value / valueMax);
valueBar.setWeightToShow((float) percent);
valueBar.setText((int) value + "/" + (int) valueMax);
valueBar.setDescription(description);
valueBar.setBarForegroundColor(color);
valueBar.icHeader.setImageResource(icon);
}
@Subscribe
public void onEvent(BoughtGemsEvent gemsEvent){
public void onEvent(BoughtGemsEvent gemsEvent) {
Double gems = userObject.getBalance() * 4;
gems += gemsEvent.NewGemsToAdd;
gemsText.setText(String.valueOf(gems.intValue()));

View file

@ -16,24 +16,20 @@ import butterknife.ButterKnife;
public class TutorialView extends FrameLayout implements View.OnClickListener {
public TutorialStep step;
public OnTutorialReaction onReaction;
@BindView(R.id.tutorialTextView)
TextView tutorialTextView;
@BindView(R.id.background)
RelativeLayout background;
@BindView(R.id.dismissButton)
Button dismissButton;
@BindView(R.id.completeButton)
Button completeButton;
public TutorialStep step;
public OnTutorialReaction onReaction;
public TutorialView(Context context, TutorialStep step, OnTutorialReaction onReaction) {
super(context);
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mInflater.inflate(R.layout.overlay_tutorial, this, true);
ButterKnife.bind(this);
background.setOnClickListener(this);
@ -51,7 +47,7 @@ public class TutorialView extends FrameLayout implements View.OnClickListener {
public void onClick(View v) {
if (v == background || v == completeButton) {
this.onReaction.onTutorialCompleted(this.step);
} else if (v == dismissButton){
} else if (v == dismissButton) {
this.onReaction.onTutorialDeferred(this.step);
}
}

View file

@ -71,6 +71,7 @@ public class AboutActivity extends BaseActivity {
tabLayout.setupWithViewPager(pager);
}
@Override
protected void injectActivity(AppComponent component) {
component.inject(this);

View file

@ -12,11 +12,11 @@ import butterknife.ButterKnife;
public abstract class BaseActivity extends AppCompatActivity {
protected abstract int getLayoutResId();
private boolean destroyed;
public boolean isDestroyed(){
protected abstract int getLayoutResId();
public boolean isDestroyed() {
return destroyed;
}
@ -52,6 +52,6 @@ public abstract class BaseActivity extends AppCompatActivity {
}
public HabiticaApplication getHabiticaApplication() {
return (HabiticaApplication)getApplication();
return (HabiticaApplication) getApplication();
}
}

View file

@ -103,8 +103,9 @@ public class ClassSelectionActivity extends BaseActivity implements Action1<Habi
apiHelper.apiService.changeClass()
.compose(apiHelper.configureApiCallObserver())
.subscribe(user -> {
classWasUnset = true;
}, throwable -> {});
classWasUnset = true;
}, throwable -> {
});
}
}
@ -179,7 +180,8 @@ public class ClassSelectionActivity extends BaseActivity implements Action1<Habi
this.displayProgressDialog();
apiHelper.apiService.disableClasses()
.compose(apiHelper.configureApiCallObserver())
.subscribe(this, throwable -> {});
.subscribe(this, throwable -> {
});
}
private void selectClass(String selectedClass) {
@ -187,7 +189,8 @@ public class ClassSelectionActivity extends BaseActivity implements Action1<Habi
this.displayProgressDialog();
apiHelper.apiService.changeClass(selectedClass)
.compose(apiHelper.configureApiCallObserver())
.subscribe(this, throwable -> {});
.subscribe(this, throwable -> {
});
}
private void displayProgressDialog() {

View file

@ -170,40 +170,6 @@ public class GroupFormActivity extends BaseActivity {
}
}
private class emojiClickListener implements View.OnClickListener {
EmojiEditText view;
public emojiClickListener(EmojiEditText view) {
this.view = view;
}
@Override
public void onClick(View v) {
if(!popup.isShowing()){
if(popup.isKeyBoardOpen()){
popup.showAtBottom();
changeEmojiKeyboardIcon(true);
}
else{
view.setFocusableInTouchMode(true);
view.requestFocus();
popup.showAtBottomPending();
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
changeEmojiKeyboardIcon(true);
}
}
else{
popup.dismiss();
changeEmojiKeyboardIcon(false);
}
}
}
@Override
public boolean onSupportNavigateUp() {
finish();
@ -220,7 +186,7 @@ public class GroupFormActivity extends BaseActivity {
private void finishActivitySuccessfuly() {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("name",this.groupNameEditText.getText().toString());
bundle.putString("name", this.groupNameEditText.getText().toString());
bundle.putString("description", MarkdownParser.parseCompiled(this.groupDescriptionEditText.getText()));
bundle.putString("leader", this.groupLeader);
resultIntent.putExtras(bundle);
@ -228,4 +194,34 @@ public class GroupFormActivity extends BaseActivity {
finish();
UiUtils.dismissKeyboard(this);
}
private class emojiClickListener implements View.OnClickListener {
EmojiEditText view;
public emojiClickListener(EmojiEditText view) {
this.view = view;
}
@Override
public void onClick(View v) {
if (!popup.isShowing()) {
if (popup.isKeyBoardOpen()) {
popup.showAtBottom();
changeEmojiKeyboardIcon(true);
} else {
view.setFocusableInTouchMode(true);
view.requestFocus();
popup.showAtBottomPending();
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
changeEmojiKeyboardIcon(true);
}
} else {
popup.dismiss();
changeEmojiKeyboardIcon(false);
}
}
}
}

View file

@ -21,20 +21,16 @@ import butterknife.BindView;
public class IntroActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {
@BindView(R.id.view_pager)
ViewPager pager;
@BindView(R.id.view_pager_indicator)
CirclePageIndicator indicator;
@BindView(R.id.skipButton)
Button skipButton;
@BindView(R.id.finishButton)
Button finishButton;
@Inject
public APIHelper apiHelper;
@BindView(R.id.view_pager)
ViewPager pager;
@BindView(R.id.view_pager_indicator)
CirclePageIndicator indicator;
@BindView(R.id.skipButton)
Button skipButton;
@BindView(R.id.finishButton)
Button finishButton;
@Override
protected int getLayoutResId() {
@ -55,7 +51,9 @@ public class IntroActivity extends BaseActivity implements View.OnClickListener,
apiHelper.apiService.getContent()
.compose(apiHelper.configureApiCallObserver())
.subscribe(contentResult -> {}, throwable -> {});
.subscribe(contentResult -> {
}, throwable -> {
});
}
@Override

View file

@ -50,51 +50,89 @@ import rx.functions.Action1;
* @author Mickael Goubin
*/
public class LoginActivity extends BaseActivity
implements Action1<UserAuthResponse>, HabitRPGUserCallback.OnUserReceived {
private final static String TAG_ADDRESS="address";
private final static String TAG_USERID="user";
private final static String TAG_APIKEY="key";
implements Action1<UserAuthResponse>, HabitRPGUserCallback.OnUserReceived {
private final static String TAG_ADDRESS = "address";
private final static String TAG_USERID = "user";
private final static String TAG_APIKEY = "key";
@Inject
public APIHelper apiHelper;
public APIHelper apiHelper;
@Inject
public SharedPreferences sharedPrefs;
public String mTmpUserToken;
public String mTmpApiToken;
public Boolean isRegistering;
private Menu menu;
private CallbackManager callbackManager;
@BindView(R.id.login_btn)
Button mLoginNormalBtn;
@BindView(R.id.PB_AsyncTask)
ProgressBar mProgressBar;
public String mTmpUserToken;
public String mTmpApiToken;
public Boolean isRegistering;
@BindView(R.id.login_btn)
Button mLoginNormalBtn;
@BindView(R.id.PB_AsyncTask)
ProgressBar mProgressBar;
@BindView(R.id.username)
EditText mUsernameET;
@BindView(R.id.password)
EditText mPasswordET;
@BindView(R.id.email)
EditText mEmail;
@BindView(R.id.confirm_password)
EditText mConfirmPassword;
@BindView(R.id.email_row)
TableRow mEmailRow;
@BindView(R.id.confirm_password_row)
TableRow mConfirmPasswordRow;
@BindView(R.id.login_button)
LoginButton mFacebookLoginBtn;
@BindView(R.id.forgot_pw_tv)
TextView mForgotPWTV;
private Menu menu;
private CallbackManager callbackManager;
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
if (isRegistering) {
String username, email, password, cpassword;
username = String.valueOf(mUsernameET.getText()).trim();
email = String.valueOf(mEmail.getText()).trim();
password = String.valueOf(mPasswordET.getText());
cpassword = String.valueOf(mConfirmPassword.getText());
if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
apiHelper.registerUser(username, email, password, cpassword)
.compose(apiHelper.configureApiCallObserver())
.subscribe(LoginActivity.this, throwable -> {
hideProgress();
});
} else {
String username, password;
username = String.valueOf(mUsernameET.getText()).trim();
password = String.valueOf(mPasswordET.getText());
if (username.length() == 0 || password.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
apiHelper.connectUser(username, password)
.compose(apiHelper.configureApiCallObserver())
.subscribe(LoginActivity.this, throwable -> {
hideProgress();
});
}
}
};
private View.OnClickListener mForgotPWClick = v -> {
String url = BuildConfig.BASE_URL;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
};
public static void show(final View v) {
v.setVisibility(View.VISIBLE);
}
public static void hide(final View v) {
v.setVisibility(View.GONE);
}
@Override
protected int getLayoutResId() {
@ -102,16 +140,16 @@ public class LoginActivity extends BaseActivity
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
//Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false);
ButterKnife.bind(this);
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
mFacebookLoginBtn.setReadPermissions("user_friends");
mFacebookLoginBtn.setReadPermissions("user_friends");
mForgotPWTV.setOnClickListener(mForgotPWClick);
SpannableString content = new SpannableString(mForgotPWTV.getText());
@ -121,12 +159,14 @@ public class LoginActivity extends BaseActivity
callbackManager = CallbackManager.Factory.create();
mFacebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
apiHelper.connectSocial(accessToken.getUserId(), accessToken.getToken())
.compose(apiHelper.configureApiCallObserver())
.subscribe(LoginActivity.this, throwable -> {hideProgress();});
.subscribe(LoginActivity.this, throwable -> {
hideProgress();
});
}
@Override
@ -134,11 +174,11 @@ public class LoginActivity extends BaseActivity
Log.d("FB Login", "Cancelled");
}
@Override
public void onError(FacebookException exception) {
@Override
public void onError(FacebookException exception) {
Log.e("FB Login", "Error", exception);
}
});
}
});
this.isRegistering = true;
@ -159,7 +199,7 @@ public class LoginActivity extends BaseActivity
}
private void resetLayout() {
if (this.isRegistering) {
if (this.isRegistering) {
if (this.mEmailRow.getVisibility() == View.GONE) {
show(this.mEmailRow);
}
@ -174,61 +214,13 @@ public class LoginActivity extends BaseActivity
hide(this.mConfirmPasswordRow);
}
}
}
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
if (isRegistering) {
String username, email,password,cpassword;
username = String.valueOf(mUsernameET.getText()).trim();
email = String.valueOf(mEmail.getText()).trim();
password = String.valueOf(mPasswordET.getText());
cpassword = String.valueOf(mConfirmPassword.getText());
if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
apiHelper.registerUser(username,email,password, cpassword)
.compose(apiHelper.configureApiCallObserver())
.subscribe(LoginActivity.this, throwable -> {hideProgress();});
} else {
String username,password;
username = String.valueOf(mUsernameET.getText()).trim();
password = String.valueOf(mPasswordET.getText());
if (username.length() == 0 || password.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
apiHelper.connectUser(username,password)
.compose(apiHelper.configureApiCallObserver())
.subscribe(LoginActivity.this, throwable -> {hideProgress();});
}
}
};
private View.OnClickListener mForgotPWClick = v -> {
String url = BuildConfig.BASE_URL;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
};
public static void show(final View v) {
v.setVisibility(View.VISIBLE);
}
public static void hide(final View v) {
v.setVisibility(View.GONE);
}
private void startMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
private void startMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void startSetupActivity() {
@ -241,9 +233,9 @@ startActivity(i);
private void toggleRegistering() {
this.isRegistering = !this.isRegistering;
this.setRegistering();
}
}
private void setRegistering() {
private void setRegistering() {
MenuItem menuItem = menu.findItem(R.id.action_toggleRegistering);
if (this.isRegistering) {
this.mLoginNormalBtn.setText(getString(R.string.register_btn));
@ -257,77 +249,77 @@ startActivity(i);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_DONE);
}
this.resetLayout();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
callbackManager.onActivityResult(requestCode, resultCode, intent);
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
try {
Log.d("scanresult", scanResult.getContents());
this.parse(scanResult.getContents());
} catch(Exception e) {
Log.e("scanresult", "Could not parse scanResult", e);
}
}
}
if (scanResult != null) {
try {
Log.d("scanresult", scanResult.getContents());
this.parse(scanResult.getContents());
} catch (Exception e) {
Log.e("scanresult", "Could not parse scanResult", e);
}
}
}
private void parse(String contents) {
String adr,user,key;
try {
JSONObject obj;
private void parse(String contents) {
String adr, user, key;
try {
JSONObject obj;
obj = new JSONObject(contents);
adr = obj.getString(TAG_ADDRESS);
user = obj.getString(TAG_USERID);
key = obj.getString(TAG_APIKEY);
Log.d("", "adr" + adr + " user:" + user + " key" + key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_address), adr)
.putString(getString(R.string.SP_APIToken), key)
.putString(getString(R.string.SP_userID), user)
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
startMainActivity();
} catch (JSONException e) {
showSnackbar(getString(R.string.ERR_pb_barcode));
e.printStackTrace();
} catch(Exception e) {
if("PB_string_commit".equals(e.getMessage())) {
showSnackbar(getString(R.string.ERR_pb_barcode));
}
}
}
obj = new JSONObject(contents);
adr = obj.getString(TAG_ADDRESS);
user = obj.getString(TAG_USERID);
key = obj.getString(TAG_APIKEY);
Log.d("", "adr" + adr + " user:" + user + " key" + key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_address), adr)
.putString(getString(R.string.SP_APIToken), key)
.putString(getString(R.string.SP_userID), user)
.commit();
if (!ans) {
throw new Exception("PB_string_commit");
}
startMainActivity();
} catch (JSONException e) {
showSnackbar(getString(R.string.ERR_pb_barcode));
e.printStackTrace();
} catch (Exception e) {
if ("PB_string_commit".equals(e.getMessage())) {
showSnackbar(getString(R.string.ERR_pb_barcode));
}
}
}
private void showSnackbar(String content)
{
Snackbar snackbar = Snackbar
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
private void showSnackbar(String content) {
Snackbar snackbar = Snackbar
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
snackbar.show(); // Dont forget to show!
}
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
snackbar.show(); // Dont forget to show!
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_toggleRegistering:
toggleRegistering();
break;
}
return super.onOptionsItemSelected(item);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_toggleRegistering:
toggleRegistering();
break;
}
return super.onOptionsItemSelected(item);
}
private void saveTokens(String api, String user) throws Exception {
this.apiHelper.updateAuthenticationCredentials(user, api);
@ -335,7 +327,7 @@ startActivity(i);
boolean ans = editor.putString(getString(R.string.SP_APIToken), api)
.putString(getString(R.string.SP_userID), user)
.commit();
if(!ans) {
if (!ans) {
throw new Exception("PB_string_commit");
}
}
@ -354,16 +346,16 @@ startActivity(i);
mProgressBar.setVisibility(View.GONE);
}
private void showValidationError(int resourceMessageString) {
mProgressBar.setVisibility(View.GONE);
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.login_validation_error_title)
.setMessage(resourceMessageString)
.setNeutralButton(android.R.string.ok, (dialog, which) -> {
})
.setIcon(R.drawable.ic_warning_black)
.show();
}
private void showValidationError(int resourceMessageString) {
mProgressBar.setVisibility(View.GONE);
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.login_validation_error_title)
.setMessage(resourceMessageString)
.setNeutralButton(android.R.string.ok, (dialog, which) -> {
})
.setIcon(R.drawable.ic_warning_black)
.show();
}
@Override
public void call(UserAuthResponse userAuthResponse) {

View file

@ -142,9 +142,17 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
TaskScoringCallback.OnTaskScored,
GemsPurchaseFragment.Listener, TutorialView.OnTutorialReaction {
private static final int MIN_LEVEL_FOR_SKILLS = 11;
public static final int SELECT_CLASS_RESULT = 11;
private static final int MIN_LEVEL_FOR_SKILLS = 11;
// Checkout needs to be in the Activity..
public ActivityCheckout checkout = null;
@Inject
public APIHelper apiHelper;
@Inject
public MaintenanceApiService maintenanceService;
public HabitRPGUser user;
@Inject
protected HostConfig hostConfig;
@BindView(R.id.floating_menu_wrapper)
FrameLayout floatingMenuWrapper;
@BindView(R.id.toolbar)
@ -155,20 +163,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
View avatar_with_bars;
@BindView(R.id.overlayFrameLayout)
FrameLayout overlayFrameLayout;
// Checkout needs to be in the Activity..
public ActivityCheckout checkout = null;
private Drawer drawer;
private Drawer filterDrawer;
@Inject
protected HostConfig hostConfig;
@Inject
public APIHelper apiHelper;
@Inject
public MaintenanceApiService maintenanceService;
public HabitRPGUser user;
private AccountHeader accountHeader;
private BaseMainFragment activeFragment;
private AvatarWithBarsViewModel avatarInHeader;
@ -181,6 +177,27 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
private TutorialView activeTutorialView;
private boolean isloadingContent;
private TransactionListener<HabitRPGUser> userTransactionListener = new TransactionListener<HabitRPGUser>() {
@Override
public void onResultReceived(HabitRPGUser habitRPGUser) {
MainActivity.this.user = habitRPGUser;
MainActivity.this.setUserData(true);
}
@Override
public boolean onReady(BaseTransaction<HabitRPGUser> baseTransaction) {
return true;
}
@Override
public boolean hasResult(BaseTransaction<HabitRPGUser> baseTransaction, HabitRPGUser habitRPGUser) {
return true;
}
};
static public Double round(Double value, int n) {
return (Math.round(value * Math.pow(10, n))) / (Math.pow(10, n));
}
@Override
protected int getLayoutResId() {
@ -235,7 +252,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
if (this.apiHelper != null && this.apiHelper.hasAuthenticationKeys()) {
this.apiHelper.retrieveUser(true)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new HabitRPGUserCallback(this), throwable -> {});
.subscribe(new HabitRPGUserCallback(this), throwable -> {
});
this.checkMaintenance();
}
}
@ -298,24 +316,6 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
}
}
private TransactionListener<HabitRPGUser> userTransactionListener = new TransactionListener<HabitRPGUser>() {
@Override
public void onResultReceived(HabitRPGUser habitRPGUser) {
MainActivity.this.user = habitRPGUser;
MainActivity.this.setUserData(true);
}
@Override
public boolean onReady(BaseTransaction<HabitRPGUser> baseTransaction) {
return true;
}
@Override
public boolean hasResult(BaseTransaction<HabitRPGUser> baseTransaction, HabitRPGUser habitRPGUser) {
return true;
}
};
private void setUserData(boolean fromLocalDb) {
if (user != null) {
Calendar calendar = new GregorianCalendar();
@ -325,7 +325,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
Map<String, Object> updateData = new HashMap<>();
updateData.put("preferences.timezoneOffset", String.valueOf(offset));
apiHelper.apiService.updateUser(updateData).compose(apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(this, user), throwable -> {});
.subscribe(new MergeUserCallback(this, user), throwable -> {
});
}
runOnUiThread(() -> {
updateHeader();
@ -607,6 +608,7 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
}
return updates;
}
private List<ItemData> updateOwnedData(HashMap<String, Boolean> ownedMapping) {
List<ItemData> updates = new ArrayList<>();
if (ownedMapping == null) {
@ -614,7 +616,7 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
}
List<ItemData> items = new Select().from(ItemData.class).queryList();
for (ItemData item : items) {
if (ownedMapping.containsKey(item.key) && item.owned != ownedMapping.get(item.key) ) {
if (ownedMapping.containsKey(item.key) && item.owned != ownedMapping.get(item.key)) {
item.owned = ownedMapping.get(item.key);
updates.add(item);
} else if (!ownedMapping.containsKey(item.key) && item.owned != null) {
@ -715,7 +717,6 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
@ -724,11 +725,14 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
if (this.apiHelper != null) {
this.apiHelper.retrieveUser(true)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new HabitRPGUserCallback(this), throwable -> {});
.subscribe(new HabitRPGUserCallback(this), throwable -> {
});
}
}
}
// region Events
@Override
public void onDestroy() {
if (checkout != null) {
@ -739,8 +743,6 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
super.onDestroy();
}
// region Events
@Subscribe
public void onEvent(ToggledInnStateEvent evt) {
avatarInHeader.updateData(user);
@ -749,14 +751,16 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
@Subscribe
public void onEvent(UpdateUserCommand event) {
apiHelper.apiService.updateUser(event.updateData).compose(apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(this, user), throwable -> {});
.subscribe(new MergeUserCallback(this, user), throwable -> {
});
}
@Subscribe
public void onEvent(EquipCommand event) {
this.apiHelper.apiService.equipItem(event.type, event.key)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new ItemsCallback(this, this.user), throwable -> {});
.subscribe(new ItemsCallback(this, this.user), throwable -> {
});
}
@Subscribe
@ -765,7 +769,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
this.setUserData(false);
apiHelper.apiService.unlockPath(event.path)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new UnlockCallback(this, this.user), throwable -> {});
.subscribe(new UnlockCallback(this, this.user), throwable -> {
});
}
@Subscribe
@ -832,12 +837,14 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
MainActivity.this.setUserData(true);
showSnackbar(MainActivity.this, floatingMenuWrapper, snackbarMessage, SnackbarDisplayType.NORMAL);
}, throwable -> {});
}, throwable -> {
});
} else {
// user created Rewards
apiHelper.apiService.postTaskDirection(rewardKey, TaskDirection.down.toString())
.compose(apiHelper.configureApiCallObserver())
.subscribe(new TaskScoringCallback(this, rewardKey), throwable -> {});
.subscribe(new TaskScoringCallback(this, rewardKey), throwable -> {
});
}
//Update the users gold
@ -854,7 +861,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
apiHelper.apiService.deleteTask(cmd.TaskIdToDelete).compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
EventBus.getDefault().post(new TaskRemovedEvent(cmd.TaskIdToDelete));
}, throwable -> {});
}, throwable -> {
});
}
@Subscribe
@ -881,7 +889,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
user.save();
user.setStats(habitRPGUser.getStats());
setUserData(false);
}, throwable -> {});
}, throwable -> {
});
}
@Subscribe
@ -907,7 +916,7 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
.setNeutralButton(R.string.share, (hatchingDialog, which) -> {
ShareEvent event1 = new ShareEvent();
event1.sharedMessage = getString(R.string.share_hatched, potionName, eggName) + " https://habitica.com/social/hatch-pet";
Bitmap animalBitmap = ((BitmapDrawable)petImageView.getDrawable()).getBitmap();
Bitmap animalBitmap = ((BitmapDrawable) petImageView.getDrawable()).getBitmap();
Bitmap sharedImage = Bitmap.createBitmap(140, 140, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(sharedImage);
canvas.drawColor(getResources().getColor(R.color.brand_300));
@ -919,7 +928,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
})
.create();
dialog.show();
}, this.user), throwable -> {});
}, this.user), throwable -> {
});
}
@Subscribe
@ -932,7 +942,7 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
.compose(apiHelper.configureApiCallObserver())
.subscribe(feedResponse -> {
MainActivity.this.user.getItems().getPets().put(pet.getKey(), feedResponse.value);
MainActivity.this.user.getItems().getFood().put(event.usingFood.getKey(), event.usingFood.getOwned()-1);
MainActivity.this.user.getItems().getFood().put(event.usingFood.getKey(), event.usingFood.getOwned() - 1);
MainActivity.this.setUserData(false);
showSnackbar(MainActivity.this, floatingMenuWrapper, getString(R.string.notification_pet_fed, pet.getColorText(), pet.getAnimalText()), SnackbarDisplayType.NORMAL);
if (feedResponse.value == -1) {
@ -951,7 +961,7 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
.setNeutralButton(R.string.share, (hatchingDialog, which) -> {
ShareEvent event1 = new ShareEvent();
event1.sharedMessage = getString(R.string.share_raised, colorName, animalName) + " https://habitica.com/social/raise-pet";
Bitmap animalBitmap = ((BitmapDrawable)mountImageView.getDrawable()).getBitmap();
Bitmap animalBitmap = ((BitmapDrawable) mountImageView.getDrawable()).getBitmap();
Bitmap sharedImage = Bitmap.createBitmap(99, 99, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(sharedImage);
canvas.drawColor(getResources().getColor(R.color.brand_300));
@ -964,9 +974,12 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
.create();
dialog.show();
}
}, throwable -> {});
}, throwable -> {
});
}
// endregion
@Subscribe
public void reloadContent(ReloadContentEvent event) {
if (!this.isloadingContent) {
@ -977,12 +990,11 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
isloadingContent = false;
ContentReloadedEvent event1 = new ContentReloadedEvent();
EventBus.getDefault().post(event1);
}, throwable -> {});
}, throwable -> {
});
}
}
// endregion
@Override
public void onTaskDataReceived(TaskDirectionData data, Task task) {
if (task.type.equals("reward")) {
@ -1015,7 +1027,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
this.apiHelper.retrieveUser(true)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new HabitRPGUserCallback(this), throwable -> {});
.subscribe(new HabitRPGUserCallback(this), throwable -> {
});
user.getStats().setLvl(lvl);
showSnackbar(this, floatingMenuWrapper, message.toString(), SnackbarDisplayType.NORMAL);
@ -1048,10 +1061,6 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
setUserData(true);
}
static public Double round(Double value, int n) {
return (Math.round(value * Math.pow(10, n))) / (Math.pow(10, n));
}
private void displayDeathDialogIfNeeded() {
if (user.getStats().getHp() == null || user.getStats().getHp() > 0) {
@ -1079,7 +1088,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
faintDialog = null;
apiHelper.apiService.revive()
.compose(apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(MainActivity.this, MainActivity.this.user), throwable -> {});
.subscribe(new MergeUserCallback(MainActivity.this, MainActivity.this.user), throwable -> {
});
})
.create();
@ -1224,7 +1234,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
updateData.put(path, true);
apiHelper.apiService.updateUser(updateData)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(this, user), throwable -> {});
.subscribe(new MergeUserCallback(this, user), throwable -> {
});
this.overlayFrameLayout.removeView(this.activeTutorialView);
this.removeActiveTutorialView();
@ -1301,7 +1312,8 @@ public class MainActivity extends BaseActivity implements Action1<Throwable>, Ha
}
}
}
}, throwable -> {});
}, throwable -> {
});
}
private Intent createMaintenanceIntent(MaintenanceResponse maintenanceResponse, Boolean isDeprecationNotice) {

View file

@ -26,21 +26,16 @@ import rx.schedulers.Schedulers;
public class MaintenanceActivity extends BaseActivity {
@BindView(R.id.titleTextView)
TextView titleTextView;
@BindView(R.id.imageView)
ImageView imageView;
@BindView(R.id.descriptionTextView)
EmojiTextView descriptionTextView;
@BindView(R.id.playStoreButton)
Button playStoreButton;
@Inject
public MaintenanceApiService maintenanceService;
@BindView(R.id.titleTextView)
TextView titleTextView;
@BindView(R.id.imageView)
ImageView imageView;
@BindView(R.id.descriptionTextView)
EmojiTextView descriptionTextView;
@BindView(R.id.playStoreButton)
Button playStoreButton;
private Boolean isDeprecationNotice;
@Override
@ -83,7 +78,8 @@ public class MaintenanceActivity extends BaseActivity {
if (!maintenanceResponse.activeMaintenance) {
finish();
}
}, throwable -> {});
}, throwable -> {
});
}
}

View file

@ -23,6 +23,19 @@ public class PrefsActivity extends BaseActivity implements
@BindView(R.id.toolbar)
Toolbar toolbar;
// TODO:
// This method should be moved to HabiticaApplication
public static HostConfig fromContext(Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
HostConfig config;
String httpPort = BuildConfig.PORT;
String address = BuildConfig.DEBUG ? BuildConfig.BASE_URL : ctx.getString(R.string.base_url);
String api = prefs.getString(ctx.getString(R.string.SP_APIToken), null);
String userID = prefs.getString(ctx.getString(R.string.SP_userID), null);
config = new HostConfig(address, httpPort, api, userID);
return config;
}
@Override
protected int getLayoutResId() {
return R.layout.activity_prefs;
@ -77,18 +90,5 @@ public class PrefsActivity extends BaseActivity implements
}
return fragment;
}
// TODO:
// This method should be moved to HabiticaApplication
public static HostConfig fromContext(Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
HostConfig config;
String httpPort = BuildConfig.PORT;
String address = BuildConfig.DEBUG ? BuildConfig.BASE_URL : ctx.getString(R.string.base_url);
String api = prefs.getString(ctx.getString(R.string.SP_APIToken), null);
String userID = prefs.getString(ctx.getString(R.string.SP_userID), null);
config = new HostConfig(address, httpPort, api, userID);
return config;
}
}

View file

@ -36,25 +36,20 @@ import butterknife.BindView;
public class SetupActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, HabitRPGUserCallback.OnUserReceived {
@BindView(R.id.view_pager)
ViewPager pager;
@BindView(R.id.skipButton)
Button skipButton;
@BindView(R.id.nextButton)
Button nextButton;
@BindView(R.id.previousButton)
Button previousButton;
AvatarSetupFragment avatarSetupFragment;
TaskSetupFragment taskSetupFragment;
@Inject
public APIHelper apiHelper;
@Inject
protected HostConfig hostConfig;
@BindView(R.id.view_pager)
ViewPager pager;
@BindView(R.id.skipButton)
Button skipButton;
@BindView(R.id.nextButton)
Button nextButton;
@BindView(R.id.previousButton)
Button previousButton;
AvatarSetupFragment avatarSetupFragment;
TaskSetupFragment taskSetupFragment;
HabitRPGUser user;
Boolean completedSetup;
@ -100,7 +95,8 @@ public class SetupActivity extends BaseActivity implements View.OnClickListener,
} else {
this.apiHelper.apiService.getUser()
.compose(this.apiHelper.configureApiCallObserver())
.subscribe(new HabitRPGUserCallback(this), throwable -> {});
.subscribe(new HabitRPGUserCallback(this), throwable -> {
});
}
}
}
@ -146,7 +142,8 @@ public class SetupActivity extends BaseActivity implements View.OnClickListener,
public void onEvent(UpdateUserCommand event) {
this.apiHelper.apiService.updateUser(event.updateData)
.compose(this.apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(this, user), throwable -> {});
.subscribe(new MergeUserCallback(this, user), throwable -> {
});
}
@Override
@ -159,12 +156,13 @@ public class SetupActivity extends BaseActivity implements View.OnClickListener,
.compose(this.apiHelper.configureApiCallObserver())
.subscribe(tasks -> {
onUserReceived(user);
}, throwable -> {});
}, throwable -> {
});
//this.apiHelper.apiService.batchOperation(operations, new HabitRPGUserCallback(this));
}
this.pager.setCurrentItem(this.pager.getCurrentItem()+1);
this.pager.setCurrentItem(this.pager.getCurrentItem() + 1);
} else if (v == this.previousButton) {
this.pager.setCurrentItem(this.pager.getCurrentItem()-1);
this.pager.setCurrentItem(this.pager.getCurrentItem() - 1);
} else if (v == this.skipButton) {
JSONObject eventProperties = new JSONObject();
try {

View file

@ -27,9 +27,8 @@ public class SkillTasksActivity extends BaseActivity {
@BindView(R.id.tab_layout)
public TabLayout tabLayout;
Map<Integer, SkillTasksRecyclerViewFragment> viewFragmentsDictionary = new HashMap<>();
protected HabitRPGUser user;
Map<Integer, SkillTasksRecyclerViewFragment> viewFragmentsDictionary = new HashMap<>();
@Override
protected int getLayoutResId() {

View file

@ -80,12 +80,84 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
public static final String USER_ID_KEY = "userId";
public static final String TASK_TYPE_KEY = "type";
public static final String ALLOCATION_MODE_KEY = "allocationModeKey";
@BindView(R.id.task_value_edittext)
EditText taskValue;
@BindView(R.id.task_value_layout)
TextInputLayout taskValueLayout;
@BindView(R.id.task_checklist_wrapper)
LinearLayout checklistWrapper;
@BindView(R.id.task_difficulty_wrapper)
LinearLayout difficultyWrapper;
@BindView(R.id.task_attribute_wrapper)
LinearLayout attributeWrapper;
@BindView(R.id.task_main_wrapper)
LinearLayout mainWrapper;
@BindView(R.id.task_text_edittext)
EmojiEditText taskText;
@BindView(R.id.task_notes_edittext)
EmojiEditText taskNotes;
@BindView(R.id.task_difficulty_spinner)
Spinner taskDifficultySpinner;
@BindView(R.id.task_attribute_spinner)
Spinner taskAttributeSpinner;
@BindView(R.id.btn_delete_task)
Button btnDelete;
@BindView(R.id.task_startdate_layout)
LinearLayout startDateLayout;
@BindView(R.id.task_task_wrapper)
LinearLayout taskWrapper;
@BindView(R.id.task_positive_checkbox)
CheckBox positiveCheckBox;
@BindView(R.id.task_negative_checkbox)
CheckBox negativeCheckBox;
@BindView(R.id.task_actions_wrapper)
LinearLayout actionsLayout;
@BindView(R.id.task_weekdays_wrapper)
LinearLayout weekdayWrapper;
@BindView(R.id.task_frequency_spinner)
Spinner dailyFrequencySpinner;
@BindView(R.id.task_frequency_container)
LinearLayout frequencyContainer;
@BindView(R.id.checklist_recycler_view)
RecyclerView recyclerView;
@BindView(R.id.new_checklist)
EmojiEditText newCheckListEditText;
@BindView(R.id.add_checklist_button)
Button addChecklistItemButton;
@BindView(R.id.task_reminders_wrapper)
LinearLayout remindersWrapper;
@BindView(R.id.new_reminder_edittext)
EditText newRemindersEditText;
@BindView(R.id.reminders_recycler_view)
RecyclerView remindersRecyclerView;
@BindView(R.id.add_reminder_button)
Button addReminderButton;
@BindView(R.id.emoji_toggle_btn0)
ImageButton emojiToggle0;
@BindView(R.id.emoji_toggle_btn1)
ImageButton emojiToggle1;
ImageButton emojiToggle2;
@BindView(R.id.task_duedate_layout)
LinearLayout dueDateLayout;
@BindView(R.id.task_duedate_picker_layout)
LinearLayout dueDatePickerLayout;
@BindView(R.id.duedate_checkbox)
CheckBox dueDateCheckBox;
@BindView(R.id.startdate_text_edittext)
EditText startDatePickerText;
DateEditTextListener startDateListener;
@BindView(R.id.duedate_text_edittext)
EditText dueDatePickerText;
DateEditTextListener dueDateListener;
@BindView(R.id.task_tags_wrapper)
LinearLayout tagsWrapper;
@BindView(R.id.task_tags_checklist)
LinearLayout tagsContainerLinearLayout;
EmojiPopup popup;
private String taskType;
private String taskId;
private String userId;
private Task task;
private String allocationMode;
private List<CheckBox> weekdayCheckboxes = new ArrayList<>();
private NumberPicker frequencyPicker;
@ -93,120 +165,7 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
private CheckListAdapter checklistAdapter;
private RemindersAdapter remindersAdapter;
private List<CheckBox> tagCheckBoxList;
private TaskAlarmManager taskAlarmManager;
@BindView(R.id.task_value_edittext)
EditText taskValue;
@BindView(R.id.task_value_layout)
TextInputLayout taskValueLayout;
@BindView(R.id.task_checklist_wrapper)
LinearLayout checklistWrapper;
@BindView(R.id.task_difficulty_wrapper)
LinearLayout difficultyWrapper;
@BindView(R.id.task_attribute_wrapper)
LinearLayout attributeWrapper;
@BindView(R.id.task_main_wrapper)
LinearLayout mainWrapper;
@BindView(R.id.task_text_edittext)
EmojiEditText taskText;
@BindView(R.id.task_notes_edittext)
EmojiEditText taskNotes;
@BindView(R.id.task_difficulty_spinner)
Spinner taskDifficultySpinner;
@BindView(R.id.task_attribute_spinner)
Spinner taskAttributeSpinner;
@BindView(R.id.btn_delete_task)
Button btnDelete;
@BindView(R.id.task_startdate_layout)
LinearLayout startDateLayout;
@BindView(R.id.task_task_wrapper)
LinearLayout taskWrapper;
@BindView(R.id.task_positive_checkbox)
CheckBox positiveCheckBox;
@BindView(R.id.task_negative_checkbox)
CheckBox negativeCheckBox;
@BindView(R.id.task_actions_wrapper)
LinearLayout actionsLayout;
@BindView(R.id.task_weekdays_wrapper)
LinearLayout weekdayWrapper;
@BindView(R.id.task_frequency_spinner)
Spinner dailyFrequencySpinner;
@BindView(R.id.task_frequency_container)
LinearLayout frequencyContainer;
@BindView(R.id.checklist_recycler_view)
RecyclerView recyclerView;
@BindView(R.id.new_checklist)
EmojiEditText newCheckListEditText;
@BindView(R.id.add_checklist_button)
Button addChecklistItemButton;
@BindView(R.id.task_reminders_wrapper)
LinearLayout remindersWrapper;
@BindView(R.id.new_reminder_edittext)
EditText newRemindersEditText;
@BindView(R.id.reminders_recycler_view)
RecyclerView remindersRecyclerView;
@BindView(R.id.add_reminder_button)
Button addReminderButton;
@BindView(R.id.emoji_toggle_btn0)
ImageButton emojiToggle0;
@BindView(R.id.emoji_toggle_btn1)
ImageButton emojiToggle1;
ImageButton emojiToggle2;
@BindView(R.id.task_duedate_layout)
LinearLayout dueDateLayout;
@BindView(R.id.task_duedate_picker_layout)
LinearLayout dueDatePickerLayout;
@BindView(R.id.duedate_checkbox)
CheckBox dueDateCheckBox;
@BindView(R.id.startdate_text_edittext)
EditText startDatePickerText;
DateEditTextListener startDateListener;
@BindView(R.id.duedate_text_edittext)
EditText dueDatePickerText;
DateEditTextListener dueDateListener;
@BindView(R.id.task_tags_wrapper)
LinearLayout tagsWrapper;
@BindView(R.id.task_tags_checklist)
LinearLayout tagsContainerLinearLayout;
EmojiPopup popup;
private List<Tag> selectedTags;
@Override
@ -249,8 +208,8 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
EventBus.getDefault().post(new DeleteTaskCommand(taskId));
}).setNegativeButton(getString(R.string.no), (dialog, which) -> {
dialog.dismiss();
}).show());
dialog.dismiss();
}).show());
ArrayAdapter<CharSequence> difficultyAdapter = ArrayAdapter.createFromResource(this,
R.array.task_difficulties, android.R.layout.simple_spinner_item);
@ -410,7 +369,8 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
tags = loadedTags;
createTagsCheckBoxes();
},
throwable -> {}
throwable -> {
}
);
}
@ -436,84 +396,6 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
}
}
private class DateEditTextListener implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
Calendar calendar;
DatePickerDialog datePickerDialog;
EditText datePickerText;
DateFormat dateFormatter;
public DateEditTextListener(EditText dateText) {
calendar = Calendar.getInstance();
this.datePickerText = dateText;
this.datePickerText.setOnClickListener(this);
this.dateFormatter = DateFormat.getDateInstance();
this.datePickerDialog = new DatePickerDialog(datePickerText.getContext(), this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
this.datePickerDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getResources().getString(R.string.today), (dialog, which) -> {
setCalendar(Calendar.getInstance().getTime());
});
updateDateText();
}
public void onClick(View view) {
datePickerDialog.show();
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(year, monthOfYear, dayOfMonth);
updateDateText();
}
public Calendar getCalendar() {
return (Calendar) calendar.clone();
}
public void setCalendar(Date date) {
calendar.setTime(date);
datePickerDialog.updateDate(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
updateDateText();
}
private void updateDateText() {
datePickerText.setText(dateFormatter.format(calendar.getTime()));
}
}
private class emojiClickListener implements View.OnClickListener {
EmojiEditText view;
public emojiClickListener(EmojiEditText view) {
this.view = view;
}
@Override
public void onClick(View v) {
if (!popup.isShowing()) {
if (popup.isKeyBoardOpen()) {
popup.showAtBottom();
changeEmojiKeyboardIcon(true);
} else {
view.setFocusableInTouchMode(true);
view.requestFocus();
popup.showAtBottomPending();
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
changeEmojiKeyboardIcon(true);
}
} else {
popup.dismiss();
changeEmojiKeyboardIcon(false);
}
}
}
private void createCheckListRecyclerView() {
List<ChecklistItem> checklistItems = new ArrayList<>();
if (task != null && task.getChecklist() != null) {
@ -628,7 +510,6 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
}
}
private void setTitle(Task task) {
ActionBar actionBar = getSupportActionBar();
@ -982,4 +863,82 @@ public class TaskFormActivity extends BaseActivity implements AdapterView.OnItem
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
}
private class DateEditTextListener implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
Calendar calendar;
DatePickerDialog datePickerDialog;
EditText datePickerText;
DateFormat dateFormatter;
public DateEditTextListener(EditText dateText) {
calendar = Calendar.getInstance();
this.datePickerText = dateText;
this.datePickerText.setOnClickListener(this);
this.dateFormatter = DateFormat.getDateInstance();
this.datePickerDialog = new DatePickerDialog(datePickerText.getContext(), this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
this.datePickerDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getResources().getString(R.string.today), (dialog, which) -> {
setCalendar(Calendar.getInstance().getTime());
});
updateDateText();
}
public void onClick(View view) {
datePickerDialog.show();
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(year, monthOfYear, dayOfMonth);
updateDateText();
}
public Calendar getCalendar() {
return (Calendar) calendar.clone();
}
public void setCalendar(Date date) {
calendar.setTime(date);
datePickerDialog.updateDate(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
updateDateText();
}
private void updateDateText() {
datePickerText.setText(dateFormatter.format(calendar.getTime()));
}
}
private class emojiClickListener implements View.OnClickListener {
EmojiEditText view;
public emojiClickListener(EmojiEditText view) {
this.view = view;
}
@Override
public void onClick(View v) {
if (!popup.isShowing()) {
if (popup.isKeyBoardOpen()) {
popup.showAtBottom();
changeEmojiKeyboardIcon(true);
} else {
view.setFocusableInTouchMode(true);
view.requestFocus();
popup.showAtBottomPending();
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
changeEmojiKeyboardIcon(true);
}
} else {
popup.dismiss();
changeEmojiKeyboardIcon(false);
}
}
}
}

View file

@ -34,38 +34,17 @@ import butterknife.ButterKnife;
public class CustomizationRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Object> customizationList;
private String activeCustomization;
public String userSize;
public String hairColor;
public double gemBalance;
public void setCustomizationList(List<Customization> newCustomizationList) {
this.customizationList = new ArrayList<>();
CustomizationSet lastSet = new CustomizationSet();
for (Customization customization : newCustomizationList) {
if (customization.getCustomizationSet() != null && !customization.getCustomizationSet().equals(lastSet.identifier)) {
CustomizationSet set = new CustomizationSet();
set.identifier = customization.getCustomizationSet();
set.text = customization.getCustomizationSetName();
set.price = customization.getSetPrice();
set.hasPurchasable = !customization.isUsable();
lastSet = set;
customizationList.add(set);
}
customizationList.add(customization);
if (!customization.isUsable() && !lastSet.hasPurchasable) {
lastSet.hasPurchasable = true;
}
}
this.notifyDataSetChanged();
}
private List<Object> customizationList;
private String activeCustomization;
public void updateOwnership(List<String> ownedCustomizations) {
int position = 0;
for (Object obj : customizationList) {
if (obj.getClass().equals(Customization.class)) {
Customization customization = (Customization)obj;
Customization customization = (Customization) obj;
if (customization.getPurchased() != ownedCustomizations.contains(customization.getId())) {
customization.setPurchased(ownedCustomizations.contains(customization.getId()));
notifyItemChanged(position);
@ -109,7 +88,7 @@ public class CustomizationRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Object obj = customizationList.get(position);
if (obj.getClass().equals(CustomizationSet.class)) {
((SectionViewHolder)holder).bind((CustomizationSet) obj);
((SectionViewHolder) holder).bind((CustomizationSet) obj);
} else {
((CustomizationViewHolder) holder).bind((Customization) customizationList.get(position));
@ -138,10 +117,31 @@ public class CustomizationRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
return this.customizationList;
}
public void setCustomizationList(List<Customization> newCustomizationList) {
this.customizationList = new ArrayList<>();
CustomizationSet lastSet = new CustomizationSet();
for (Customization customization : newCustomizationList) {
if (customization.getCustomizationSet() != null && !customization.getCustomizationSet().equals(lastSet.identifier)) {
CustomizationSet set = new CustomizationSet();
set.identifier = customization.getCustomizationSet();
set.text = customization.getCustomizationSetName();
set.price = customization.getSetPrice();
set.hasPurchasable = !customization.isUsable();
lastSet = set;
customizationList.add(set);
}
customizationList.add(customization);
if (!customization.isUsable() && !lastSet.hasPurchasable) {
lastSet.hasPurchasable = true;
}
}
this.notifyDataSetChanged();
}
class CustomizationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.card_view)
CardView cardView;
CardView cardView;
@BindView(R.id.linearLayout)
RelativeLayout linearLayout;
@ -236,15 +236,12 @@ public class CustomizationRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
class SectionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CustomizationSet set;
@BindView(R.id.label)
TextView label;
@BindView(R.id.purchaseSetButton)
Button purchaseSetButton;
Context context;
private CustomizationSet set;
public SectionViewHolder(View itemView) {
super(itemView);
@ -266,40 +263,40 @@ public class CustomizationRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
@Override
public void onClick(View v) {
LinearLayout dialogContent = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.dialog_purchase_customization, null);
LinearLayout dialogContent = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.dialog_purchase_customization, null);
TextView priceLabel = (TextView) dialogContent.findViewById(R.id.priceLabel);
priceLabel.setText(String.valueOf(set.price));
TextView priceLabel = (TextView) dialogContent.findViewById(R.id.priceLabel);
priceLabel.setText(String.valueOf(set.price));
AlertDialog dialog = new AlertDialog.Builder(context)
.setPositiveButton(R.string.purchase_button, (dialog1, which) -> {
if (set.price > gemBalance) {
OpenMenuItemCommand event = new OpenMenuItemCommand();
event.identifier = MainDrawerBuilder.SIDEBAR_PURCHASE;
EventBus.getDefault().post(event);
return;
}
UnlockPathCommand event = new UnlockPathCommand();
String path = "";
for (Object obj : customizationList) {
if (obj.getClass().equals(Customization.class)) {
Customization customization = (Customization) obj;
if (!customization.isUsable() && customization.getCustomizationSet() != null && customization.getCustomizationSet().equals(set.identifier)) {
path = path + "," + customization.getPath();
}
AlertDialog dialog = new AlertDialog.Builder(context)
.setPositiveButton(R.string.purchase_button, (dialog1, which) -> {
if (set.price > gemBalance) {
OpenMenuItemCommand event = new OpenMenuItemCommand();
event.identifier = MainDrawerBuilder.SIDEBAR_PURCHASE;
EventBus.getDefault().post(event);
return;
}
UnlockPathCommand event = new UnlockPathCommand();
String path = "";
for (Object obj : customizationList) {
if (obj.getClass().equals(Customization.class)) {
Customization customization = (Customization) obj;
if (!customization.isUsable() && customization.getCustomizationSet() != null && customization.getCustomizationSet().equals(set.identifier)) {
path = path + "," + customization.getPath();
}
}
path = path.substring(1);
event.path = path;
event.balanceDiff = set.price / 4;
EventBus.getDefault().post(event);
})
.setTitle(context.getString(R.string.purchase_set_title, set.text))
.setView(dialogContent)
.setNegativeButton(R.string.reward_dialog_dismiss, (dialog1, which) -> {
dialog1.dismiss();
}).create();
dialog.show();
}
path = path.substring(1);
event.path = path;
event.balanceDiff = set.price / 4;
EventBus.getDefault().post(event);
})
.setTitle(context.getString(R.string.purchase_set_title, set.text))
.setView(dialogContent)
.setNegativeButton(R.string.reward_dialog_dismiss, (dialog1, which) -> {
dialog1.dismiss();
}).create();
dialog.show();
}
}
}

View file

@ -17,10 +17,10 @@ import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FAQOverviewRecyclerAdapter extends RecyclerView.Adapter<FAQOverviewRecyclerAdapter.FAQArticleViewHolder> {
public class FAQOverviewRecyclerAdapter extends RecyclerView.Adapter<FAQOverviewRecyclerAdapter.FAQArticleViewHolder> {
private List<FAQArticle> articles;
public MainActivity activity;
private List<FAQArticle> articles;
public void setArticles(List<FAQArticle> articles) {
this.articles = articles;

View file

@ -26,11 +26,10 @@ import butterknife.ButterKnife;
public class SkillTasksRecyclerViewAdapter extends RecyclerView.Adapter<SkillTasksRecyclerViewAdapter.ViewHolder> {
String taskType;
private ObservableArrayList<Task> observableContent;
SkillTasksActivity activity;
private static final int TYPE_CELL = 1;
String taskType;
SkillTasksActivity activity;
private ObservableArrayList<Task> observableContent;
private RecyclerView.Adapter<ViewHolder> parentAdapter;
public SkillTasksRecyclerViewAdapter(String taskType, SkillTasksActivity activity) {
@ -67,7 +66,7 @@ public class SkillTasksRecyclerViewAdapter extends RecyclerView.Adapter<SkillTas
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.skill_task_item_card, parent, false);
.inflate(R.layout.skill_task_item_card, parent, false);
return new SkillTasksRecyclerViewAdapter.ViewHolder(view);
}
@ -80,12 +79,39 @@ public class SkillTasksRecyclerViewAdapter extends RecyclerView.Adapter<SkillTas
// region ViewHolders
public void loadContent() {
this.loadContent(false);
}
// endregion
public void loadContent(boolean forced) {
if (this.observableContent == null || forced) {
this.observableContent = new ObservableArrayList<>();
this.observableContent.addAll(new Select().from(Task.class)
.where(Condition.column("type").eq(this.taskType))
.and(Condition.CombinedCondition
.begin(Condition.column("completed").eq(false))
.or(Condition.column("type").eq("daily"))
)
.orderBy(OrderBy.columns("position", "dateCreated").descending())
.queryList());
}
if (parentAdapter != null) {
parentAdapter.notifyDataSetChanged();
} else {
notifyDataSetChanged();
}
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected android.content.res.Resources resources;
public Task task;
protected android.content.res.Resources resources;
SkillTaskItemCardBinding binding;
@BindView(R.id.notesTextView)
@ -121,33 +147,4 @@ public class SkillTasksRecyclerViewAdapter extends RecyclerView.Adapter<SkillTas
}
}
// endregion
public void loadContent() {
this.loadContent(false);
}
public void loadContent(boolean forced) {
if (this.observableContent == null || forced) {
this.observableContent = new ObservableArrayList<>();
this.observableContent.addAll(new Select().from(Task.class)
.where(Condition.column("type").eq(this.taskType))
.and(Condition.CombinedCondition
.begin(Condition.column("completed").eq(false))
.or(Condition.column("type").eq("daily"))
)
.orderBy(OrderBy.columns("position", "dateCreated").descending())
.queryList());
}
if (parentAdapter != null) {
parentAdapter.notifyDataSetChanged();
} else {
notifyDataSetChanged();
}
}
}

View file

@ -24,9 +24,8 @@ import butterknife.ButterKnife;
public class SkillsRecyclerViewAdapter extends RecyclerView.Adapter<SkillsRecyclerViewAdapter.SkillViewHolder> {
private List<Skill> skillList;
public Double mana;
private List<Skill> skillList;
public void setSkillList(List<Skill> skillList) {
this.skillList = skillList;
@ -91,7 +90,7 @@ public class SkillsRecyclerViewAdapter extends RecyclerView.Adapter<SkillsRecycl
skillNameTextView.setText(skill.text);
skillNotesTextView.setText(skill.notes);
priceButton.setText(String.format(context.getResources().getString(R.string.mana_price_button), skill.mana));
DataBindingUtils.loadImage(skillImageView, "shop_"+skill.key);
DataBindingUtils.loadImage(skillImageView, "shop_" + skill.key);
if (skill.mana > mana) {
priceButton.setEnabled(false);

View file

@ -23,102 +23,101 @@ import butterknife.ButterKnife;
public class EquipmentRecyclerViewAdapter extends RecyclerView.Adapter<EquipmentRecyclerViewAdapter.GearViewHolder> {
private List<ItemData> gearList;
public String equippedGear;
public Boolean isCostume;
public String type;
private List<ItemData> gearList;
public String equippedGear;
public Boolean isCostume;
public String type;
public void setGearList(List<ItemData> gearList) {
public void setGearList(List<ItemData> gearList) {
this.gearList = gearList;
this.notifyDataSetChanged();
}
@Override
public GearViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gear_list_item, parent, false);
return new GearViewHolder(view);
}
@Override
public void onBindViewHolder(GearViewHolder holder, int position) {
holder.bind(gearList.get(position));
}
@Override
public int getItemCount() {
return gearList == null ? 0 : gearList.size();
}
class GearViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.gear_container)
View gearContainer;
@BindView(R.id.gear_text)
TextView gearNameTextView;
@BindView(R.id.gear_notes)
TextView gearNotesTextView;
@BindView(R.id.gear_image)
ImageView imageView;
@BindView(R.id.equippedIndicator)
View equippedIndicator;
ItemData gear;
Context context;
public GearViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
context = itemView.getContext();
itemView.setOnClickListener(this);
}
public void bind(ItemData gear) {
this.gear = gear;
this.gearNameTextView.setText(this.gear.text);
this.gearNotesTextView.setText(this.gear.notes);
if (gear.key.equals(equippedGear)) {
this.equippedIndicator.setVisibility(View.VISIBLE);
this.gearContainer.setBackgroundColor(ContextCompat.getColor(context, R.color.brand_700));
} else {
this.equippedIndicator.setVisibility(View.GONE);
this.gearContainer.setBackgroundResource(R.drawable.selection_highlight);
}
String imageUrl = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/shop_" + gear.key + ".png";
Picasso.with(imageView.getContext())
.load(imageUrl)
.into(imageView);
}
@Override
public void onClick(View v) {
EquipCommand command = new EquipCommand();
command.key = this.gear.key;
if (isCostume) {
command.type = "costume";
} else {
command.type = "equipped";
public GearViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gear_list_item, parent, false);
return new GearViewHolder(view);
}
@Override
public void onBindViewHolder(GearViewHolder holder, int position) {
holder.bind(gearList.get(position));
}
@Override
public int getItemCount() {
return gearList == null ? 0 : gearList.size();
}
class GearViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.gear_container)
View gearContainer;
@BindView(R.id.gear_text)
TextView gearNameTextView;
@BindView(R.id.gear_notes)
TextView gearNotesTextView;
@BindView(R.id.gear_image)
ImageView imageView;
@BindView(R.id.equippedIndicator)
View equippedIndicator;
ItemData gear;
Context context;
public GearViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
context = itemView.getContext();
itemView.setOnClickListener(this);
}
EventBus.getDefault().post(command);
if (this.gear.key.equals(equippedGear)) {
equippedGear = type + "_base_0";
} else {
equippedGear = this.gear.key;
public void bind(ItemData gear) {
this.gear = gear;
this.gearNameTextView.setText(this.gear.text);
this.gearNotesTextView.setText(this.gear.notes);
if (gear.key.equals(equippedGear)) {
this.equippedIndicator.setVisibility(View.VISIBLE);
this.gearContainer.setBackgroundColor(ContextCompat.getColor(context, R.color.brand_700));
} else {
this.equippedIndicator.setVisibility(View.GONE);
this.gearContainer.setBackgroundResource(R.drawable.selection_highlight);
}
String imageUrl = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/shop_" + gear.key + ".png";
Picasso.with(imageView.getContext())
.load(imageUrl)
.into(imageView);
}
@Override
public void onClick(View v) {
EquipCommand command = new EquipCommand();
command.key = this.gear.key;
if (isCostume) {
command.type = "costume";
} else {
command.type = "equipped";
}
EventBus.getDefault().post(command);
if (this.gear.key.equals(equippedGear)) {
equippedGear = type + "_base_0";
} else {
equippedGear = this.gear.key;
}
notifyDataSetChanged();
}
notifyDataSetChanged();
}
}
}

View file

@ -32,16 +32,14 @@ import java.util.List;
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> {
private List<Item> itemList;
public Boolean isHatching;
public Boolean isFeeding;
public Item hatchingItem;
public Pet feedingPet;
public ItemRecyclerFragment fragment;
public HashMap<String, Integer> ownedPets;
public Context context;
private List<Item> itemList;
public void setItemList(List<Item> itemList) {
this.itemList = itemList;
@ -104,7 +102,7 @@ public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapte
binding.setDisabled(false);
if (item instanceof QuestContent) {
binding.setImageNamed("inventory_quest_scroll_"+item.getKey());
binding.setImageNamed("inventory_quest_scroll_" + item.getKey());
} else {
String type = "";
if (item instanceof Egg) {
@ -114,7 +112,7 @@ public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapte
} else if (item instanceof HatchingPotion) {
type = "HatchingPotion";
}
binding.setImageNamed("Pet_"+type+"_"+item.getKey());
binding.setImageNamed("Pet_" + type + "_" + item.getKey());
if (isHatching != null && isHatching) {
this.binding.setDisabled(this.isPetOwned());
@ -143,7 +141,7 @@ public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapte
event.item = item;
EventBus.getDefault().post(event);
if (item.getOwned() > 1) {
item.setOwned(item.getOwned()-1);
item.setOwned(item.getOwned() - 1);
notifyItemChanged(getAdapterPosition());
} else {
if (getAdapterPosition() >= 0) {
@ -156,15 +154,15 @@ public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapte
}
if (item instanceof Egg) {
HatchingCommand event = new HatchingCommand();
event.usingEgg = (Egg)item;
event.usingEgg = (Egg) item;
EventBus.getDefault().post(event);
} else if (item instanceof Food) {
FeedCommand event = new FeedCommand();
event.usingFood = (Food)item;
event.usingFood = (Food) item;
EventBus.getDefault().post(event);
} else if (item instanceof HatchingPotion) {
HatchingCommand event = new HatchingCommand();
event.usingHatchingPotion = (HatchingPotion)item;
event.usingHatchingPotion = (HatchingPotion) item;
EventBus.getDefault().post(event);
} else if (item instanceof QuestContent) {
InvitePartyToQuestCommand event = new InvitePartyToQuestCommand();
@ -173,26 +171,26 @@ public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapte
}
});
menu.show();
} else if (isHatching){
} else if (isHatching) {
if (this.isPetOwned()) {
return;
}
if (item instanceof Egg) {
HatchingCommand event = new HatchingCommand();
event.usingEgg = (Egg)item;
event.usingHatchingPotion = (HatchingPotion)hatchingItem;
event.usingEgg = (Egg) item;
event.usingHatchingPotion = (HatchingPotion) hatchingItem;
EventBus.getDefault().post(event);
} else if (item instanceof HatchingPotion) {
HatchingCommand event = new HatchingCommand();
event.usingHatchingPotion = (HatchingPotion) item;
event.usingEgg = (Egg)hatchingItem;
event.usingEgg = (Egg) hatchingItem;
EventBus.getDefault().post(event);
}
fragment.dismiss();
} else if (isFeeding) {
FeedCommand event = new FeedCommand();
event.usingPet = feedingPet;
event.usingFood = (Food)item;
event.usingFood = (Food) item;
EventBus.getDefault().post(event);
fragment.dismiss();
}

View file

@ -27,11 +27,10 @@ import butterknife.ButterKnife;
public class MountDetailRecyclerAdapter extends RecyclerView.Adapter<MountDetailRecyclerAdapter.MountViewHolder> {
public String itemType;
public Context context;
private List<Mount> itemList;
private HashMap<String, Boolean> ownedMapping;
public String itemType;
public Context context;
public void setItemList(List<Mount> itemList) {
this.itemList = itemList;
@ -88,7 +87,7 @@ public class MountDetailRecyclerAdapter extends RecyclerView.Adapter<MountDetail
itemView.setOnClickListener(this);
}
public Boolean isOwned() {
public Boolean isOwned() {
if (ownedMapping != null && animal != null) {
if (ownedMapping.containsKey(animal.getKey()) && ownedMapping.get(animal.getKey())) {
return true;

View file

@ -29,12 +29,11 @@ import butterknife.ButterKnife;
public class PetDetailRecyclerAdapter extends RecyclerView.Adapter<PetDetailRecyclerAdapter.PetViewHolder> {
public String itemType;
public Context context;
private List<Pet> itemList;
private HashMap<String, Integer> ownedMapping;
private HashMap<String, Boolean> ownedMountMapping;
public String itemType;
public Context context;
public void setItemList(List<Pet> itemList) {
this.itemList = itemList;
@ -96,7 +95,7 @@ public class PetDetailRecyclerAdapter extends RecyclerView.Adapter<PetDetailRecy
itemView.setOnClickListener(this);
}
public int getOwnedStatus() {
public int getOwnedStatus() {
if (ownedMapping != null && animal != null) {
if (ownedMapping.containsKey(animal.getKey())) {
return ownedMapping.get(animal.getKey());

View file

@ -25,10 +25,9 @@ import butterknife.ButterKnife;
public class StableRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Object> itemList;
public String itemType;
public MainActivity activity;
private List<Object> itemList;
public <T extends Animal> void setItemList(List<Object> itemList) {
this.itemList = itemList;
@ -54,7 +53,7 @@ public class StableRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.Vie
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Object obj = this.itemList.get(position);
if (obj.getClass().equals(String.class)) {
((SectionViewHolder)holder).bind((String) obj);
((SectionViewHolder) holder).bind((String) obj);
} else {
((StableViewHolder) holder).bind((Animal) itemList.get(position));
@ -158,12 +157,12 @@ public class StableRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.Vie
}
public void bind(String title) {
try {
Integer stringID = context.getResources().getIdentifier("section"+title, "string", context.getPackageName());
this.label.setText(context.getString(stringID));
} catch (Exception e) {
this.label.setText(title);
}
try {
Integer stringID = context.getResources().getIdentifier("section" + title, "string", context.getPackageName());
this.label.setText(context.getString(stringID));
} catch (Exception e) {
this.label.setText(title);
}
}
}
}

View file

@ -29,9 +29,9 @@ import butterknife.ButterKnife;
public class CustomizationSetupAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Object> customizationList;
public String userSize;
public HabitRPGUser user;
private List<Object> customizationList;
public void setCustomizationList(List<Customization> newCustomizationList) {
this.customizationList = new ArrayList<>();
@ -76,7 +76,7 @@ public class CustomizationSetupAdapter extends RecyclerView.Adapter<RecyclerView
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Object obj = customizationList.get(position);
if (obj.getClass().equals(String.class)) {
((SectionViewHolder)holder).bind((String) obj);
((SectionViewHolder) holder).bind((String) obj);
} else {
((CustomizationViewHolder) holder).bind((Customization) customizationList.get(position));

View file

@ -19,8 +19,8 @@ import butterknife.ButterKnife;
public class TaskSetupAdapter extends RecyclerView.Adapter<TaskSetupAdapter.TaskViewHolder> {
private String[][] taskList;
public List<Boolean> checkedList;
private String[][] taskList;
public void setTaskList(String[][] taskList) {
this.taskList = taskList;

View file

@ -129,54 +129,46 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
public class ChatRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {
private int layoutType;
private String uuid;
private String groupId;
// Toggle Inn State
@BindView(R.id.btn_toggle_inn)
@Nullable
Button btnToggleInn;
// New Msg
@BindView(R.id.edit_new_message_text)
@Nullable
EmojiEditText textNewMessage;
@BindView(R.id.btn_send_message)
@Nullable
Button btnSendNewMessage;
@BindView(R.id.btn_options)
@Nullable
ImageView btnOptions;
@BindView(R.id.user_background_layout)
@Nullable
LinearLayout userBackground;
@BindView(R.id.like_background_layout)
@Nullable
LinearLayout likeBackground;
@BindView(R.id.user_label)
@Nullable
TextView userLabel;
@BindView(R.id.message_text)
@Nullable
EmojiTextView messageText;
@BindView(R.id.ago_label)
@Nullable
TextView agoLabel;
@BindView(R.id.tvLikes)
@Nullable
TextView tvLikes;
Context context;
Resources res;
int likeCount = 0;
boolean currentUserLikedPost = false;
private int layoutType;
private String uuid;
private String groupId;
private ChatMessage currentMsg;
public ChatRecyclerViewHolder(View itemView, int layoutType, String currentUserId, String groupId) {
super(itemView);
@ -197,9 +189,9 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
}
ViewHelper.SetBackgroundTint(btnToggleInn, ContextCompat.getColor(context, R.color.brand));
if(HabiticaApplication.User != null && HabiticaApplication.User.getPreferences().getSleep()){
if (HabiticaApplication.User != null && HabiticaApplication.User.getPreferences().getSleep()) {
btnToggleInn.setText(R.string.tavern_inn_checkOut);
}else{
} else {
btnToggleInn.setText(R.string.tavern_inn_rest);
}
@ -231,8 +223,6 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
}
}
private ChatMessage currentMsg;
public void bind(final ChatMessage msg) {
currentMsg = msg;
@ -261,14 +251,11 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
}
}
int likeCount = 0;
boolean currentUserLikedPost = false;
private void setLikeProperties(ChatMessage msg) {
likeCount = 0;
currentUserLikedPost = false;
if(msg != null && msg.likes != null) {
if (msg != null && msg.likes != null) {
for (Map.Entry<String, Boolean> e : msg.likes.entrySet()) {
if (e.getValue()) {
likeCount++;
@ -374,11 +361,11 @@ public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerVi
if (v == btnToggleInn) {
EventBus.getDefault().post(new ToggleInnCommand());
if(!HabiticaApplication.User.getPreferences().getSleep()){
if (!HabiticaApplication.User.getPreferences().getSleep()) {
if (btnToggleInn != null) {
btnToggleInn.setText(R.string.tavern_inn_checkOut);
}
}else{
} else {
if (btnToggleInn != null) {
btnToggleInn.setText(R.string.tavern_inn_rest);
}

View file

@ -25,8 +25,9 @@ import butterknife.ButterKnife;
public class PartyMemberRecyclerViewAdapter extends RecyclerView.Adapter<PartyMemberRecyclerViewAdapter.MemberViewHolder> {
private List<HabitRPGUser> memberList;
public Context context;
private List<HabitRPGUser> memberList;
public void setMemberList(List<HabitRPGUser> memberList) {
this.memberList = memberList;
this.notifyDataSetChanged();

View file

@ -59,7 +59,8 @@ public class PublicGuildsRecyclerViewAdapter extends RecyclerView.Adapter<Public
memberGuildIDs.remove(guild.id);
int indexOfGroup = publicGuildList.indexOf(guild);
notifyItemChanged(indexOfGroup);
}, throwable -> {});
}, throwable -> {
});
} else {
PublicGuildsRecyclerViewAdapter.this.apiHelper.apiService.joinGroup(guild.id)
.compose(apiHelper.configureApiCallObserver())
@ -67,7 +68,8 @@ public class PublicGuildsRecyclerViewAdapter extends RecyclerView.Adapter<Public
memberGuildIDs.add(group.id);
int indexOfGroup = publicGuildList.indexOf(group);
notifyItemChanged(indexOfGroup);
}, throwable -> {});
}, throwable -> {
});
}
});

View file

@ -31,7 +31,7 @@ public class QuestCollectRecyclerViewAdapter extends RecyclerView.Adapter<QuestC
this.notifyDataSetChanged();
}
public void setQuestContent(QuestContent quest){
public void setQuestContent(QuestContent quest) {
this.quest = quest;
this.notifyDataSetChanged();
}
@ -44,6 +44,7 @@ public class QuestCollectRecyclerViewAdapter extends RecyclerView.Adapter<QuestC
return new QuestCollectViewHolder(view);
}
@Override
public void onBindViewHolder(QuestCollectViewHolder holder, int position) {
holder.bind(collect.get(position));

View file

@ -103,11 +103,11 @@ public abstract class BaseTasksRecyclerViewAdapter<VH extends BaseTaskViewHolder
}
@Subscribe
public void onEvent(TaskCheckedCommand evnt){
public void onEvent(TaskCheckedCommand evnt) {
if (!taskType.equals(evnt.Task.getType()))
return;
if(evnt.completed && evnt.Task.getType().equals("todo")){
if (evnt.completed && evnt.Task.getType().equals("todo")) {
// remove from the list
content.remove(evnt.Task);
}
@ -136,14 +136,14 @@ public abstract class BaseTasksRecyclerViewAdapter<VH extends BaseTaskViewHolder
public void onEvent(TaskRemovedEvent evnt) {
Task taskToDelete = null;
for(Task t : content) {
if(t.getId().equals(evnt.deletedTaskId)){
for (Task t : content) {
if (t.getId().equals(evnt.deletedTaskId)) {
taskToDelete = t;
break;
}
}
if(taskToDelete != null) {
if (taskToDelete != null) {
content.remove(taskToDelete);
filter();
}
@ -151,7 +151,7 @@ public abstract class BaseTasksRecyclerViewAdapter<VH extends BaseTaskViewHolder
private void updateTask(Task task) {
int i;
for(i = 0; i < this.content.size(); ++i) {
for (i = 0; i < this.content.size(); ++i) {
if (content.get(i).getId().equals(task.getId())) {
break;
}

View file

@ -26,7 +26,7 @@ import butterknife.ButterKnife;
* Created by franzejr on 15/11/15.
*/
public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.ItemViewHolder>
implements ItemTouchHelperAdapter{
implements ItemTouchHelperAdapter {
private final List<ChecklistItem> items = new ArrayList<>();
@ -47,12 +47,12 @@ public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.Item
holder.checkListTextView.setText(items.get(position).getText());
}
public void addItem(ChecklistItem item){
public void addItem(ChecklistItem item) {
items.add(item);
notifyItemInserted(items.size() - 1);
}
public List<ChecklistItem> getCheckListItems(){
public List<ChecklistItem> getCheckListItems() {
return items;
}
@ -64,7 +64,7 @@ public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.Item
@Override
public void onItemDismiss(int position) {
if(position >= 0 && position < items.size()){
if (position >= 0 && position < items.size()) {
items.remove(position);
notifyItemRemoved(position);
}
@ -82,14 +82,12 @@ public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.Item
public class ItemViewHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder, Button.OnClickListener {
public ChecklistTextWatcher textWatcher;
@BindView(R.id.item_edittext)
EmojiEditText checkListTextView;
@BindView(R.id.delete_item_button)
Button deleteButton;
public ChecklistTextWatcher textWatcher;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
@ -112,7 +110,7 @@ public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.Item
@Override
public void onClick(View v) {
if (v == deleteButton) {
CheckListAdapter.this.onItemDismiss(getAdapterPosition());
CheckListAdapter.this.onItemDismiss(getAdapterPosition());
}
}

View file

@ -47,12 +47,12 @@ public class RemindersAdapter extends RecyclerView.Adapter<RemindersAdapter.Item
holder.minute = time.getMinutes();
}
public void addItem(RemindersItem item){
public void addItem(RemindersItem item) {
reminders.add(item);
notifyItemInserted(reminders.size() - 1);
}
public List<RemindersItem> getRemindersItems(){
public List<RemindersItem> getRemindersItems() {
return reminders;
}
@ -64,7 +64,7 @@ public class RemindersAdapter extends RecyclerView.Adapter<RemindersAdapter.Item
@Override
public void onItemDismiss(int position) {
if(position >= 0 && position < reminders.size()){
if (position >= 0 && position < reminders.size()) {
reminders.get(position).async().delete();
reminders.remove(position);
notifyItemRemoved(position);

View file

@ -86,7 +86,8 @@ public class RewardsRecyclerViewAdapter extends BaseTasksRecyclerViewAdapter<Rew
.subscribe(items -> {
this.filteredContent.addAll(items);
notifyDataSetChanged();
}, throwable -> {});
}, throwable -> {
});
}
}

View file

@ -22,16 +22,15 @@ import butterknife.Unbinder;
public class AboutFragment extends Fragment {
private String androidSourceCodeLink = "https://github.com/HabitRPG/habitrpg-android/";
private String twitterLink = "https://twitter.com/habitica";
@BindView(R.id.versionInfo)
public TextView versionInfo;
String versionName = "";
int versionCode = 0;
String userId = "";
Unbinder unbinder;
@BindView(R.id.versionInfo)
public TextView versionInfo;
private String androidSourceCodeLink = "https://github.com/HabitRPG/habitrpg-android/";
private String twitterLink = "https://twitter.com/habitica";
private View view;
@OnClick(R.id.sourceCodeLink)
public void openSourceCodePageByLabel() {
@ -58,7 +57,6 @@ public class AboutFragment extends Fragment {
sendEmail("[Android] Feedback");
}
@OnClick(R.id.googlePlayStoreButton)
public void openGooglePlay() {
Intent intent = new Intent(Intent.ACTION_VIEW);
@ -66,8 +64,6 @@ public class AboutFragment extends Fragment {
startActivity(intent);
}
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@ -109,13 +105,13 @@ public class AboutFragment extends Fragment {
int version = Build.VERSION.SDK_INT;
String device = Build.DEVICE;
String bodyOfEmail = "Device: " + device +
" \nAndroid Version: " + version +
" \nAppVersion: " + getString(R.string.version_info, versionName, versionCode) +
" \nUser ID: " + userId +
" \nDetails: ";
" \nAndroid Version: " + version +
" \nAppVersion: " + getString(R.string.version_info, versionName, versionCode) +
" \nUser ID: " + userId +
" \nDetails: ";
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","mobile@habitica.com", null));
"mailto", "mobile@habitica.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, bodyOfEmail);
startActivity(Intent.createChooser(emailIntent, "Send email..."));

View file

@ -30,12 +30,31 @@ import butterknife.Unbinder;
public abstract class BaseFragment extends DialogFragment {
private boolean registerEventBus = false;
public String tutorialStepIdentifier;
public String tutorialText;
public Unbinder unbinder;
private boolean registerEventBus = false;
private TransactionListener<TutorialStep> tutorialStepTransactionListener = new TransactionListener<TutorialStep>() {
@Override
public void onResultReceived(TutorialStep step) {
if (step != null && !step.getWasCompleted() && (step.getDisplayedOn() == null || (new Date().getTime() - step.getDisplayedOn().getTime()) > 86400000)) {
DisplayTutorialEvent event = new DisplayTutorialEvent();
event.step = step;
event.tutorialText = tutorialText;
EventBus.getDefault().post(event);
}
}
@Override
public boolean onReady(BaseTransaction<TutorialStep> baseTransaction) {
return true;
}
@Override
public boolean hasResult(BaseTransaction<TutorialStep> baseTransaction, TutorialStep step) {
return true;
}
};
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
@ -64,7 +83,7 @@ public abstract class BaseFragment extends DialogFragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
injectFragment(((BaseActivity)getActivity()).getHabiticaApplication().getComponent());
injectFragment(((BaseActivity) getActivity()).getHabiticaApplication().getComponent());
}
@Nullable
@ -111,28 +130,5 @@ public abstract class BaseFragment extends DialogFragment {
return this.getClass().getSimpleName();
}
private TransactionListener<TutorialStep> tutorialStepTransactionListener = new TransactionListener<TutorialStep>() {
@Override
public void onResultReceived(TutorialStep step) {
if (step != null && !step.getWasCompleted() && (step.getDisplayedOn() == null || (new Date().getTime() - step.getDisplayedOn().getTime()) > 86400000)) {
DisplayTutorialEvent event = new DisplayTutorialEvent();
event.step = step;
event.tutorialText = tutorialText;
EventBus.getDefault().post(event);
}
}
@Override
public boolean onReady(BaseTransaction<TutorialStep> baseTransaction) {
return true;
}
@Override
public boolean hasResult(BaseTransaction<TutorialStep> baseTransaction, TutorialStep step) {
return true;
}
};
}

View file

@ -24,10 +24,9 @@ public abstract class BaseMainFragment extends BaseFragment {
public MainActivity activity;
public TabLayout tabLayout;
public FrameLayout floatingMenuWrapper;
protected HabitRPGUser user;
public boolean usesTabLayout;
public int fragmentSidebarPosition;
protected HabitRPGUser user;
public void setUser(HabitRPGUser user) {
this.user = user;

View file

@ -34,13 +34,10 @@ import io.fabric.sdk.android.Fabric;
public class GemsPurchaseFragment extends BaseMainFragment {
private static final int GEMS_TO_ADD = 21;
private Listener listener;
private BillingRequests billingRequests;
@BindView(R.id.btn_purchase_gems)
Button btnPurchaseGems;
private Listener listener;
private BillingRequests billingRequests;
@Override
public void onAttach(Context context) {
@ -106,7 +103,7 @@ public class GemsPurchaseFragment extends BaseMainFragment {
GemsPurchaseFragment.this.billingRequests = billingRequests;
// if the user leaves the fragment before the checkout callback is done
if(btnPurchaseGems != null) {
if (btnPurchaseGems != null) {
btnPurchaseGems.setEnabled(true);
}
@ -122,7 +119,7 @@ public class GemsPurchaseFragment extends BaseMainFragment {
java.util.List<Sku> skus = gems.getSkus();
for (Sku sku : skus){
for (Sku sku : skus) {
updateBuyButtonText(sku.price);
}
});
@ -132,22 +129,20 @@ public class GemsPurchaseFragment extends BaseMainFragment {
}
}
private void updateBuyButtonText(String price){
if(price == null || price.isEmpty()){
btnPurchaseGems.setText("+"+ GEMS_TO_ADD);
}
else
{
btnPurchaseGems.setText(price + " = " +"+"+GEMS_TO_ADD );
private void updateBuyButtonText(String price) {
if (price == null || price.isEmpty()) {
btnPurchaseGems.setText("+" + GEMS_TO_ADD);
} else {
btnPurchaseGems.setText(price + " = " + "+" + GEMS_TO_ADD);
}
}
private void checkIfPendingPurchases(){
private void checkIfPendingPurchases() {
billingRequests.getAllPurchases(ProductTypes.IN_APP, new RequestListener<Purchases>() {
@Override
public void onSuccess(@NonNull Purchases purchases) {
for(Purchase purchase : purchases.list){
if(purchase.sku.equals(HabiticaApplication.Purchase20Gems)) {
for (Purchase purchase : purchases.list) {
if (purchase.sku.equals(HabiticaApplication.Purchase20Gems)) {
billingRequests.consume(purchase.token, new RequestListener<Object>() {
@Override
public void onSuccess(@NonNull Object o) {
@ -155,7 +150,7 @@ public class GemsPurchaseFragment extends BaseMainFragment {
}
@Override
public void onError(int i,@NonNull Exception e) {
public void onError(int i, @NonNull Exception e) {
Fabric.getLogger().e("Purchase", "Consume", e);
}
});
@ -164,8 +159,8 @@ public class GemsPurchaseFragment extends BaseMainFragment {
}
@Override
public void onError(int i,@NonNull Exception e) {
Fabric.getLogger().e("Purchase","getAllPurchases", e);
public void onError(int i, @NonNull Exception e) {
Fabric.getLogger().e("Purchase", "getAllPurchases", e);
}
});
}
@ -180,14 +175,13 @@ public class GemsPurchaseFragment extends BaseMainFragment {
// no current product exist
final ActivityCheckout checkout = listener.getActivityCheckout();
billingRequests.purchase(ProductTypes.IN_APP, HabiticaApplication.Purchase20Gems, null, checkout.getPurchaseFlow());
}
else{
} else {
checkIfPendingPurchases();
}
}
@Override
public void onError(int i,@NonNull Exception e) {
public void onError(int i, @NonNull Exception e) {
Fabric.getLogger().e("Purchase", "Error", e);
}
});

View file

@ -15,10 +15,9 @@ import butterknife.ButterKnife;
public class NewsFragment extends BaseMainFragment {
private View view;
@BindView(R.id.news_webview)
WebView newsWebview;
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View file

@ -21,27 +21,27 @@ import butterknife.BindView;
import butterknife.ButterKnife;
public class FAQOverviewFragment extends BaseMainFragment {
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
FAQOverviewRecyclerAdapter adapter;
FAQOverviewRecyclerAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
unbinder = ButterKnife.bind(this, view);
adapter = new FAQOverviewRecyclerAdapter();
adapter.activity = activity;
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
recyclerView.setAdapter(adapter);
this.loadArticles();
unbinder = ButterKnife.bind(this, view);
adapter = new FAQOverviewRecyclerAdapter();
adapter.activity = activity;
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
recyclerView.setAdapter(adapter);
this.loadArticles();
return view;
}
return view;
}
@Override
public void injectFragment(AppComponent component) {
@ -49,13 +49,13 @@ public class FAQOverviewFragment extends BaseMainFragment {
}
private void loadArticles() {
if(user == null || adapter == null){
return;
}
List<FAQArticle> articles = new Select()
.from(FAQArticle.class).queryList();
adapter.setArticles(articles);
if (user == null || adapter == null) {
return;
}
List<FAQArticle> articles = new Select()
.from(FAQArticle.class).queryList();
adapter.setArticles(articles);
}
}

View file

@ -83,7 +83,7 @@ public class AvatarCustomizationFragment extends BaseMainFragment {
}
private void loadCustomizations() {
if(user == null || adapter == null){
if (user == null || adapter == null) {
return;
}
@ -95,10 +95,10 @@ public class AvatarCustomizationFragment extends BaseMainFragment {
.or(Condition.column("price").isNull())
.or(Condition.CombinedCondition.begin(
Condition.CombinedCondition.begin(Condition.column("availableUntil").isNull())
.or(Condition.column("availableUntil").greaterThanOrEq(new Date().getTime())))
.and(Condition.CombinedCondition.begin(Condition.column("availableFrom").isNull())
.or(Condition.column("availableFrom").lessThanOrEq(new Date().getTime()))
)
.or(Condition.column("availableUntil").greaterThanOrEq(new Date().getTime())))
.and(Condition.CombinedCondition.begin(Condition.column("availableFrom").isNull())
.or(Condition.column("availableFrom").lessThanOrEq(new Date().getTime()))
)
)
);
if (this.category != null) {

View file

@ -63,7 +63,9 @@ public class AvatarOverviewFragment extends BaseMainFragment implements AdapterV
if (this.apiHelper != null) {
this.apiHelper.apiService.getContent()
.compose(apiHelper.configureApiCallObserver())
.subscribe(contentResult -> {}, throwable -> {});
.subscribe(contentResult -> {
}, throwable -> {
});
}
}
@ -107,10 +109,10 @@ public class AvatarOverviewFragment extends BaseMainFragment implements AdapterV
}
private void displayCustomizationFragment(String type, String category) {
AvatarCustomizationFragment fragment = new AvatarCustomizationFragment();
fragment.type = type;
fragment.category = category;
activity.displayFragment(fragment);
AvatarCustomizationFragment fragment = new AvatarCustomizationFragment();
fragment.type = type;
fragment.category = category;
activity.displayFragment(fragment);
}
@Override
@ -142,10 +144,12 @@ public class AvatarOverviewFragment extends BaseMainFragment implements AdapterV
updateData.put("preferences.size", newSize);
apiHelper.apiService.updateUser(updateData)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(activity, user), throwable -> {});
.subscribe(new MergeUserCallback(activity, user), throwable -> {
});
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
public void onNothingSelected(AdapterView<?> parent) {
}
}

View file

@ -61,14 +61,14 @@ public class EquipmentDetailFragment extends BaseMainFragment {
}
private void loadGear() {
if(user == null || adapter == null){
if (user == null || adapter == null) {
return;
}
List<ItemData> gear = new Select()
.from(ItemData.class)
.where(Condition.CombinedCondition.begin(Condition.column("type").eq(this.type))
.and(Condition.column("owned").eq(true))
.and(Condition.column("owned").eq(true))
).queryList();
adapter.setGearList(gear);

View file

@ -35,25 +35,21 @@ import butterknife.BindView;
import butterknife.ButterKnife;
public class ItemRecyclerFragment extends BaseFragment {
private static final String ITEM_TYPE_KEY = "CLASS_TYPE_KEY";
@BindView(R.id.recyclerView)
public RecyclerViewEmptySupport recyclerView;
@BindView(R.id.empty_view)
public TextView emptyView;
@BindView(R.id.titleTextView)
public TextView titleView;
public ItemRecyclerAdapter adapter;
public String itemType;
public String itemTypeText;
public Boolean isHatching;
public Boolean isFeeding;
public Item hatchingItem;
public Pet feedingPet;
public HashMap<String, Integer> ownedPets;
private static final String ITEM_TYPE_KEY = "CLASS_TYPE_KEY";
LinearLayoutManager layoutManager = null;
private View view;
@ -78,7 +74,7 @@ public class ItemRecyclerFragment extends BaseFragment {
recyclerView.setLayoutManager(layoutManager);
}
adapter = (ItemRecyclerAdapter)recyclerView.getAdapter();
adapter = (ItemRecyclerAdapter) recyclerView.getAdapter();
if (adapter == null) {
adapter = new ItemRecyclerAdapter();
adapter.context = this.getActivity();
@ -96,7 +92,7 @@ public class ItemRecyclerFragment extends BaseFragment {
}
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
if (savedInstanceState != null){
if (savedInstanceState != null) {
this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "");
}

View file

@ -112,7 +112,8 @@ public class ItemsFragment extends BaseMainFragment {
OpenMenuItemCommand event1 = new OpenMenuItemCommand();
event1.identifier = MainDrawerBuilder.SIDEBAR_PARTY;
EventBus.getDefault().post(event1);
}, throwable -> {});
}, throwable -> {
});
}
@Subscribe
@ -121,7 +122,7 @@ public class ItemsFragment extends BaseMainFragment {
ItemRecyclerFragment fragment = new ItemRecyclerFragment();
if (event.usingEgg != null) {
fragment.itemType = "hatchingPotions";
fragment.hatchingItem= event.usingEgg;
fragment.hatchingItem = event.usingEgg;
} else {
fragment.itemType = "eggs";
fragment.hatchingItem = event.usingHatchingPotion;

View file

@ -20,12 +20,12 @@ import android.view.ViewGroup;
import java.util.List;
public class MountDetailRecyclerFragment extends BaseMainFragment {
private static final String ANIMAL_TYPE_KEY = "ANIMAL_TYPE_KEY";
public RecyclerView recyclerView;
public MountDetailRecyclerAdapter adapter;
public String animalType;
public String animalGroup;
public List<Mount> animals;
private static final String ANIMAL_TYPE_KEY = "ANIMAL_TYPE_KEY";
GridLayoutManager layoutManager = null;
private View view;
@ -45,7 +45,7 @@ public class MountDetailRecyclerFragment extends BaseMainFragment {
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new MarginDecoration(getActivity()));
adapter = (MountDetailRecyclerAdapter)recyclerView.getAdapter();
adapter = (MountDetailRecyclerAdapter) recyclerView.getAdapter();
if (adapter == null) {
adapter = new MountDetailRecyclerAdapter();
adapter.context = this.getActivity();
@ -56,7 +56,7 @@ public class MountDetailRecyclerFragment extends BaseMainFragment {
}
}
if (savedInstanceState != null){
if (savedInstanceState != null) {
this.animalType = savedInstanceState.getString(ANIMAL_TYPE_KEY, "");
}
@ -82,7 +82,6 @@ public class MountDetailRecyclerFragment extends BaseMainFragment {
}
private void setGridSpanCount(int width) {
float itemWidth;
itemWidth = getContext().getResources().getDimension(R.dimen.pet_width);

View file

@ -25,12 +25,12 @@ import android.view.ViewGroup;
import java.util.List;
public class PetDetailRecyclerFragment extends BaseMainFragment {
private static final String ANIMAL_TYPE_KEY = "ANIMAL_TYPE_KEY";
public RecyclerView recyclerView;
public PetDetailRecyclerAdapter adapter;
public String animalType;
public String animalGroup;
public List<Pet> animals;
private static final String ANIMAL_TYPE_KEY = "ANIMAL_TYPE_KEY";
GridLayoutManager layoutManager = null;
private View view;
@ -50,7 +50,7 @@ public class PetDetailRecyclerFragment extends BaseMainFragment {
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new MarginDecoration(getActivity()));
adapter = (PetDetailRecyclerAdapter)recyclerView.getAdapter();
adapter = (PetDetailRecyclerAdapter) recyclerView.getAdapter();
if (adapter == null) {
adapter = new PetDetailRecyclerAdapter();
adapter.context = this.getActivity();
@ -61,7 +61,7 @@ public class PetDetailRecyclerFragment extends BaseMainFragment {
}
}
if (savedInstanceState != null){
if (savedInstanceState != null) {
this.animalType = savedInstanceState.getString(ANIMAL_TYPE_KEY, "");
}
@ -102,7 +102,7 @@ public class PetDetailRecyclerFragment extends BaseMainFragment {
Runnable itemsRunnable = () -> {
List<Pet> items = new Select().from(Pet.class).where(Condition.CombinedCondition
.begin(Condition.column("animal").eq(animalType))
.and(Condition.column("animalGroup").eq(animalGroup))).orderBy(true, "color").queryList();
.and(Condition.column("animalGroup").eq(animalGroup))).orderBy(true, "color").queryList();
adapter.setItemList(items);
animals = items;
adapter.setOwnedMapping(user.getItems().getPets());

View file

@ -37,17 +37,15 @@ import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class StableRecyclerFragment extends BaseFragment {
private static final String ITEM_TYPE_KEY = "CLASS_TYPE_KEY";
@BindView(R.id.recyclerView)
public RecyclerViewEmptySupport recyclerView;
@BindView(R.id.empty_view)
public TextView emptyView;
public StableRecyclerAdapter adapter;
public String itemType;
public String itemTypeText;
public HabitRPGUser user;
private static final String ITEM_TYPE_KEY = "CLASS_TYPE_KEY";
GridLayoutManager layoutManager = null;
private View view;
@ -83,15 +81,15 @@ public class StableRecyclerFragment extends BaseFragment {
}
adapter = (StableRecyclerAdapter)recyclerView.getAdapter();
adapter = (StableRecyclerAdapter) recyclerView.getAdapter();
if (adapter == null) {
adapter = new StableRecyclerAdapter();
adapter.activity = (MainActivity)this.getActivity();
adapter.activity = (MainActivity) this.getActivity();
adapter.itemType = this.itemType;
recyclerView.setAdapter(adapter);
}
if (savedInstanceState != null){
if (savedInstanceState != null) {
this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "");
}
@ -118,7 +116,6 @@ public class StableRecyclerFragment extends BaseFragment {
}
private void setGridSpanCount(int width) {
float itemWidth;
itemWidth = getContext().getResources().getDimension(R.dimen.pet_width);
@ -168,8 +165,8 @@ public class StableRecyclerFragment extends BaseFragment {
lastAnimal = animal;
}
if (!animal.getAnimalGroup().equals(lastSectionTitle)) {
if (items.size() > 0 && items.get(items.size()-1).getClass().equals(String.class)) {
items.remove(items.size()-1);
if (items.size() > 0 && items.get(items.size() - 1).getClass().equals(String.class)) {
items.remove(items.size() - 1);
}
items.add(animal.getAnimalGroup());
lastSectionTitle = animal.getAnimalGroup();
@ -207,7 +204,8 @@ public class StableRecyclerFragment extends BaseFragment {
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> {
adapter.setItemList(items);
}, throwable -> {});
}, throwable -> {
});
}
@Subscribe

View file

@ -29,19 +29,34 @@ import javax.inject.Inject;
public class PreferencesFragment extends BasePreferencesFragment implements
SharedPreferences.OnSharedPreferenceChangeListener {
@Inject
public APIHelper apiHelper;
private Context context;
private TimePreference timePreference;
private Preference classSelectionPreference;
private HabitRPGUser user;
private TransactionListener<HabitRPGUser> userTransactionListener = new TransactionListener<HabitRPGUser>() {
@Override
public void onResultReceived(HabitRPGUser habitRPGUser) {
PreferencesFragment.this.setUser(habitRPGUser);
}
@Inject
public APIHelper apiHelper;
@Override
public boolean onReady(BaseTransaction<HabitRPGUser> baseTransaction) {
return true;
}
@Override
public boolean hasResult(BaseTransaction<HabitRPGUser> baseTransaction, HabitRPGUser habitRPGUser) {
return true;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((HabiticaApplication)getActivity().getApplication()).getComponent().inject(this);
((HabiticaApplication) getActivity().getApplication()).getComponent().inject(this);
context = getActivity();
String userID = getPreferenceManager().getSharedPreferences().getString(context.getString(R.string.SP_userID), null);
@ -74,23 +89,6 @@ public class PreferencesFragment extends BasePreferencesFragment implements
super.onPause();
}
private TransactionListener<HabitRPGUser> userTransactionListener = new TransactionListener<HabitRPGUser>() {
@Override
public void onResultReceived(HabitRPGUser habitRPGUser) {
PreferencesFragment.this.setUser(habitRPGUser);
}
@Override
public boolean onReady(BaseTransaction<HabitRPGUser> baseTransaction) {
return true;
}
@Override
public boolean hasResult(BaseTransaction<HabitRPGUser> baseTransaction, HabitRPGUser habitRPGUser) {
return true;
}
};
@Override
public boolean onPreferenceTreeClick(Preference preference) {
if (preference.getKey().equals("logout")) {

View file

@ -28,20 +28,16 @@ import butterknife.ButterKnife;
public class AvatarSetupFragment extends BaseFragment {
View view;
public SetupActivity activity;
private HabitRPGUser user;
public int width;
View view;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.avatarView)
AvatarView avatarView;
CustomizationSetupAdapter adapter;
GridLayoutManager layoutManager;
private HabitRPGUser user;
@Nullable
@Override
@ -94,15 +90,15 @@ public class AvatarSetupFragment extends BaseFragment {
}
private void loadCustomizations() {
if(this.user == null || this.adapter == null){
if (this.user == null || this.adapter == null) {
return;
}
Where<Customization> select = new Select()
.from(Customization.class)
.where(Condition.CombinedCondition.begin(Condition.column("purchased").eq(true))
.or(Condition.column("price").eq(0))
.or(Condition.column("price").isNull())
.or(Condition.column("price").eq(0))
.or(Condition.column("price").isNull())
);
List<Customization> customizations = select.queryList();

View file

@ -26,18 +26,14 @@ import butterknife.ButterKnife;
public class TaskSetupFragment extends BaseFragment {
View view;
public SetupActivity activity;
public int width;
private String[][] taskGroups;
private Object[][] tasks;
View view;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
TaskSetupAdapter adapter;
private String[][] taskGroups;
private Object[][] tasks;
@Nullable
@Override

View file

@ -17,65 +17,63 @@ import android.view.View;
import android.view.ViewGroup;
public class SkillTasksRecyclerViewFragment extends BaseFragment implements View.OnClickListener {
public RecyclerView mRecyclerView;
public RecyclerView.Adapter mAdapter;
private String classType;
public RecyclerView mRecyclerView;
public RecyclerView.Adapter mAdapter;
LinearLayoutManager layoutManager = null;
private String classType;
private View view;
public void SetInnerAdapter(SkillTasksRecyclerViewAdapter adapter, String classType) {
this.classType = classType;
mAdapter = adapter;
}
public static SkillTasksRecyclerViewFragment newInstance(SkillTasksRecyclerViewAdapter adapter, String classType) {
SkillTasksRecyclerViewFragment fragment = new SkillTasksRecyclerViewFragment();
fragment.setRetainInstance(true);
private View view;
fragment.SetInnerAdapter(adapter, classType);
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null)
view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
return fragment;
}
return view;
}
public void SetInnerAdapter(SkillTasksRecyclerViewAdapter adapter, String classType) {
this.classType = classType;
mAdapter = adapter;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null)
view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
return view;
}
@Override
public void injectFragment(AppComponent component) {
component.inject(this);
}
LinearLayoutManager layoutManager = null;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
android.support.v4.app.FragmentActivity context = getActivity();
android.support.v4.app.FragmentActivity context = getActivity();
layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
if (layoutManager == null) {
layoutManager = new LinearLayoutManager(context);
if (layoutManager == null) {
layoutManager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(layoutManager);
}
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(layoutManager);
}
public static SkillTasksRecyclerViewFragment newInstance(SkillTasksRecyclerViewAdapter adapter, String classType) {
SkillTasksRecyclerViewFragment fragment = new SkillTasksRecyclerViewFragment();
fragment.setRetainInstance(true);
mRecyclerView.setAdapter(mAdapter);
}
fragment.SetInnerAdapter(adapter, classType);
@Override
public void onClick(View v) {
AddNewTaskCommand event = new AddNewTaskCommand();
event.ClassType = this.classType;
return fragment;
}
@Override
public void onClick(View v) {
AddNewTaskCommand event = new AddNewTaskCommand();
event.ClassType = this.classType;
EventBus.getDefault().post(event);
}
EventBus.getDefault().post(event);
}
}

View file

@ -37,10 +37,11 @@ import rx.Observable;
public class SkillsFragment extends BaseMainFragment {
private final int TASK_SELECTION_ACTIVITY = 10;
@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
SkillsRecyclerViewAdapter adapter;
private View view;
private Skill selectedSkill;
private ProgressDialog progressDialog;
@Nullable
@ -64,11 +65,6 @@ public class SkillsFragment extends BaseMainFragment {
component.inject(this);
}
@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
SkillsRecyclerViewAdapter adapter;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@ -77,8 +73,8 @@ public class SkillsFragment extends BaseMainFragment {
mRecyclerView.setAdapter(adapter);
}
private void checkUserLoadSkills(){
if(user == null || adapter == null){
private void checkUserLoadSkills() {
if (user == null || adapter == null) {
return;
}
@ -119,14 +115,15 @@ public class SkillsFragment extends BaseMainFragment {
UiUtils.showSnackbar(activity, activity.getFloatingMenuWrapper(), activity.getString(R.string.used_skill, skill.text, skill.mana), UiUtils.SnackbarDisplayType.NORMAL);
apiHelper.apiService.getUser()
.compose(apiHelper.configureApiCallObserver())
.subscribe(new MergeUserCallback(activity, user), throwable -> {});
.subscribe(new MergeUserCallback(activity, user), throwable -> {
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (TASK_SELECTION_ACTIVITY) : {
switch (requestCode) {
case (TASK_SELECTION_ACTIVITY): {
if (resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, data.getStringExtra("task_id"));
}

View file

@ -46,15 +46,23 @@ import rx.functions.Action1;
public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, Action1<List<ChatMessage>> {
private String groupId;
public String seenGroupId;
@Inject
public APIHelper apiHelper;
public boolean isTavern;
@BindView(R.id.chat_list)
RecyclerView mRecyclerView;
@BindView(R.id.chat_refresh_layout)
SwipeRefreshLayout swipeRefreshLayout;
LinearLayoutManager layoutManager;
private String groupId;
private HabitRPGUser user;
private String userId;
public boolean isTavern;
private ChatRecyclerViewAdapter chatAdapter;
private View view;
private List<ChatMessage> currentChatMessages;
private boolean navigatedOnceToFragment = false;
private boolean gotNewMessages = false;
public void configure(String groupId, HabitRPGUser user, boolean isTavern) {
this.groupId = groupId;
@ -65,27 +73,25 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
this.isTavern = isTavern;
}
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("groupId")) {
this.groupId = savedInstanceState.getString("groupId");
}
if (savedInstanceState.containsKey("isTavern")) {
this.isTavern = savedInstanceState.getBoolean("isTavern");
}
if (savedInstanceState.containsKey("userId")) {
this.userId = savedInstanceState.getString("userId");
if (this.userId != null) {
this.user = new Select().from(HabitRPGUser.class).where(Condition.column("id").eq(userId)).querySingle();
if (savedInstanceState.containsKey("groupId")) {
this.groupId = savedInstanceState.getString("groupId");
}
if (savedInstanceState.containsKey("isTavern")) {
this.isTavern = savedInstanceState.getBoolean("isTavern");
}
if (savedInstanceState.containsKey("userId")) {
this.userId = savedInstanceState.getString("userId");
if (this.userId != null) {
this.user = new Select().from(HabitRPGUser.class).where(Condition.column("id").eq(userId)).querySingle();
}
}
}
}
@ -100,14 +106,6 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
component.inject(this);
}
@BindView(R.id.chat_list)
RecyclerView mRecyclerView;
@BindView(R.id.chat_refresh_layout)
SwipeRefreshLayout swipeRefreshLayout;
LinearLayoutManager layoutManager;
@Override
public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@ -136,30 +134,28 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
swipeRefreshLayout.setRefreshing(true);
apiHelper.apiService.listGroupChat(groupId).compose(apiHelper.configureApiCallObserver())
.subscribe(this, throwable -> {});
.subscribe(this, throwable -> {
});
}
private List<ChatMessage> currentChatMessages;
public void setNavigatedToFragment(String groupId){
public void setNavigatedToFragment(String groupId) {
seenGroupId = groupId;
navigatedOnceToFragment = true;
markMessagesAsSeen();
}
private boolean navigatedOnceToFragment = false;
private boolean gotNewMessages = false;
private void markMessagesAsSeen(){
if(!isTavern && seenGroupId != null && !seenGroupId.isEmpty()
private void markMessagesAsSeen() {
if (!isTavern && seenGroupId != null && !seenGroupId.isEmpty()
&& gotNewMessages && navigatedOnceToFragment) {
gotNewMessages = false;
apiHelper.apiService.seenMessages(seenGroupId)
.compose(apiHelper.configureApiCallObserver())
.subscribe(s -> {}, throwable -> {});
.subscribe(s -> {
}, throwable -> {
});
}
}
@ -171,9 +167,10 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
apiHelper.apiService.flagMessage(cmd.groupId, cmd.chatMessage.id)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
MainActivity activity = (MainActivity)getActivity();
MainActivity activity = (MainActivity) getActivity();
UiUtils.showSnackbar(activity, activity.getFloatingMenuWrapper(), "Flagged message by " + cmd.chatMessage.user, UiUtils.SnackbarDisplayType.NORMAL);
}, throwable -> {});
}, throwable -> {
});
})
.setNegativeButton(R.string.action_cancel, (dialog, id) -> {
});
@ -183,7 +180,9 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
@Subscribe
public void onEvent(final ToggleLikeMessageCommand cmd) {
apiHelper.apiService.likeMessage(cmd.groupId, cmd.chatMessage.id).compose(apiHelper.configureApiCallObserver())
.subscribe(voids -> {}, throwable -> {});
.subscribe(voids -> {
}, throwable -> {
});
}
@Subscribe
@ -191,12 +190,13 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
apiHelper.apiService.deleteMessage(cmd.groupId, cmd.chatMessage.id)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
if (currentChatMessages != null) {
currentChatMessages.remove(cmd.chatMessage);
if (currentChatMessages != null) {
currentChatMessages.remove(cmd.chatMessage);
ChatListFragment.this.call(currentChatMessages);
}
}, throwable -> {});
ChatListFragment.this.call(currentChatMessages);
}
}, throwable -> {
});
}
@Subscribe
@ -206,12 +206,13 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
apiHelper.apiService.postGroupChat(cmd.TargetGroupId, messageObject)
.compose(apiHelper.configureApiCallObserver())
.subscribe(postChatMessageResult -> {
if (currentChatMessages != null) {
currentChatMessages.add(0, postChatMessageResult.message);
if (currentChatMessages != null) {
currentChatMessages.add(0, postChatMessageResult.message);
ChatListFragment.this.call(currentChatMessages);
}
}, throwable -> {});
ChatListFragment.this.call(currentChatMessages);
}
}, throwable -> {
});
UiUtils.dismissKeyboard(HabiticaApplication.currentActivity);
}
@ -227,7 +228,8 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
user.getPreferences().setSleep(innState.Inn);
EventBus.getDefault().post(innState);
}, throwable -> {});
}, throwable -> {
});
}
@Override
@ -269,7 +271,7 @@ public class ChatListFragment extends BaseFragment implements SwipeRefreshLayout
@Override
protected Void doInBackground(Void... params) {
for (int i = 0; i < chatMessages.size() ; i++) {
for (int i = 0; i < chatMessages.size(); i++) {
chatMessages.get(i).parsedText = MarkdownParser.parseMarkdown(chatMessages.get(i).text);
}

View file

@ -34,7 +34,6 @@ import butterknife.OnClick;
public class GroupInformationFragment extends BaseFragment {
private View view;
FragmentGroupInfoBinding viewBinding;
@Inject
APIHelper apiHelper;
@ -42,6 +41,7 @@ public class GroupInformationFragment extends BaseFragment {
LinearLayout questMemberView;
@BindView(R.id.collectionStats)
RecyclerView collectionStats;
private View view;
private Group group;
private HabitRPGUser user;
private QuestContent quest;
@ -50,6 +50,10 @@ public class GroupInformationFragment extends BaseFragment {
private QuestCollectRecyclerViewAdapter questCollectViewAdapter;
public GroupInformationFragment() {
}
public static GroupInformationFragment newInstance(Group group, HabitRPGUser user) {
Bundle args = new Bundle();
@ -61,10 +65,6 @@ public class GroupInformationFragment extends BaseFragment {
return fragment;
}
public GroupInformationFragment(){
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@ -195,11 +195,12 @@ public class GroupInformationFragment extends BaseFragment {
apiHelper.apiService.acceptQuest(group.id)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
user.getParty().getQuest().RSVPNeeded = false;
group.quest.members.put(user.getId(), true);
setGroup(group);
viewBinding.setUser(user);
}, throwable -> {});
user.getParty().getQuest().RSVPNeeded = false;
group.quest.members.put(user.getId(), true);
setGroup(group);
viewBinding.setUser(user);
}, throwable -> {
});
}
@ -208,11 +209,12 @@ public class GroupInformationFragment extends BaseFragment {
apiHelper.apiService.rejectQuest(group.id)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
user.getParty().getQuest().RSVPNeeded = false;
group.quest.members.put(user.getId(), false);
setGroup(group);
viewBinding.setUser(user);
}, throwable -> {});
user.getParty().getQuest().RSVPNeeded = false;
group.quest.members.put(user.getId(), false);
setGroup(group);
viewBinding.setUser(user);
}, throwable -> {
});
}
@ -224,9 +226,10 @@ public class GroupInformationFragment extends BaseFragment {
apiHelper.apiService.leaveQuest(group.id)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
group.quest.members.remove(user.getId());
setGroup(group);
}, throwable -> {});
group.quest.members.remove(user.getId());
setGroup(group);
}, throwable -> {
});
}).setNegativeButton("No", (dialog, which) -> {
});
@ -244,7 +247,8 @@ public class GroupInformationFragment extends BaseFragment {
.subscribe(quest -> {
group.quest = quest;
setGroup(group);
}, throwable -> {});
}, throwable -> {
});
}).setNegativeButton(R.string.no, (dialog, which) -> {
});
@ -259,9 +263,10 @@ public class GroupInformationFragment extends BaseFragment {
apiHelper.apiService.cancelQuest(group.id)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
setGroup(group);
setQuestContent(null);
}, throwable -> {});
setGroup(group);
setQuestContent(null);
}, throwable -> {
});
}).setNegativeButton(R.string.no, (dialog, which) -> {
});
@ -279,7 +284,8 @@ public class GroupInformationFragment extends BaseFragment {
group.quest = quest;
setGroup(group);
setQuestContent(null);
}, throwable -> {});
}, throwable -> {
});
}).setNegativeButton("No", (dialog, which) -> {
});

View file

@ -23,11 +23,9 @@ import rx.functions.Action1;
public class GuildFragment extends BaseMainFragment implements Action1<Group> {
private Group guild;
public boolean isMember;
public ViewPager viewPager;
private Group guild;
private GroupInformationFragment guildInformationFragment;
private ChatListFragment chatListFragment;
@ -39,7 +37,8 @@ public class GuildFragment extends BaseMainFragment implements Action1<Group> {
if (this.guild.chat == null) {
if (this.apiHelper != null) {
apiHelper.apiService.getGroup(this.guild.id).compose(apiHelper.configureApiCallObserver())
.subscribe(this, throwable -> {});
.subscribe(this, throwable -> {
});
}
}
}
@ -70,7 +69,8 @@ public class GuildFragment extends BaseMainFragment implements Action1<Group> {
super.onViewCreated(view, savedInstanceState);
if (this.apiHelper != null && this.guild != null) {
apiHelper.apiService.getGroup(this.guild.id).compose(apiHelper.configureApiCallObserver())
.subscribe(this, throwable -> {});
.subscribe(this, throwable -> {
});
}
}
@ -95,14 +95,16 @@ public class GuildFragment extends BaseMainFragment implements Action1<Group> {
switch (id) {
case R.id.menu_guild_join:
this.apiHelper.apiService.joinGroup(this.guild.id).compose(apiHelper.configureApiCallObserver())
.subscribe(this, throwable -> {});
.subscribe(this, throwable -> {
});
this.isMember = true;
return true;
case R.id.menu_guild_leave:
this.apiHelper.apiService.leaveGroup(this.guild.id).compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {
this.activity.supportInvalidateOptionsMenu();
}, throwable -> {});
}, throwable -> {
});
this.isMember = false;
return true;
case R.id.menu_guild_edit:
@ -185,11 +187,11 @@ public class GuildFragment extends BaseMainFragment implements Action1<Group> {
private void displayEditForm() {
Bundle bundle = new Bundle();
bundle.putString("groupID",this.guild.id);
bundle.putString("name",this.guild.name);
bundle.putString("description",this.guild.description);
bundle.putString("privacy",this.guild.privacy);
bundle.putString("leader",this.guild.leaderID);
bundle.putString("groupID", this.guild.id);
bundle.putString("name", this.guild.name);
bundle.putString("description", this.guild.description);
bundle.putString("privacy", this.guild.privacy);
bundle.putString("leader", this.guild.leaderID);
Intent intent = new Intent(activity, GroupFormActivity.class);
intent.putExtras(bundle);
@ -200,8 +202,8 @@ public class GuildFragment extends BaseMainFragment implements Action1<Group> {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (GroupFormActivity.GROUP_FORM_ACTIVITY) : {
switch (requestCode) {
case (GroupFormActivity.GROUP_FORM_ACTIVITY): {
if (resultCode == Activity.RESULT_OK) {
boolean needsSaving = false;
Bundle bundle = data.getExtras();
@ -224,7 +226,9 @@ public class GuildFragment extends BaseMainFragment implements Action1<Group> {
if (needsSaving) {
this.apiHelper.apiService.updateGroup(this.guild.id, this.guild)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {}, throwable -> {});
.subscribe(aVoid -> {
}, throwable -> {
});
this.guildInformationFragment.setGroup(guild);
}
}

View file

@ -24,7 +24,7 @@ import butterknife.ButterKnife;
public class GuildsOverviewFragment extends BaseMainFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
@BindView(R.id.my_guilds_listview)
LinearLayout guildsListView;
LinearLayout guildsListView;
@BindView(R.id.publicGuildsButton)
Button publicGuildsButton;
@ -72,12 +72,13 @@ public class GuildsOverviewFragment extends BaseMainFragment implements View.OnC
this.apiHelper.apiService.listGroups("guilds")
.compose(apiHelper.configureApiCallObserver())
.subscribe(groups -> {
GuildsOverviewFragment.this.guilds = groups;
GuildsOverviewFragment.this.setGuildsOnListView();
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setRefreshing(false);
}
}, throwable -> {});
GuildsOverviewFragment.this.guilds = groups;
GuildsOverviewFragment.this.setGuildsOnListView();
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setRefreshing(false);
}
}, throwable -> {
});
}
}
@ -87,7 +88,7 @@ public class GuildsOverviewFragment extends BaseMainFragment implements View.OnC
}
this.guildIDs = new ArrayList<>();
this.guildsListView.removeAllViewsInLayout();
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (Group guild : this.guilds) {
TextView entry = (TextView) inflater.inflate(R.layout.plain_list_item, this.guildsListView, false);
entry.setText(guild.name);
@ -104,7 +105,7 @@ public class GuildsOverviewFragment extends BaseMainFragment implements View.OnC
publicGuildsFragment.memberGuildIDs = this.guildIDs;
this.activity.displayFragment(publicGuildsFragment);
} else {
Integer guildIndex = ((ViewGroup)v.getParent()).indexOfChild(v);
Integer guildIndex = ((ViewGroup) v.getParent()).indexOfChild(v);
GuildFragment guildFragment = new GuildFragment();
guildFragment.setGuild(this.guilds.get(guildIndex));
guildFragment.isMember = true;

View file

@ -23,7 +23,7 @@ import butterknife.ButterKnife;
public class PublicGuildsFragment extends BaseMainFragment {
List<String> memberGuildIDs;
List <Group> guilds;
List<Group> guilds;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@ -68,11 +68,12 @@ public class PublicGuildsFragment extends BaseMainFragment {
this.apiHelper.apiService.listGroups("publicGuilds")
.compose(apiHelper.configureApiCallObserver())
.subscribe(groups -> {
PublicGuildsFragment.this.guilds = groups;
if (PublicGuildsFragment.this.viewAdapter!= null) {
PublicGuildsFragment.this.viewAdapter.setPublicGuildList(groups);
}
}, throwable -> {});
PublicGuildsFragment.this.guilds = groups;
if (PublicGuildsFragment.this.viewAdapter != null) {
PublicGuildsFragment.this.viewAdapter.setPublicGuildList(groups);
}
}, throwable -> {
});
}
}
}

View file

@ -52,23 +52,24 @@ public class TavernFragment extends BaseMainFragment {
apiHelper.apiService.getGroup("habitrpg")
.compose(apiHelper.configureApiCallObserver())
.subscribe(group -> {
TavernFragment.this.tavern = group;
if (group.quest != null && group.quest.key != null && TavernFragment.this.isAdded()) {
TavernFragment.this.viewPager.getAdapter().notifyDataSetChanged();
if (TavernFragment.this.tabLayout != null) {
TavernFragment.this.tabLayout.setVisibility(View.VISIBLE);
TavernFragment.this.tabLayout.setupWithViewPager(TavernFragment.this.viewPager);
}
TavernFragment.this.tavern = group;
if (group.quest != null && group.quest.key != null && TavernFragment.this.isAdded()) {
TavernFragment.this.viewPager.getAdapter().notifyDataSetChanged();
if (TavernFragment.this.tabLayout != null) {
TavernFragment.this.tabLayout.setVisibility(View.VISIBLE);
TavernFragment.this.tabLayout.setupWithViewPager(TavernFragment.this.viewPager);
}
ContentCache contentCache = new ContentCache(apiHelper.apiService);
ContentCache contentCache = new ContentCache(apiHelper.apiService);
contentCache.GetQuestContent(group.quest.key, content -> {
if (questInfoFragment != null) {
questInfoFragment.setQuestContent(content);
contentCache.GetQuestContent(group.quest.key, content -> {
if (questInfoFragment != null) {
questInfoFragment.setQuestContent(content);
}
});
}
}, throwable -> {
});
}
}, throwable -> {});
}
}

View file

@ -73,8 +73,10 @@ public class PartyFragment extends BaseMainFragment {
PartyFragment.this.group.members = members;
updateGroupUI();
},
throwable -> {});
}, throwable -> {});
throwable -> {
});
}, throwable -> {
});
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setMessage(activity.getString(R.string.no_party_message))
@ -109,7 +111,7 @@ public class PartyFragment extends BaseMainFragment {
groupInformationFragment.setGroup(group);
}
if(chatListFragment != null){
if (chatListFragment != null) {
chatListFragment.seenGroupId = group.id;
}
@ -153,8 +155,9 @@ public class PartyFragment extends BaseMainFragment {
case R.id.menu_guild_leave:
this.apiHelper.apiService.leaveGroup(this.group.id).compose(apiHelper.configureApiCallObserver())
.subscribe(group -> {
getActivity().getSupportFragmentManager().beginTransaction().remove(PartyFragment.this).commit();
}, throwable -> {});
getActivity().getSupportFragmentManager().beginTransaction().remove(PartyFragment.this).commit();
}, throwable -> {
});
return true;
}
@ -163,10 +166,10 @@ public class PartyFragment extends BaseMainFragment {
private void displayEditForm() {
Bundle bundle = new Bundle();
bundle.putString("groupID",this.group.id);
bundle.putString("name",this.group.name);
bundle.putString("description",this.group.description);
bundle.putString("leader",this.group.leaderID);
bundle.putString("groupID", this.group.id);
bundle.putString("name", this.group.name);
bundle.putString("description", this.group.description);
bundle.putString("leader", this.group.leaderID);
Intent intent = new Intent(activity, GroupFormActivity.class);
intent.putExtras(bundle);
@ -177,8 +180,8 @@ public class PartyFragment extends BaseMainFragment {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (GroupFormActivity.GROUP_FORM_ACTIVITY) : {
switch (requestCode) {
case (GroupFormActivity.GROUP_FORM_ACTIVITY): {
if (resultCode == Activity.RESULT_OK) {
boolean needsSaving = false;
Bundle bundle = data.getExtras();
@ -201,13 +204,15 @@ public class PartyFragment extends BaseMainFragment {
if (needsSaving) {
this.apiHelper.apiService.updateGroup(this.group.id, this.group)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {}, throwable -> {});
.subscribe(aVoid -> {
}, throwable -> {
});
this.groupInformationFragment.setGroup(group);
}
}
break;
}
case (PartyInviteActivity.RESULT_SEND_INVITES) : {
case (PartyInviteActivity.RESULT_SEND_INVITES): {
if (resultCode == Activity.RESULT_OK) {
Map<String, Object> inviteData = new HashMap<>();
inviteData.put("inviter", this.user.getProfile().getName());
@ -229,7 +234,9 @@ public class PartyFragment extends BaseMainFragment {
}
this.apiHelper.apiService.inviteToGroup(this.group.id, inviteData)
.compose(apiHelper.configureApiCallObserver())
.subscribe(aVoid -> {}, throwable -> {});
.subscribe(aVoid -> {
}, throwable -> {
});
}
}
}
@ -243,7 +250,7 @@ public class PartyFragment extends BaseMainFragment {
UserParty party = this.user.getParty();
if(party == null) {
if (party == null) {
return;
}

View file

@ -68,8 +68,8 @@ public class PartyInviteFragment extends BaseFragment {
public String[] getValues() {
List<String> values = new ArrayList<>();
for (int i = 0; i < invitationWrapper.getChildCount();i++) {
EditText valueEditText = (EditText)invitationWrapper.getChildAt(i);
for (int i = 0; i < invitationWrapper.getChildCount(); i++) {
EditText valueEditText = (EditText) invitationWrapper.getChildAt(i);
if (valueEditText.getText().toString().length() > 0) {
values.add(valueEditText.getText().toString());
}

View file

@ -24,10 +24,12 @@ import butterknife.BindView;
*/
public class PartyMemberListFragment extends BaseFragment {
@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private Context ctx;
private List<HabitRPGUser> members;
private PartyMemberRecyclerViewAdapter viewAdapter;
private View view;
public void configure(Context ctx, List<HabitRPGUser> members) {
this.ctx = ctx;
@ -35,11 +37,6 @@ public class PartyMemberListFragment extends BaseFragment {
}
private View view;
@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View file

@ -35,20 +35,28 @@ import javax.inject.Named;
* - Handles the ScrollPosition - if anyone has a better solution please share it
*/
public class TaskRecyclerViewFragment extends BaseFragment implements View.OnClickListener {
private static final String CLASS_TYPE_KEY = "CLASS_TYPE_KEY";
public RecyclerView recyclerView;
public BaseTasksRecyclerViewAdapter recyclerAdapter;
private String classType;
private HabitRPGUser user;
private static final String CLASS_TYPE_KEY = "CLASS_TYPE_KEY";
@Inject @Named("UserID")
@Inject
@Named("UserID")
String userID;
@Inject
APIHelper apiHelper;
@Inject
TagsHelper tagsHelper;
LinearLayoutManager layoutManager = null;
private String classType;
private HabitRPGUser user;
private View view;
public static TaskRecyclerViewFragment newInstance(HabitRPGUser user, String classType) {
TaskRecyclerViewFragment fragment = new TaskRecyclerViewFragment();
fragment.setRetainInstance(true);
fragment.user = user;
fragment.classType = classType;
return fragment;
}
// TODO needs a bit of cleanup
public void setInnerAdapter() {
@ -77,8 +85,6 @@ public class TaskRecyclerViewFragment extends BaseFragment implements View.OnCli
}
}
private View view;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null) {
@ -101,7 +107,7 @@ public class TaskRecyclerViewFragment extends BaseFragment implements View.OnCli
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
}
if (savedInstanceState != null){
if (savedInstanceState != null) {
this.classType = savedInstanceState.getString(CLASS_TYPE_KEY, "");
}
@ -136,8 +142,6 @@ public class TaskRecyclerViewFragment extends BaseFragment implements View.OnCli
component.inject(this);
}
LinearLayoutManager layoutManager = null;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@ -150,14 +154,6 @@ public class TaskRecyclerViewFragment extends BaseFragment implements View.OnCli
outState.putString(CLASS_TYPE_KEY, this.classType);
}
public static TaskRecyclerViewFragment newInstance(HabitRPGUser user, String classType) {
TaskRecyclerViewFragment fragment = new TaskRecyclerViewFragment();
fragment.setRetainInstance(true);
fragment.user = user;
fragment.classType = classType;
return fragment;
}
@Override
public void onClick(View v) {
AddNewTaskCommand event = new AddNewTaskCommand();

View file

@ -72,17 +72,11 @@ public class TasksFragment extends BaseMainFragment implements OnCheckedChangeLi
private static final int TASK_UPDATED_RESULT = 2;
public ViewPager viewPager;
MenuItem refreshItem;
FloatingActionMenu floatingMenu;
Map<Integer, TaskRecyclerViewFragment> ViewFragmentsDictionary = new HashMap<>();
@Inject
public TagsHelper tagsHelper; // This will be used for this fragment. Currently being used to help filtering
MenuItem refreshItem;
FloatingActionMenu floatingMenu;
Map<Integer, TaskRecyclerViewFragment> ViewFragmentsDictionary = new HashMap<>();
private ArrayList<String> tagNames; // Added this so other activities/fragments can get the String names, not IDs
private ArrayList<String> tagIds; // Added this so other activities/fragments can get the IDs
@ -265,7 +259,7 @@ public class TasksFragment extends BaseMainFragment implements OnCheckedChangeLi
for (TaskRecyclerViewFragment fragm : ViewFragmentsDictionary.values()) {
if (fragm != null) {
BaseTasksRecyclerViewAdapter adapter= fragm.recyclerAdapter;
BaseTasksRecyclerViewAdapter adapter = fragm.recyclerAdapter;
if (adapter.getClass().equals(DailiesRecyclerViewHolder.class)) {
final DailiesRecyclerViewHolder dailyAdapter = (DailiesRecyclerViewHolder) fragm.recyclerAdapter;
dailyAdapter.dailyResetOffset = this.user.getPreferences().getDayStart();
@ -282,7 +276,7 @@ public class TasksFragment extends BaseMainFragment implements OnCheckedChangeLi
}
String allocationMode = "";
if (HabiticaApplication.User != null && HabiticaApplication.User.getPreferences() != null){
if (HabiticaApplication.User != null && HabiticaApplication.User.getPreferences() != null) {
allocationMode = HabiticaApplication.User.getPreferences().getAllocationMode();
}
@ -327,7 +321,7 @@ public class TasksFragment extends BaseMainFragment implements OnCheckedChangeLi
}
String allocationMode = "";
if (HabiticaApplication.User != null && HabiticaApplication.User.getPreferences() != null){
if (HabiticaApplication.User != null && HabiticaApplication.User.getPreferences() != null) {
allocationMode = HabiticaApplication.User.getPreferences().getAllocationMode();
}
@ -349,21 +343,24 @@ public class TasksFragment extends BaseMainFragment implements OnCheckedChangeLi
public void onEvent(TaskCheckedCommand event) {
apiHelper.apiService.postTaskDirection(event.Task.getId(), (event.Task.getCompleted() ? TaskDirection.down : TaskDirection.up).toString())
.compose(apiHelper.configureApiCallObserver())
.subscribe(new TaskScoringCallback(activity, event.Task.getId()), throwable -> {});
.subscribe(new TaskScoringCallback(activity, event.Task.getId()), throwable -> {
});
}
@Subscribe
public void onEvent(ChecklistCheckedCommand event) {
apiHelper.apiService.scoreChecklistItem(event.task.getId(), event.item.getId())
.compose(apiHelper.configureApiCallObserver())
.subscribe(new TaskUpdateCallback(), throwable -> {});
.subscribe(new TaskUpdateCallback(), throwable -> {
});
}
@Subscribe
public void onEvent(HabitScoreEvent event) {
apiHelper.apiService.postTaskDirection(event.habit.getId(), (event.Up ? TaskDirection.up : TaskDirection.down).toString())
.compose(apiHelper.configureApiCallObserver())
.subscribe(new TaskScoringCallback(activity, event.habit.getId()), throwable -> {});
.subscribe(new TaskScoringCallback(activity, event.habit.getId()), throwable -> {
});
}
@Subscribe
@ -377,12 +374,14 @@ public class TasksFragment extends BaseMainFragment implements OnCheckedChangeLi
if (event.created) {
this.apiHelper.apiService.createItem(task)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new TaskCreationCallback(), throwable -> {});
.subscribe(new TaskCreationCallback(), throwable -> {
});
floatingMenu.close(true);
} else {
this.apiHelper.apiService.updateTask(task.getId(), task)
.compose(apiHelper.configureApiCallObserver())
.subscribe(new TaskUpdateCallback(), throwable -> {});
.subscribe(new TaskUpdateCallback(), throwable -> {
});
}
}

View file

@ -11,13 +11,13 @@ public abstract class Debounce {
private long debounceDelay = 0;
private long checkDelay = 0;
public abstract void execute();
public Debounce(long debounceDelay, long checkDelay) {
this.debounceDelay = debounceDelay;
this.checkDelay = checkDelay;
}
public abstract void execute();
public void hit() {
lastHit = System.currentTimeMillis();
if (this.timer != null) {

View file

@ -21,9 +21,10 @@ public class EmojiKeyboard {
* Create a Emoji keyboard
*
* @param itemView Must contain views with the following IDs:
* 'emoji.toggle.btn' for the ImageButton that is used to enable/disable the emoji keyboard
* 'emoji.toggle.btn' for the ImageButton that is used to enable/disable the
* emoji keyboard
* 'edit.new.message.text' for the EmojiEditText where the emojis are put into
* @param context The context from the calling Activity
* @param context The context from the calling Activity
*/
public static void createKeyboard(View itemView, final Context context) {
@ -44,7 +45,7 @@ public class EmojiKeyboard {
@Override
public void onKeyboardClose() {
if(popup.isShowing())
if (popup.isShowing())
popup.dismiss();
}
});
@ -73,14 +74,12 @@ public class EmojiKeyboard {
emojiButton.setOnClickListener(v -> {
if(!popup.isShowing()){
if (!popup.isShowing()) {
if(popup.isKeyBoardOpen()){
if (popup.isKeyBoardOpen()) {
popup.showAtBottom();
changeEmojiKeyboardIcon(emojiButton, context, true);
}
else{
} else {
emojiEditText.setFocusableInTouchMode(true);
emojiEditText.requestFocus();
popup.showAtBottomPending();
@ -88,14 +87,13 @@ public class EmojiKeyboard {
inputMethodManager.showSoftInput(emojiEditText, InputMethodManager.SHOW_IMPLICIT);
changeEmojiKeyboardIcon(emojiButton, context, true);
}
}
else{
} else {
popup.dismiss();
changeEmojiKeyboardIcon(emojiButton, context, false);
}
});
}
private static void changeEmojiKeyboardIcon(ImageButton view, Context context, Boolean keyboardOpened) {
if (keyboardOpened) {

View file

@ -82,15 +82,15 @@ public class FloatingActionMenuBehavior extends CoordinatorLayout.Behavior {
return minOffset;
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, final View child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, final View child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
/*
Logic:
@ -108,36 +108,36 @@ public class FloatingActionMenuBehavior extends CoordinatorLayout.Behavior {
- If we're not on screen
AND we're scrolling upwards and not animating OR we're at the top of the screen > SHOW
*/
} else if (isOffScreen && ((dyConsumed < -10 && !isAnimating) || dyUnconsumed < 0)) {
} else if (isOffScreen && ((dyConsumed < -10 && !isAnimating) || dyUnconsumed < 0)) {
isAnimating = true;
slideFabOnScreen(child);
resetAnimatingStatusWithDelay(child);
isOffScreen = false;
}
}
}
}
private void resetAnimatingStatusWithDelay(final View child) {
child.postDelayed(() -> {
isAnimating = false;
FloatingActionMenu fab = (FloatingActionMenu)((ViewGroup) child).getChildAt(0);
if (isOffScreen && fab != null) {
fab.hideMenu(false);
}
}, FAB_ANIMATION_DURATION);
FloatingActionMenu fab = (FloatingActionMenu) ((ViewGroup) child).getChildAt(0);
if (isOffScreen && fab != null) {
fab.hideMenu(false);
}
}, FAB_ANIMATION_DURATION);
}
private void slideFabOffScreen(View view){
private void slideFabOffScreen(View view) {
Animation slideOff = AnimationUtils.loadAnimation(context, R.anim.fab_slide_out);
slideOff.setDuration(FAB_ANIMATION_DURATION);
slideOff.setFillAfter(true);
view.startAnimation(slideOff);
}
private void slideFabOnScreen(View view){
private void slideFabOnScreen(View view) {
Animation slideIn = AnimationUtils.loadAnimation(context, R.anim.fab_slide_in);
slideIn.setDuration(FAB_ANIMATION_DURATION);
slideIn.setFillAfter(true);
FloatingActionMenu fab = (FloatingActionMenu)((ViewGroup) view).getChildAt(0);
FloatingActionMenu fab = (FloatingActionMenu) ((ViewGroup) view).getChildAt(0);
view.startAnimation(slideIn);
if (fab != null) {
fab.showMenu(false);

View file

@ -23,21 +23,18 @@ import java.util.List;
* Created by keithholliday on 5/29/16.
*/
public class TaskAlarmManager {
private static TaskAlarmManager instance = null;
private Context context;
public static final String TASK_ID_INTENT_KEY = "TASK_ID";
public static final String TASK_NAME_INTENT_KEY = "TASK_NAME";
private static TaskAlarmManager instance = null;
private Context context;
private TaskAlarmManager(Context context) {
this.context = context;
EventBus.getDefault().register(this);
}
public static TaskAlarmManager getInstance(Context context){
if(instance == null)
{
public static TaskAlarmManager getInstance(Context context) {
if (instance == null) {
instance = new TaskAlarmManager(context);
}
return instance;
@ -94,7 +91,7 @@ public class TaskAlarmManager {
}
}
private RemindersItem setTimeForDailyReminder (RemindersItem remindersItem, Task task) {
private RemindersItem setTimeForDailyReminder(RemindersItem remindersItem, Task task) {
Date oldTime = remindersItem.getTime();
Date newTime = task.getNextActiveDateAfter(oldTime);
newTime.setHours(oldTime.getHours());

View file

@ -15,10 +15,6 @@ import android.widget.TextView;
*/
public class UiUtils {
public enum SnackbarDisplayType {
NORMAL, FAILURE, FAILURE_BLUE, DROP
}
/**
* Hides soft keyboard if it's opened.
*
@ -34,9 +30,10 @@ public class UiUtils {
/**
* Shows snackbar in given container.
* @param context Context.
*
* @param context Context.
* @param container Parent view where Snackbar will appear.
* @param content Message.
* @param content Message.
*/
public static void showSnackbar(Context context, View container, String content, SnackbarDisplayType displayType) {
Snackbar snackbar = Snackbar.make(container, content, Snackbar.LENGTH_LONG);
@ -59,4 +56,8 @@ public class UiUtils {
snackbar.show();
}
public enum SnackbarDisplayType {
NORMAL, FAILURE, FAILURE_BLUE, DROP
}
}

View file

@ -19,7 +19,7 @@ public class BottomSheetMenu extends BottomSheetDialog implements View.OnClickLi
super(context);
this.context = context;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.contentView = (LinearLayout)inflater.inflate(R.layout.menu_bottom_sheet, null);
this.contentView = (LinearLayout) inflater.inflate(R.layout.menu_bottom_sheet, null);
this.setContentView(this.contentView);
}

View file

@ -26,8 +26,8 @@ public class BottomSheetMenuItem {
}
public View inflate(Context context, LayoutInflater inflater, ViewGroup contentView) {
LinearLayout menuItemView = (LinearLayout)inflater.inflate(R.layout.menu_bottom_sheet_item, contentView, false);
TextView textView = (TextView)menuItemView.findViewById(R.id.textView);
LinearLayout menuItemView = (LinearLayout) inflater.inflate(R.layout.menu_bottom_sheet_item, contentView, false);
TextView textView = (TextView) menuItemView.findViewById(R.id.textView);
textView.setText(this.title);
if (this.isDestructive) {
textView.setTextColor(ContextCompat.getColor(context, R.color.worse_50));

View file

@ -26,14 +26,11 @@ import android.view.View;
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;

View file

@ -46,7 +46,6 @@ public class MainDrawerBuilder {
public static final int SIDEBAR_ABOUT = 14;
public static AccountHeaderBuilder CreateDefaultAccountHeader(final Activity activity) {
return new AccountHeaderBuilder()
.withActivity(activity)
@ -140,7 +139,7 @@ public class MainDrawerBuilder {
break;
}
case SIDEBAR_NEWS: {
fragment= new NewsFragment();
fragment = new NewsFragment();
break;
}
case SIDEBAR_SETTINGS: {

View file

@ -22,10 +22,8 @@ import rx.schedulers.Schedulers;
public class BaseTaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected Context context;
public Task task;
protected Context context;
@BindView(R.id.checkedTextView)
TextView titleTextView;

View file

@ -29,29 +29,24 @@ import butterknife.OnClick;
public abstract class ChecklistedViewHolder extends BaseTaskViewHolder implements CompoundButton.OnCheckedChangeListener {
public Boolean displayChecklist;
@BindView(R.id.checkBoxHolder)
ViewGroup checkboxHolder;
@BindView(R.id.checkBox)
CheckBox checkbox;
@BindView(R.id.checklistView)
LinearLayout checklistView;
@BindView(R.id.checklistSeparator)
View checklistSeparator;
@BindView(R.id.checklistBottomSpace)
View checklistBottomSpace;
@BindView(R.id.checklistIndicatorWrapper)
ViewGroup checklistIndicatorWrapper;
@BindView(R.id.checkListCompletedTextView)
TextView checklistCompletedTextView;
@BindView(R.id.checkListAllTextView)
TextView checklistAllTextView;
public Boolean displayChecklist;
public ChecklistedViewHolder(View itemView) {
super(itemView);
checklistIndicatorWrapper.setClickable(true);
@ -126,13 +121,13 @@ public abstract class ChecklistedViewHolder extends BaseTaskViewHolder implement
this.setDisplayChecklist(true);
}
if (this.displayChecklist) {
RecyclerView recyclerView = (RecyclerView)this.checklistView.getParent().getParent();
LinearLayoutManager layoutManager = (LinearLayoutManager)recyclerView.getLayoutManager();
RecyclerView recyclerView = (RecyclerView) this.checklistView.getParent().getParent();
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
layoutManager.scrollToPositionWithOffset(this.getAdapterPosition(), 15);
}
}
public void expandCheckboxTouchArea(final View expandedView, final View checkboxView){
public void expandCheckboxTouchArea(final View expandedView, final View checkboxView) {
expandedView.post(() -> {
Rect rect = new Rect();
expandedView.getHitRect(rect);
@ -146,12 +141,12 @@ public abstract class ChecklistedViewHolder extends BaseTaskViewHolder implement
if (isChecked != task.getCompleted()) {
TaskCheckedCommand event = new TaskCheckedCommand();
event.Task = task;
event.completed = !task.getCompleted();
event.completed = !task.getCompleted();
// it needs to be changed after the event is send -> to the server
// maybe a refactor is needed here
EventBus.getDefault().post(event);
task.completed =event.completed;
task.completed = event.completed;
task.save();
}
} else {

View file

@ -10,11 +10,10 @@ import butterknife.BindView;
public class DailyViewHolder extends ChecklistedViewHolder {
public final int dailyResetOffset;
@BindView(R.id.streakTextView)
TextView streakTextView;
public final int dailyResetOffset;
public DailyViewHolder(View itemView, int dailyResetOffset) {
super(itemView);
this.dailyResetOffset = dailyResetOffset;

View file

@ -70,7 +70,7 @@ public class RewardViewHolder extends BaseTaskViewHolder {
@Override
public void onClick(View v) {
if(task.specialTag != null && task.specialTag.equals("item")) {
if (task.specialTag != null && task.specialTag.equals("item")) {
LinearLayout contentViewForDialog = createContentViewForGearDialog();
AlertDialog dialog = createGearDialog(contentViewForDialog);
dialog.show();
@ -85,7 +85,7 @@ public class RewardViewHolder extends BaseTaskViewHolder {
private AlertDialog createGearDialog(LinearLayout contentViewForDialog) {
return new AlertDialog.Builder(context)
.setPositiveButton(R.string.reward_dialog_buy, (dialog, which) -> {
this.buyReward();
this.buyReward();
})
.setTitle(this.task.getText())
.setView(contentViewForDialog)
@ -109,7 +109,7 @@ public class RewardViewHolder extends BaseTaskViewHolder {
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
gearImageLayoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
gearImageLayoutParams.setMargins(0,0,0,20);
gearImageLayoutParams.setMargins(0, 0, 0, 20);
gearImageView.setMinimumWidth(200);
gearImageView.setMinimumHeight(200);
gearImageView.setLayoutParams(gearImageLayoutParams);
@ -117,7 +117,7 @@ public class RewardViewHolder extends BaseTaskViewHolder {
// Gear Description
TextView contentTextView = new TextView(context, null);
if(!content.isEmpty()){
if (!content.isEmpty()) {
contentTextView.setText(content);
}
@ -147,14 +147,14 @@ public class RewardViewHolder extends BaseTaskViewHolder {
goldPriceLayout.addView(gold);
goldPriceLayout.addView(priceTextView);
if(gearImageView.getDrawable()!= null){
if (gearImageView.getDrawable() != null) {
contentViewLayout.addView(gearImageView);
}
contentViewLayout.setGravity(Gravity.CENTER_VERTICAL);
contentViewLayout.addView(goldPriceLayout);
if(!content.isEmpty()){
if (!content.isEmpty()) {
contentViewLayout.addView(contentTextView);
}

View file

@ -74,9 +74,9 @@ public class BitmapUtils {
private static boolean createNomedia() {
//Returns true if .nomedia was created/already existed and false if not
try {
File cacheDir = new File (getSavePath());
File cacheDir = new File(getSavePath());
cacheDir.mkdirs();
File nomediaFile = new File (getSavePath() + "/.nomedia");
File nomediaFile = new File(getSavePath() + "/.nomedia");
if (!nomediaFile.isFile()) return nomediaFile.createNewFile();
} catch (IOException e) {
}

View file

@ -23,25 +23,22 @@ import java.util.concurrent.atomic.AtomicInteger;
public class UserPicture {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
private static final int WIDTH = 140;
private static final int HEIGHT = 147;
private static final int COMPACT_WIDTH = 114;
private static final int COMPACT_HEIGHT = 114;
final List<Bitmap> layers = new ArrayList<>();
final List<SpriteTarget> targets = new ArrayList<>();
private HabitRPGUser user;
private ImageView imageView;
private UserPictureRunnable runnable;
private Context context;
private AtomicInteger numOfTasks = new AtomicInteger(0);
private boolean hasBackground, hasPetMount;
private boolean userHasBackground, userHasPet, userHasMount;
private String currentCacheFileName;
final List<Bitmap> layers = new ArrayList<>();
final List<SpriteTarget> targets = new ArrayList<>();
public UserPicture(Context context) {
this.context = context;
this.hasBackground = true;
@ -54,6 +51,30 @@ public class UserPicture {
this.hasPetMount = hasPetMount;
}
private static String generateHashCode(String value) {
byte[] digest = new byte[0];
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(value.getBytes());
digest = md.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return bytesToHex(digest);
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public void setUser(HabitRPGUser user) {
this.user = user;
}
@ -120,7 +141,7 @@ public class UserPicture {
Bitmap cache = this.getCachedImage(layerNames);
// yes => load image to bitmap
if(cache != null){
if (cache != null) {
runnable.run(cache);
return;
}
@ -212,32 +233,6 @@ public class UserPicture {
}
}
private static String generateHashCode(String value) {
byte[] digest = new byte[0];
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(value.getBytes());
digest = md.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return bytesToHex(digest);
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private void modifyCanvas(Bitmap img, Canvas canvas, Integer layerNumber) {
Paint paint = new Paint();
paint.setFilterBitmap(false);
@ -254,14 +249,14 @@ public class UserPicture {
if (this.userHasMount) {
if (((this.userHasBackground && layerNumber > 1) ||
(!this.userHasBackground && layerNumber > 0)) &&
((this.userHasPet && layerNumber < (this.layers.size()-2)) ||
(!this.userHasPet && layerNumber < this.layers.size()-1))) {
((this.userHasPet && layerNumber < (this.layers.size() - 2)) ||
(!this.userHasPet && layerNumber < this.layers.size() - 1))) {
yOffset = 0;
}
}
}
if (this.hasPetMount && this.userHasPet && layerNumber == this.layers.size()-1) {
if (this.hasPetMount && this.userHasPet && layerNumber == this.layers.size() - 1) {
xOffset = 0;
yOffset = 43;
}
@ -270,6 +265,15 @@ public class UserPicture {
new Rect(xOffset, yOffset, img.getWidth() + xOffset, img.getHeight() + yOffset), paint);
}
private String getFileName(String imageName) {
if (imageName.equals("head_special_1")) {
return "ContributorOnly-Equip-CrystalHelmet.gif";
} else if (imageName.equals("armor_special_1")) {
return "ContributorOnly-Equip-CrystalArmor.gif";
}
return imageName + ".png";
}
private class SpriteTarget implements Target {
private Integer layerNumber;
@ -300,15 +304,6 @@ public class UserPicture {
}
}
private String getFileName(String imageName) {
if (imageName.equals("head_special_1")) {
return "ContributorOnly-Equip-CrystalHelmet.gif";
} else if (imageName.equals("armor_special_1")) {
return "ContributorOnly-Equip-CrystalArmor.gif";
}
return imageName+".png";
}
}

View file

@ -21,6 +21,21 @@ import android.widget.RemoteViews;
public class SimpleWidget extends AppWidgetProvider {
private static final String LOG = "simplewidgetprovider";
/**
* Returns number of cells needed for given size of the widget.<br/>
* see http://stackoverflow.com/questions/14270138/dynamically-adjusting-widgets-content-and-layout-to-the-size-the-user-defined-t
*
* @param size Widget size in dp.
* @return Size in number of cells.
*/
private static int getCellsForSize(int size) {
int n = 2;
while (70 * n - 30 < size) {
++n;
}
return n - 1;
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.w(LOG, "onUpdate method called");
@ -55,14 +70,9 @@ public class SimpleWidget extends AppWidgetProvider {
}
/**
* Determine appropriate view based on width provided.<br/>
* see http://stackoverflow.com/questions/14270138/dynamically-adjusting-widgets-content-and-layout-to-the-size-the-user-defined-t
*
* @param minWidth
* @param minHeight
* @return
*/
private RemoteViews getRemoteViews(Context context, int minWidth,
int minHeight) {
@ -82,20 +92,5 @@ public class SimpleWidget extends AppWidgetProvider {
}
/**
* Returns number of cells needed for given size of the widget.<br/>
* see http://stackoverflow.com/questions/14270138/dynamically-adjusting-widgets-content-and-layout-to-the-size-the-user-defined-t
*
* @param size Widget size in dp.
* @return Size in number of cells.
*/
private static int getCellsForSize(int size) {
int n = 2;
while (70 * n - 30 < size) {
++n;
}
return n - 1;
}
}

View file

@ -25,14 +25,13 @@ import javax.inject.Inject;
*/
public class UpdateWidgetService extends Service implements HabitRPGUserCallback.OnUserReceived {
private static final String LOG = ".simplewidget.service";
private AppWidgetManager appWidgetManager;
@Inject
public APIHelper apiHelper;
private AppWidgetManager appWidgetManager;
public UpdateWidgetService() {
super();
((HabiticaApplication)getApplication()).getComponent().inject(this);
((HabiticaApplication) getApplication()).getComponent().inject(this);
}
@Override

View file

@ -6,23 +6,19 @@ package com.magicmicky.habitrpgwrapper.lib.api;
public class Server {
private String addr;
public Server(String addr)
{
public Server(String addr) {
this(addr, true);
}
public Server(String addr, boolean attachSuffix)
{
if(attachSuffix){
if(addr.endsWith("/api/v3") || addr.endsWith("/api/v3/"))
this.addr=addr;
else if(addr.endsWith("/"))
this.addr=addr + "api/v3/";
public Server(String addr, boolean attachSuffix) {
if (attachSuffix) {
if (addr.endsWith("/api/v3") || addr.endsWith("/api/v3/"))
this.addr = addr;
else if (addr.endsWith("/"))
this.addr = addr + "api/v3/";
else
this.addr = addr + "/api/v3/";
}
else
{
} else {
this.addr = addr;
}
}

View file

@ -17,21 +17,24 @@ import com.raizlabs.android.dbflow.structure.BaseModel;
@Table(databaseName = HabitDatabase.NAME)
public class Authentication extends BaseModel {
@Column
@PrimaryKey
@NotNull
String user_id;
@SerializedName("local")
@Column
@ForeignKey(references = {@ForeignKeyReference(columnName = "localauthentication_user_id",
columnType = String.class,
foreignColumnName = "user_id")})
public LocalAuthentication localAuthentication;
@Column
@PrimaryKey
@NotNull
String user_id;
public LocalAuthentication getLocalAuthentication() { return localAuthentication; }
public LocalAuthentication getLocalAuthentication() {
return localAuthentication;
}
public void setLocalAuthentication(LocalAuthentication LocalAuthentication) {this.localAuthentication = LocalAuthentication; }
public void setLocalAuthentication(LocalAuthentication LocalAuthentication) {
this.localAuthentication = LocalAuthentication;
}
@Override
public void save() {

View file

@ -16,17 +16,15 @@ import com.raizlabs.android.dbflow.structure.BaseModel;
@Table(databaseName = HabitDatabase.NAME)
public class BasicStats extends BaseModel {
@Column
@PrimaryKey
@NotNull
String id;
@Column
public Float con, str, per;
@Column
@SerializedName("int")
public Float _int;
@Column
@PrimaryKey
@NotNull
String id;
public Float getCon() {
return con != null ? con : Float.valueOf(0);

View file

@ -17,15 +17,16 @@ public class Buffs extends BasicStats {
private Boolean streaks;
public Buffs() {
this(false,false);
this(false, false);
}
public Buffs(Boolean snowball, Boolean streaks) {
this.snowball = snowball;
this.streaks = streaks;
}
public Boolean getSnowball() {
return snowball != null ? snowball: Boolean.FALSE;
return snowball != null ? snowball : Boolean.FALSE;
}
public void setSnowball(Boolean snowball) {

View file

@ -55,9 +55,9 @@ public class ChatMessage {
if (contributor != null) {
if (CONTRIBUTOR_COLOR_DICT.containsKey(contributor.level)) {
rColor = CONTRIBUTOR_COLOR_DICT.get(contributor.level);
}
if (CONTRIBUTOR_COLOR_DICT.containsKey(contributor.level)) {
rColor = CONTRIBUTOR_COLOR_DICT.get(contributor.level);
}
}
if (backer != null) {

View file

@ -4,7 +4,7 @@ import com.magicmicky.habitrpgwrapper.lib.models.tasks.ItemData;
import java.util.List;
public class ContentGear{
public class ContentGear {
public List<ItemData> flat;

Some files were not shown because too many files have changed in this diff Show more