Update opoc

This commit is contained in:
Gregor Santner 2017-08-09 17:23:19 +02:00
parent bdd502174d
commit 92bd98ea28
No known key found for this signature in database
GPG Key ID: 7E83A7834AECB009
10 changed files with 396 additions and 261 deletions

View File

@ -1,3 +1,6 @@
### v1.0.3
- Update opoc
### v1.0.2 (2017-08-05)
- Improve build script
- Update translation file license

View File

@ -89,8 +89,8 @@ import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.gsantner.opoc.util.HelpersA;
import io.github.gsantner.opoc.util.SimpleMarkdownParser;
import com.github.dfa.diaspora_android.util.HelpersA;
public class MainActivity extends ThemedActivity
implements NavigationView.OnNavigationItemSelectedListener,

View File

@ -56,6 +56,7 @@ import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import com.github.dfa.diaspora_android.util.Helpers;
import com.github.dfa.diaspora_android.util.HelpersA;
import org.json.JSONException;
import org.json.JSONObject;
@ -128,7 +129,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
}
});
LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(FetchPodsService.MESSAGE_PODS_RECEIVED));
Helpers.get().showInfoIfUserNotConnectedToInternet(getActivity(), listViewPod);
HelpersA.get(getActivity()).showInfoIfUserNotConnectedToInternet(listViewPod);
}
public void mergePodlistWithRessources(DiasporaPodList podlist) {
@ -244,7 +245,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_reload: {
if (!Helpers.get().showInfoIfUserNotConnectedToInternet(getActivity(), listViewPod)) {
if (!HelpersA.get(getActivity()).showInfoIfUserNotConnectedToInternet(listViewPod)) {
Intent i = new Intent(getContext(), FetchPodsService.class);
getContext().startService(i);
return true;

View File

@ -48,7 +48,7 @@ public class AppSettings extends AppSettingsBase {
private AppSettings(Context context) {
super(context);
prefPod = this.context.getSharedPreferences("pod0", Context.MODE_PRIVATE);
prefPod = _context.getSharedPreferences("pod0", Context.MODE_PRIVATE);
}
/**
@ -63,14 +63,14 @@ public class AppSettings extends AppSettingsBase {
}
/**
* Clear all settings in prefApp (related to the App itself)
* Clear all settings in _prefApp (related to the App itself)
* This uses commit instead of apply, since
* SettingsActivity.SettingsFragmentDebugging.showWipeSettingsDialog()
* kills the app after the calling this, so we have to block until we are finished.
*/
@SuppressLint("CommitPrefEdits")
public void resetAppSettings() {
super.resetSettings(prefApp);
super.resetSettings(_prefApp);
}
//#################################
@ -85,11 +85,11 @@ public class AppSettings extends AppSettingsBase {
}
public boolean isLoadImages() {
return getBool(prefApp, R.string.pref_key__load_images, true);
return getBool(_prefApp, R.string.pref_key__load_images, true);
}
public int getMinimumFontSize() {
switch (getString(prefApp, R.string.pref_key__font_size, "")) {
switch (getString(_prefApp, R.string.pref_key__font_size, "")) {
case "huge":
return 20;
case "large":
@ -97,7 +97,7 @@ public class AppSettings extends AppSettingsBase {
case "normal":
return 8;
default:
setString(prefApp, R.string.pref_key__font_size, "normal");
setString(_prefApp, R.string.pref_key__font_size, "normal");
return 8;
}
}
@ -198,13 +198,13 @@ public class AppSettings extends AppSettingsBase {
}
public boolean isAppendSharedViaApp() {
return getBool(prefApp, R.string.pref_key__append_shared_via_app, true);
return getBool(_prefApp, R.string.pref_key__append_shared_via_app, true);
}
@SuppressLint("CommitPrefEdits")
public void setProxyHttpEnabled(boolean enabled) {
//commit instead of apply because the app is likely to be killed before apply is called.
prefApp.edit().putBoolean(context.getString(R.string.pref_key__http_proxy_enabled), enabled).commit();
_prefApp.edit().putBoolean(rstr(R.string.pref_key__http_proxy_enabled), enabled).commit();
}
/**
@ -214,7 +214,7 @@ public class AppSettings extends AppSettingsBase {
*/
public boolean isProxyHttpEnabled() {
try {
return getBool(prefApp, R.string.pref_key__http_proxy_enabled, false);
return getBool(_prefApp, R.string.pref_key__http_proxy_enabled, false);
} catch (ClassCastException e) {
setProxyHttpEnabled(false);
return false;
@ -222,7 +222,7 @@ public class AppSettings extends AppSettingsBase {
}
public boolean wasProxyEnabled() {
return getBool(prefApp, R.string.pref_key__proxy_was_enabled, false);
return getBool(_prefApp, R.string.pref_key__proxy_was_enabled, false);
}
/**
@ -233,7 +233,7 @@ public class AppSettings extends AppSettingsBase {
*/
@SuppressLint("CommitPrefEdits")
public void setProxyWasEnabled(boolean b) {
prefApp.edit().putBoolean(context.getString(R.string.pref_key__proxy_was_enabled), b).commit();
_prefApp.edit().putBoolean(rstr(R.string.pref_key__proxy_was_enabled), b).commit();
}
/**
@ -242,11 +242,11 @@ public class AppSettings extends AppSettingsBase {
* @return proxy host
*/
public String getProxyHttpHost() {
return getString(prefApp, R.string.pref_key__http_proxy_host, "");
return getString(_prefApp, R.string.pref_key__http_proxy_host, "");
}
public void setProxyHttpHost(String value) {
setString(prefApp, R.string.pref_key__http_proxy_host, value);
setString(_prefApp, R.string.pref_key__http_proxy_host, value);
}
/**
@ -256,17 +256,17 @@ public class AppSettings extends AppSettingsBase {
*/
public int getProxyHttpPort() {
try {
String str = getString(prefApp, R.string.pref_key__http_proxy_port, "0");
String str = getString(_prefApp, R.string.pref_key__http_proxy_port, "0");
return Integer.parseInt(str);
} catch (ClassCastException e) {
int port = getInt(prefApp, R.string.pref_key__http_proxy_port, 0);
int port = getInt(_prefApp, R.string.pref_key__http_proxy_port, 0);
setProxyHttpPort(port);
return port;
}
}
public void setProxyHttpPort(int value) {
setString(prefApp, R.string.pref_key__http_proxy_port, Integer.toString(value));
setString(_prefApp, R.string.pref_key__http_proxy_port, Integer.toString(value));
}
public ProxyHandler.ProxySettings getProxySettings() {
@ -274,94 +274,94 @@ public class AppSettings extends AppSettingsBase {
}
public boolean isIntellihideToolbars() {
return getBool(prefApp, R.string.pref_key__intellihide_toolbars, true);
return getBool(_prefApp, R.string.pref_key__intellihide_toolbars, true);
}
public boolean isChromeCustomTabsEnabled() {
return getBool(prefApp, R.string.pref_key__chrome_custom_tabs_enabled, true);
return getBool(_prefApp, R.string.pref_key__chrome_custom_tabs_enabled, true);
}
public boolean isLoggingEnabled() {
return getBool(prefApp, R.string.pref_key__logging_enabled, false);
return getBool(_prefApp, R.string.pref_key__logging_enabled, false);
}
public boolean isLoggingSpamEnabled() {
return getBool(prefApp, R.string.pref_key__logging_spam_enabled, false);
return getBool(_prefApp, R.string.pref_key__logging_spam_enabled, false);
}
public boolean isVisibleInNavExit() {
return getBool(prefApp, R.string.pref_key__visibility_nav__exit, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__exit, true);
}
public boolean isVisibleInNavHelp_license() {
return getBool(prefApp, R.string.pref_key__visibility_nav__help_license, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__help_license, true);
}
public boolean isVisibleInNavPublic_activities() {
return getBool(prefApp, R.string.pref_key__visibility_nav__public_activities, false);
return getBool(_prefApp, R.string.pref_key__visibility_nav__public_activities, false);
}
public boolean isVisibleInNavMentions() {
return getBool(prefApp, R.string.pref_key__visibility_nav__mentions, false);
return getBool(_prefApp, R.string.pref_key__visibility_nav__mentions, false);
}
public boolean isVisibleInNavCommented() {
return getBool(prefApp, R.string.pref_key__visibility_nav__commented, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__commented, true);
}
public boolean isVisibleInNavLiked() {
return getBool(prefApp, R.string.pref_key__visibility_nav__liked, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__liked, true);
}
public boolean isVisibleInNavActivities() {
return getBool(prefApp, R.string.pref_key__visibility_nav__activities, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__activities, true);
}
public boolean isVisibleInNavAspects() {
return getBool(prefApp, R.string.pref_key__visibility_nav__aspects, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__aspects, true);
}
public boolean isVisibleInNavFollowed_tags() {
return getBool(prefApp, R.string.pref_key__visibility_nav__followed_tags, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__followed_tags, true);
}
public boolean isVisibleInNavProfile() {
return getBool(prefApp, R.string.pref_key__visibility_nav__profile, true);
return getBool(_prefApp, R.string.pref_key__visibility_nav__profile, true);
}
public boolean isVisibleInNavContacts() {
return getBool(prefApp, R.string.pref_key__visibility_nav__contacts, false);
return getBool(_prefApp, R.string.pref_key__visibility_nav__contacts, false);
}
public boolean isVisibleInNavStatistics() {
return getBool(prefApp, R.string.pref_key__visibility_nav__statistics, false);
return getBool(_prefApp, R.string.pref_key__visibility_nav__statistics, false);
}
public boolean isVisibleInNavReports() {
return getBool(prefApp, R.string.pref_key__visibility_nav__reports, false);
return getBool(_prefApp, R.string.pref_key__visibility_nav__reports, false);
}
public boolean isVisibleToggleMobileDesktop() {
return getBool(prefApp, R.string.pref_key__visibility_nav__toggle_mobile_desktop, false);
return getBool(_prefApp, R.string.pref_key__visibility_nav__toggle_mobile_desktop, false);
}
public boolean isTopbarStreamShortcutEnabled() {
return getBool(prefApp, R.string.pref_key__topbar_stream_shortcut, false);
return getBool(_prefApp, R.string.pref_key__topbar_stream_shortcut, false);
}
public String getScreenRotation() {
return getString(prefApp, R.string.pref_key__screen_rotation, R.string.rotation_val_system);
return getString(_prefApp, R.string.pref_key__screen_rotation, R.string.rotation_val_system);
}
public boolean isAppFirstStart() {
boolean value = getBool(prefApp, R.string.pref_key__app_first_start, true);
setBool(prefApp, R.string.pref_key__app_first_start, false);
boolean value = getBool(_prefApp, R.string.pref_key__app_first_start, true);
setBool(_prefApp, R.string.pref_key__app_first_start, false);
return value;
}
public boolean isAppCurrentVersionFirstStart() {
int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1);
setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
int value = getInt(_prefApp, R.string.pref_key__app_first_start_current_version, -1);
setInt(_prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD;
}
@ -374,22 +374,22 @@ public class AppSettings extends AppSettingsBase {
}
public void setLanguage(String value) {
setString(prefApp, R.string.pref_key__language, value);
setString(_prefApp, R.string.pref_key__language, value);
}
public String getLanguage() {
return getString(prefApp, R.string.pref_key__language, "");
return getString(_prefApp, R.string.pref_key__language, "");
}
public void setPrimaryColorSettings(int base, int shade) {
setInt(prefApp, R.string.pref_key__primary_color_base, base);
setInt(prefApp, R.string.pref_key__primary_color_shade, shade);
setInt(_prefApp, R.string.pref_key__primary_color_base, base);
setInt(_prefApp, R.string.pref_key__primary_color_shade, shade);
}
public int[] getPrimaryColorSettings() {
return new int[]{
getInt(prefApp, R.string.pref_key__primary_color_base, rcolor(R.color.md_blue_650)),
getInt(prefApp, R.string.pref_key__primary_color_shade, rcolor(R.color.primary))
getInt(_prefApp, R.string.pref_key__primary_color_base, rcolor(R.color.md_blue_650)),
getInt(_prefApp, R.string.pref_key__primary_color_shade, rcolor(R.color.primary))
};
}
@ -398,36 +398,36 @@ public class AppSettings extends AppSettingsBase {
if (isAmoledColorMode()) {
return Color.BLACK;
} else {
return getInt(prefApp, R.string.pref_key__primary_color_shade, rcolor(
return getInt(_prefApp, R.string.pref_key__primary_color_shade, rcolor(
BuildConfig.IS_TEST_BUILD ? R.color.md_brown_800 : R.color.primary));
}
}
public void setAccentColorSettings(int base, int shade) {
setInt(prefApp, R.string.pref_key__accent_color_base, base);
setInt(prefApp, R.string.pref_key__accent_color_shade, shade);
setInt(_prefApp, R.string.pref_key__accent_color_base, base);
setInt(_prefApp, R.string.pref_key__accent_color_shade, shade);
}
public int[] getAccentColorSettings() {
return new int[]{
getInt(prefApp, R.string.pref_key__accent_color_base, rcolor(R.color.md_green_400)),
getInt(prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent))
getInt(_prefApp, R.string.pref_key__accent_color_base, rcolor(R.color.md_green_400)),
getInt(_prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent))
};
}
public int getAccentColor() {
return getInt(prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent));
return getInt(_prefApp, R.string.pref_key__accent_color_shade, rcolor(R.color.accent));
}
public boolean isExtendedNotificationsActivated() {
return getBool(prefApp, R.string.pref_key__extended_notifications, false);
return getBool(_prefApp, R.string.pref_key__extended_notifications, false);
}
public boolean isAmoledColorMode() {
return getBool(prefApp, R.string.pref_key__primary_color__amoled_mode, false);
return getBool(_prefApp, R.string.pref_key__primary_color__amoled_mode, false);
}
public boolean isAdBlockEnabled() {
return getBool(prefApp, R.string.pref_key__adblock_enable, true);
return getBool(_prefApp, R.string.pref_key__adblock_enable, true);
}
}

View File

@ -1,14 +1,10 @@
package com.github.dfa.diaspora_android.util;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.web.WebHelper;
import java.io.File;
import java.io.IOException;
@ -17,8 +13,6 @@ import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import io.github.gsantner.opoc.util.HelpersA;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
public class Helpers extends io.github.gsantner.opoc.util.Helpers {
protected Helpers(Context context) {
@ -44,20 +38,6 @@ public class Helpers extends io.github.gsantner.opoc.util.Helpers {
);
}
/**
* Show Information if user is offline, returns true if is not connected to internet
*
* @param activity Activity
* @param anchor A view anchor
*/
public boolean showInfoIfUserNotConnectedToInternet(Activity activity, View anchor) {
boolean isOnline = WebHelper.isOnline(context);
if (!isOnline) {
HelpersA.get(activity).showSnackBar(R.string.no_internet, true);
}
return !isOnline;
}
public void logBundle(Bundle savedInstanceState, String k) {
if (savedInstanceState != null) {
for (String key : savedInstanceState.keySet()) {

View File

@ -0,0 +1,73 @@
package com.github.dfa.diaspora_android.util;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.web.WebHelper;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
public class HelpersA extends io.github.gsantner.opoc.util.HelpersA {
protected HelpersA(Activity activity) {
super(activity);
}
public static HelpersA get(Activity activity) {
return new HelpersA(activity);
}
public File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
AppLog.d(HelpersA.class, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
return new File(
imageFileName + /* prefix */
".jpg", /* suffix */
storageDir.getAbsolutePath() /* directory */
);
}
/**
* Show Information if user is offline, returns true if is not connected to internet
*
* @param anchor A view anchor
*/
public boolean showInfoIfUserNotConnectedToInternet(View anchor) {
boolean isOnline = WebHelper.isOnline(_context);
if (!isOnline) {
showSnackBar(R.string.no_internet, true);
}
return !isOnline;
}
public void logBundle(Bundle savedInstanceState, String k) {
if (savedInstanceState != null) {
for (String key : savedInstanceState.keySet()) {
AppLog.d("Bundle", key + " is a key in the bundle " + k);
Object bun = savedInstanceState.get(key);
if (bun != null) {
if (bun instanceof Bundle) {
logBundle((Bundle) bun, k + "." + key);
} else if (bun instanceof byte[]) {
AppLog.d("Bundle", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun));
} else {
AppLog.d("Bundle", "Key: " + k + "." + key + ": " + bun.toString());
}
}
}
}
}
}

View File

@ -17,24 +17,26 @@
* with keys in resources. Extend from this class and add
* getters/setters for the app's settings.
* Example:
public boolean isAppFirstStart() {
return getBool(prefApp, R.string.pref_key__app_first_start, true);
public boolean isAppFirstStart(boolean doSet) {
boolean value = getBool(prefApp, R.string.pref_key__app_first_start, true);
if (doSet) {
setBool(prefApp, R.string.pref_key__app_first_start, false);
}
return value;
}
public void setAppFirstStart(boolean value) {
setBool(prefApp, R.string.pref_key__app_first_start, value);
}
public boolean isAppFirstStartCurrentVersion() {
int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1);
setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD;
public boolean isAppCurrentVersionFirstStart(boolean doSet) {
int value = getInt(prefApp, R.string.pref_key__app_first_start_current_version, -1);
if (doSet) {
setInt(prefApp, R.string.pref_key__app_first_start_current_version, BuildConfig.VERSION_CODE);
}
return value != BuildConfig.VERSION_CODE && !BuildConfig.IS_TEST_BUILD;
}
* Maybe add a singleton for this:
* Whereas App.get() is returning ApplicationContext
private AppSettings(Context context) {
super(context);
private AppSettings(Context _context) {
super(_context);
}
public static AppSettings get() {
@ -61,32 +63,32 @@ import java.util.List;
* Wrapper for settings based on SharedPreferences
* with keys in resources
*/
@SuppressWarnings({"WeakerAccess", "unused"})
@SuppressWarnings({"WeakerAccess", "unused", "SpellCheckingInspection", "SameParameterValue"})
public class AppSettingsBase {
protected static final String ARRAY_SEPARATOR = "%%%";
protected static final String ARRAY_SEPARATOR_SUBSTITUTE = "§§§";
public static final String SHARED_PREF_APP = "app";
//#####################
//## Members
//#####################
protected final SharedPreferences prefApp;
protected final Context context;
//########################
//## Members, Constructors
//########################
protected final SharedPreferences _prefApp;
protected final Context _context;
public AppSettingsBase(final Context context) {
this(context, SHARED_PREF_APP);
}
public AppSettingsBase(final Context context, final String prefAppName) {
_context = context.getApplicationContext();
_prefApp = _context.getSharedPreferences(prefAppName, Context.MODE_PRIVATE);
}
//#####################
//## Methods
//#####################
public AppSettingsBase(Context context) {
this(context, SHARED_PREF_APP);
}
public AppSettingsBase(Context context, String prefAppName) {
this.context = context.getApplicationContext();
prefApp = this.context.getSharedPreferences(prefAppName, Context.MODE_PRIVATE);
}
public Context getContext() {
return context;
return _context;
}
public boolean isKeyEqual(String key, int stringKeyResourceId) {
@ -94,35 +96,35 @@ public class AppSettingsBase {
}
public void resetSettings() {
resetSettings(prefApp);
resetSettings(_prefApp);
}
@SuppressLint("ApplySharedPref")
public void resetSettings(SharedPreferences pref) {
public void resetSettings(final SharedPreferences pref) {
pref.edit().clear().commit();
}
public boolean isPrefSet(@StringRes int stringKeyResourceId) {
return isPrefSet(prefApp, stringKeyResourceId);
return isPrefSet(_prefApp, stringKeyResourceId);
}
public boolean isPrefSet(SharedPreferences pref, @StringRes int stringKeyResourceId) {
public boolean isPrefSet(final SharedPreferences pref, @StringRes int stringKeyResourceId) {
return pref.contains(rstr(stringKeyResourceId));
}
public void registerPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) {
registerPreferenceChangedListener(prefApp, value);
registerPreferenceChangedListener(_prefApp, value);
}
public void registerPreferenceChangedListener(SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
public void registerPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
pref.registerOnSharedPreferenceChangeListener(value);
}
public void unregisterPreferenceChangedListener(SharedPreferences.OnSharedPreferenceChangeListener value) {
unregisterPreferenceChangedListener(prefApp, value);
unregisterPreferenceChangedListener(_prefApp, value);
}
public void unregisterPreferenceChangedListener(SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
public void unregisterPreferenceChangedListener(final SharedPreferences pref, SharedPreferences.OnSharedPreferenceChangeListener value) {
pref.unregisterOnSharedPreferenceChangeListener(value);
}
@ -130,45 +132,45 @@ public class AppSettingsBase {
//## Getter for resources
//#################################
public String rstr(@StringRes int stringKeyResourceId) {
return context.getString(stringKeyResourceId);
return _context.getString(stringKeyResourceId);
}
public int rcolor(@ColorRes int resColorId) {
return ContextCompat.getColor(context, resColorId);
return ContextCompat.getColor(_context, resColorId);
}
//#################################
//## Getter & Setter for settings
//#################################
public void setString(@StringRes int keyResourceId, String value) {
setString(prefApp, keyResourceId, value);
setString(_prefApp, keyResourceId, value);
}
public void setString(SharedPreferences pref, @StringRes int keyResourceId, String value) {
public void setString(final SharedPreferences pref, @StringRes int keyResourceId, String value) {
pref.edit().putString(rstr(keyResourceId), value).apply();
}
public String getString(@StringRes int keyResourceId, String defaultValue) {
return getString(prefApp, keyResourceId, defaultValue);
return getString(_prefApp, keyResourceId, defaultValue);
}
public String getString(SharedPreferences pref, @StringRes int keyResourceId, String defaultValue) {
public String getString(final SharedPreferences pref, @StringRes int keyResourceId, String defaultValue) {
return pref.getString(rstr(keyResourceId), defaultValue);
}
public String getString(@StringRes int keyResourceId, @StringRes int keyResourceIdDefaultValue) {
return getString(prefApp, keyResourceId, keyResourceIdDefaultValue);
return getString(_prefApp, keyResourceId, keyResourceIdDefaultValue);
}
public String getString(SharedPreferences pref, @StringRes int keyResourceId, @StringRes int keyResourceIdDefaultValue) {
public String getString(final SharedPreferences pref, @StringRes int keyResourceId, @StringRes int keyResourceIdDefaultValue) {
return pref.getString(rstr(keyResourceId), rstr(keyResourceIdDefaultValue));
}
public void setStringArray(@StringRes int keyResourceId, Object[] values) {
setStringArray(prefApp, keyResourceId, values);
setStringArray(_prefApp, keyResourceId, values);
}
public void setStringArray(SharedPreferences pref, @StringRes int keyResourceId, Object[] values) {
public void setStringArray(final SharedPreferences pref, @StringRes int keyResourceId, Object[] values) {
StringBuilder sb = new StringBuilder();
for (Object value : values) {
sb.append(ARRAY_SEPARATOR);
@ -179,12 +181,12 @@ public class AppSettingsBase {
@NonNull
public String[] getStringArray(@StringRes int keyResourceId) {
return getStringArray(prefApp, keyResourceId);
return getStringArray(_prefApp, keyResourceId);
}
@NonNull
public String[] getStringArray(SharedPreferences pref, @StringRes int keyResourceId) {
String value = pref.getString(rstr(keyResourceId), ARRAY_SEPARATOR);
public String[] getStringArray(final SharedPreferences pref, @StringRes int keyResourceId) {
String value = pref.getString(rstr(keyResourceId), ARRAY_SEPARATOR).replace(ARRAY_SEPARATOR_SUBSTITUTE, ARRAY_SEPARATOR);
if (value.equals(ARRAY_SEPARATOR)) {
return new String[0];
}
@ -192,133 +194,133 @@ public class AppSettingsBase {
}
public void setStringList(@StringRes int keyResourceId, List<String> values) {
setStringList(prefApp, keyResourceId, values);
setStringList(_prefApp, keyResourceId, values);
}
public void setStringList(SharedPreferences pref, @StringRes int keyResourceId, List<String> values) {
public void setStringList(final SharedPreferences pref, @StringRes int keyResourceId, List<String> values) {
setStringArray(pref, keyResourceId, values.toArray(new String[values.size()]));
}
public ArrayList<String> getStringList(@StringRes int keyResourceId) {
return getStringList(prefApp, keyResourceId);
return getStringList(_prefApp, keyResourceId);
}
public ArrayList<String> getStringList(SharedPreferences pref, @StringRes int keyResourceId) {
public ArrayList<String> getStringList(final SharedPreferences pref, @StringRes int keyResourceId) {
return new ArrayList<>(Arrays.asList(getStringArray(pref, keyResourceId)));
}
public void setLong(@StringRes int keyResourceId, long value) {
setLong(prefApp, keyResourceId, value);
setLong(_prefApp, keyResourceId, value);
}
public void setLong(SharedPreferences pref, @StringRes int keyResourceId, long value) {
public void setLong(final SharedPreferences pref, @StringRes int keyResourceId, long value) {
pref.edit().putLong(rstr(keyResourceId), value).apply();
}
public long getLong(@StringRes int keyResourceId, long defaultValue) {
return getLong(prefApp, keyResourceId, defaultValue);
return getLong(_prefApp, keyResourceId, defaultValue);
}
public long getLong(SharedPreferences pref, @StringRes int keyResourceId, long defaultValue) {
public long getLong(final SharedPreferences pref, @StringRes int keyResourceId, long defaultValue) {
return pref.getLong(rstr(keyResourceId), defaultValue);
}
public void setBool(@StringRes int keyResourceId, boolean value) {
setBool(prefApp, keyResourceId, value);
setBool(_prefApp, keyResourceId, value);
}
public void setBool(SharedPreferences pref, @StringRes int keyResourceId, boolean value) {
public void setBool(final SharedPreferences pref, @StringRes int keyResourceId, boolean value) {
pref.edit().putBoolean(rstr(keyResourceId), value).apply();
}
public boolean getBool(@StringRes int keyResourceId, boolean defaultValue) {
return getBool(prefApp, keyResourceId, defaultValue);
return getBool(_prefApp, keyResourceId, defaultValue);
}
public boolean getBool(SharedPreferences pref, @StringRes int keyResourceId, boolean defaultValue) {
public boolean getBool(final SharedPreferences pref, @StringRes int keyResourceId, boolean defaultValue) {
return pref.getBoolean(rstr(keyResourceId), defaultValue);
}
public int getColor(String key, int defaultColor) {
return getColor(prefApp, key, defaultColor);
return getColor(_prefApp, key, defaultColor);
}
public int getColor(SharedPreferences pref, String key, int defaultColor) {
public int getColor(final SharedPreferences pref, String key, int defaultColor) {
return pref.getInt(key, defaultColor);
}
public int getColor(@StringRes int keyResourceId, int defaultColor) {
return getColor(prefApp, keyResourceId, defaultColor);
return getColor(_prefApp, keyResourceId, defaultColor);
}
public int getColor(SharedPreferences pref, @StringRes int keyResourceId, int defaultColor) {
public int getColor(final SharedPreferences pref, @StringRes int keyResourceId, int defaultColor) {
return pref.getInt(rstr(keyResourceId), defaultColor);
}
public void setDouble(@StringRes int keyResId, double value) {
setDouble(prefApp, keyResId, value);
setDouble(_prefApp, keyResId, value);
}
public void setDouble(SharedPreferences pref, @StringRes int keyResId, double value) {
prefApp.edit().putLong(rstr(keyResId), Double.doubleToRawLongBits(value)).apply();
public void setDouble(final SharedPreferences pref, @StringRes int keyResId, double value) {
_prefApp.edit().putLong(rstr(keyResId), Double.doubleToRawLongBits(value)).apply();
}
public double getDouble(@StringRes int keyResId, double defaultValue) {
return getDouble(prefApp, keyResId, defaultValue);
return getDouble(_prefApp, keyResId, defaultValue);
}
public double getDouble(SharedPreferences pref, @StringRes int keyResId, double defaultValue) {
return Double.longBitsToDouble(prefApp.getLong(rstr(keyResId), Double.doubleToLongBits(defaultValue)));
public double getDouble(final SharedPreferences pref, @StringRes int keyResId, double defaultValue) {
return Double.longBitsToDouble(_prefApp.getLong(rstr(keyResId), Double.doubleToLongBits(defaultValue)));
}
public int getIntOfStringPref(@StringRes int keyResId, int defaultValue) {
String strNum = prefApp.getString(context.getString(keyResId), Integer.toString(defaultValue));
String strNum = _prefApp.getString(_context.getString(keyResId), Integer.toString(defaultValue));
return Integer.valueOf(strNum);
}
public void setInt(@StringRes int keyResourceId, int value) {
setInt(prefApp, keyResourceId, value);
setInt(_prefApp, keyResourceId, value);
}
public void setInt(SharedPreferences pref, @StringRes int keyResourceId, int value) {
public void setInt(final SharedPreferences pref, @StringRes int keyResourceId, int value) {
pref.edit().putInt(rstr(keyResourceId), value).apply();
}
public int getInt(@StringRes int keyResourceId, int defaultValue) {
return getInt(prefApp, keyResourceId, defaultValue);
return getInt(_prefApp, keyResourceId, defaultValue);
}
public int getInt(SharedPreferences pref, @StringRes int keyResourceId, int defaultValue) {
public int getInt(final SharedPreferences pref, @StringRes int keyResourceId, int defaultValue) {
return pref.getInt(rstr(keyResourceId), defaultValue);
}
public void setIntList(@StringRes int keyResId, List<Integer> values) {
setIntList(prefApp, keyResId, values);
setIntList(_prefApp, keyResId, values);
}
public void setIntList(SharedPreferences pref, @StringRes int keyResId, List<Integer> values) {
public void setIntList(final SharedPreferences pref, @StringRes int keyResId, List<Integer> values) {
StringBuilder sb = new StringBuilder();
for (int value : values) {
sb.append(ARRAY_SEPARATOR);
sb.append(Integer.toString(value));
}
setString(prefApp, keyResId, sb.toString().replaceFirst(ARRAY_SEPARATOR, ""));
setString(_prefApp, keyResId, sb.toString().replaceFirst(ARRAY_SEPARATOR, ""));
}
@NonNull
public ArrayList<Integer> getIntList(@StringRes int keyResId) {
return getIntList(prefApp, keyResId);
return getIntList(_prefApp, keyResId);
}
@NonNull
public ArrayList<Integer> getIntList(SharedPreferences pref, @StringRes int keyResId) {
ArrayList<Integer> ret = new ArrayList<>();
String value = getString(prefApp, keyResId, ARRAY_SEPARATOR);
public ArrayList<Integer> getIntList(final SharedPreferences pref, @StringRes int keyResId) {
final ArrayList<Integer> ret = new ArrayList<>();
final String value = getString(_prefApp, keyResId, ARRAY_SEPARATOR);
if (value.equals(ARRAY_SEPARATOR)) {
return ret;
}
for (String s : value.split(ARRAY_SEPARATOR)) {
ret.add(Integer.parseInt(s));
for (String intstr : value.split(ARRAY_SEPARATOR)) {
ret.add(Integer.parseInt(intstr));
}
return ret;
}

View File

@ -37,7 +37,6 @@ import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.webkit.WebView;
import android.widget.TextView;
@ -45,38 +44,49 @@ import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Locale;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.BuildConfig;
import com.github.dfa.diaspora_android.R;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection"})
public class Helpers {
protected Context context;
//########################
//## Members, Constructors
//########################
protected Context _context;
protected Helpers(Context context) {
this.context = context;
}
public static Helpers get() {
return new Helpers(App.get());
public Helpers(Context context) {
_context = context;
}
//########################
//## Methods
//########################
public String str(@StringRes int strResId) {
return context.getString(strResId);
return _context.getString(strResId);
}
static class ResType {
public static final String DRAWABLE = "drawable";
public static final String STRING = "string";
public static final String PLURAL = "plural";
public static final String COLOR = "color";
public static final String STYLE = "style";
public static final String ARRAY = "array";
public static final String DIMEN = "dimen";
public static final String MENU = "menu";
public static final String RAW = "raw";
}
public Drawable drawable(@DrawableRes int resId) {
return ContextCompat.getDrawable(context, resId);
return ContextCompat.getDrawable(_context, resId);
}
public int color(@ColorRes int resId) {
return ContextCompat.getColor(context, resId);
return ContextCompat.getColor(_context, resId);
}
public Context context() {
return context;
return _context;
}
public String colorToHexString(int intColor) {
@ -85,35 +95,87 @@ public class Helpers {
public String getAppVersionName() {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
PackageManager manager = _context.getPackageManager();
PackageInfo info = manager.getPackageInfo(_context.getPackageName(), 0);
return info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return "unknown";
return "?";
}
}
public int getResId(final String type, final String name) {
return _context.getResources().getIdentifier(name, type, _context.getPackageName());
}
public void openWebpageInExternalBrowser(String url) {
public boolean areResIdsAvailable(final String type, final String... names) {
for (String name : names) {
if (getResId(type, name) == 0) {
return false;
}
}
return true;
}
public void openWebpageInExternalBrowser(final String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
_context.startActivity(intent);
}
public void showDonateBitcoinRequest() {
if (!BuildConfig.IS_GPLAY_BUILD) {
/**
* https://stackoverflow.com/a/25267049
* Gets a field from the project's BuildConfig. This is useful when, for example, flavors
* are used at the project level to set custom fields.
*
* @param fieldName The name of the field-to-access
* @return The value of the field, or {@code null} if the field is not found.
*/
public Object getBuildConfigValue(String fieldName) {
try {
Class<?> clazz = Class.forName(_context.getPackageName() + ".BuildConfig");
Field field = clazz.getField(fieldName);
return field.get(null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public boolean getBuildConfigBoolean(String fieldName, boolean defaultValue) {
Object field = getBuildConfigValue(fieldName);
if (field != null && field instanceof Boolean) {
return (Boolean) field;
}
return defaultValue;
}
public boolean isGooglePlayBuild() {
return getBuildConfigBoolean("IS_GPLAY_BUILD", true);
}
public boolean isFossBuild() {
return getBuildConfigBoolean("IS_FOSS_BUILD", false);
}
// Requires donate__bitcoin_* resources (see below) to be available as string resource
public void showDonateBitcoinRequest(@StringRes final int strResBitcoinId, @StringRes final int strResBitcoinAmount, @StringRes final int strResBitcoinMessage, @StringRes final int strResAlternativeDonateUrl) {
if (!isGooglePlayBuild()) {
String btcUri = String.format("bitcoin:%s?amount=%s&label=%s&message=%s",
str(R.string.donate__bitcoin_id), str(R.string.donate__bitcoin_amount),
str(R.string.donate__bitcoin_message), str(R.string.donate__bitcoin_message));
str(strResBitcoinId), str(strResBitcoinAmount),
str(strResBitcoinMessage), str(strResBitcoinMessage));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(btcUri));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
_context.startActivity(intent);
} catch (ActivityNotFoundException e) {
openWebpageInExternalBrowser(str(R.string.donate__bitcoin_url));
openWebpageInExternalBrowser(str(strResAlternativeDonateUrl));
}
}
}
@ -127,7 +189,7 @@ public class Helpers {
linePostfix = linePostfix == null ? "" : linePostfix;
try {
br = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(rawResId)));
br = new BufferedReader(new InputStreamReader(_context.getResources().openRawResource(rawResId)));
while ((line = br.readLine()) != null) {
sb.append(linePrefix);
sb.append(line);
@ -147,9 +209,9 @@ public class Helpers {
}
public void showDialogWithRawFileInWebView(String fileInRaw, @StringRes int resTitleId) {
WebView wv = new WebView(context);
WebView wv = new WebView(_context);
wv.loadUrl("file:///android_res/raw/" + fileInRaw);
AlertDialog.Builder dialog = new AlertDialog.Builder(context)
AlertDialog.Builder dialog = new AlertDialog.Builder(_context)
.setPositiveButton(android.R.string.ok, null)
.setTitle(resTitleId)
.setView(wv);
@ -165,16 +227,16 @@ public class Helpers {
public boolean isConnectedToInternet() {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
_context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
return activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
}
public void restartApp(Class classToStartupWith) {
Intent restartIntent = new Intent(context, classToStartupWith);
PendingIntent restartIntentP = PendingIntent.getActivity(context, 555,
Intent restartIntent = new Intent(_context, classToStartupWith);
PendingIntent restartIntentP = PendingIntent.getActivity(_context, 555,
restartIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, restartIntentP);
System.exit(0);
}
@ -182,9 +244,9 @@ public class Helpers {
public String loadMarkdownForTextViewFromRaw(@RawRes int rawMdFile, String prepend) {
try {
return new SimpleMarkdownParser()
.parse(context.getResources().openRawResource(rawMdFile),
.parse(_context.getResources().openRawResource(rawMdFile),
prepend, SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW)
.replaceColor("#000001", color(R.color.accent))
.replaceColor("#000001", color(getResId(ResType.COLOR, "accent")))
.removeMultiNewlines().replaceBulletCharacter("*").getHtml();
} catch (IOException e) {
e.printStackTrace();
@ -204,7 +266,7 @@ public class Helpers {
}
public double getEstimatedScreenSizeInches() {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
DisplayMetrics dm = _context.getResources().getDisplayMetrics();
double density = dm.density * 160;
double x = Math.pow(dm.widthPixels / density, 2);
@ -216,7 +278,7 @@ public class Helpers {
}
public boolean isInPortraitMode() {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
return _context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
public Locale getLocaleByAndroidCode(String code) {
@ -231,8 +293,16 @@ public class Helpers {
// "en"/"de"/"de-rAt"; Empty string = default locale
public void setAppLanguage(String androidLocaleString) {
Locale locale = getLocaleByAndroidCode(androidLocaleString);
Configuration config = context.getResources().getConfiguration();
Configuration config = _context.getResources().getConfiguration();
config.locale = locale != null ? locale : Locale.getDefault();
context.getResources().updateConfiguration(config, null);
_context.getResources().updateConfiguration(config, null);
}
public float px2dp(final float px) {
return px / _context.getResources().getDisplayMetrics().density;
}
public float dp2px(final float dp) {
return dp * _context.getResources().getDisplayMetrics().density;
}
}

View File

@ -24,23 +24,19 @@ import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import com.github.dfa.diaspora_android.R;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "SpellCheckingInspection"})
public class HelpersA extends Helpers {
protected Activity activity;
//########################
//## Members, Constructors
//########################
protected Activity _activity;
protected HelpersA(Activity activity) {
public HelpersA(final Activity activity) {
super(activity);
this.activity = activity;
_activity = activity;
}
public static HelpersA get(Activity activity) {
return new HelpersA(activity);
}
//########################
//## Methods
//########################
@ -48,45 +44,46 @@ public class HelpersA extends Helpers {
/**
* Animate to specified Activity
*
* @param to The class of the activity
* @param finishFromActivity true: Finish the current activity
* @param requestCode Request code for stating the activity, not waiting for result if null
* @param to The class of the _activity
* @param finishFromActivity true: Finish the current _activity
* @param requestCode Request code for stating the _activity, not waiting for result if null
*/
public void animateToActivity(Class to, Boolean finishFromActivity, Integer requestCode) {
animateToActivity(new Intent(activity, to), finishFromActivity, requestCode);
animateToActivity(new Intent(_activity, to), finishFromActivity, requestCode);
}
/**
* Animate to activity specified in intent
* Animate to Activity specified in intent
* Requires animation resources
*
* @param intent Intent to open start an activity
* @param finishFromActivity true: Finish the current activity
* @param requestCode Request code for stating the activity, not waiting for result if null
* @param intent Intent to open start an _activity
* @param finishFromActivity true: Finish the current _activity
* @param requestCode Request code for stating the _activity, not waiting for result if null
*/
public void animateToActivity(Intent intent, Boolean finishFromActivity, Integer requestCode) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
if (requestCode != null) {
activity.startActivityForResult(intent, requestCode);
_activity.startActivityForResult(intent, requestCode);
} else {
activity.startActivity(intent);
_activity.startActivity(intent);
}
activity.overridePendingTransition(R.anim.fadein, R.anim.fadeout);
_activity.overridePendingTransition(getResId(ResType.DIMEN, "fadein"), getResId(ResType.DIMEN, "fadeout"));
if (finishFromActivity != null && finishFromActivity) {
activity.finish();
_activity.finish();
}
}
public void showSnackBar(@StringRes int stringId, boolean showLong) {
Snackbar.make(activity.findViewById(android.R.id.content), stringId,
Snackbar.make(_activity.findViewById(android.R.id.content), stringId,
showLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
}
public void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
InputMethodManager inputMethodManager = (InputMethodManager) _activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (_activity.getCurrentFocus() != null && _activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(_activity.getCurrentFocus().getWindowToken(), 0);
}
}
@ -95,14 +92,14 @@ public class HelpersA extends Helpers {
}
public void showDialogWithHtmlTextView(@StringRes int resTitleId, String text, boolean isHtml, DialogInterface.OnDismissListener dismissedListener) {
AppCompatTextView textView = new AppCompatTextView(context);
AppCompatTextView textView = new AppCompatTextView(_context);
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
context.getResources().getDisplayMetrics());
_context.getResources().getDisplayMetrics());
textView.setMovementMethod(new LinkMovementMethod());
textView.setPadding(padding, 0, padding, 0);
textView.setText(isHtml ? new SpannableString(Html.fromHtml(text)) : text);
AlertDialog.Builder dialog = new AlertDialog.Builder(context)
AlertDialog.Builder dialog = new AlertDialog.Builder(_context)
.setPositiveButton(android.R.string.ok, null)
.setOnDismissListener(dismissedListener)
.setTitle(resTitleId)

View File

@ -21,7 +21,7 @@
* You can e.g. apply a accent color by replacing #000001 with your accentColor string.
*
* FILTER_ANDROID_TEXTVIEW output is intended to be used at simple Android TextViews,
* were a limited set of html tags is supported. This allow to still display e.g. a simple
* were a limited set of _html tags is supported. This allow to still display e.g. a simple
* CHANGELOG.md file without including a WebView for showing HTML, or other additional UI-libraries.
*
* FILTER_WEB is intended to be used at engines understanding most common HTML tags.
@ -40,15 +40,9 @@ import java.io.InputStreamReader;
*/
@SuppressWarnings({"WeakerAccess", "CaughtExceptionImmediatelyRethrown", "SameParameterValue", "unused", "SpellCheckingInspection", "RepeatedSpace", "SingleCharAlternation"})
public class SimpleMarkdownParser {
private static SimpleMarkdownParser instance;
public static SimpleMarkdownParser get() {
if (instance == null) {
instance = new SimpleMarkdownParser();
}
return instance;
}
//########################
//## Statics
//########################
public interface SmpFilter {
String filter(String text);
}
@ -56,7 +50,7 @@ public class SimpleMarkdownParser {
public final static SmpFilter FILTER_ANDROID_TEXTVIEW = new SmpFilter() {
@Override
public String filter(String text) {
// TextView supports a limited set of html tags, most notably
// TextView supports a limited set of _html tags, most notably
// a href, b, big, font size&color, i, li, small, u
// Don't start new line if 2 empty lines and heading
@ -118,17 +112,32 @@ public class SimpleMarkdownParser {
};
//########################
//## Members
//## Singleton
//########################
private SmpFilter defaultSmpFilter;
private String html;
private static SimpleMarkdownParser instance;
public static SimpleMarkdownParser get() {
if (instance == null) {
instance = new SimpleMarkdownParser();
}
return instance;
}
//########################
//## Members, Constructors
//########################
private SmpFilter _defaultSmpFilter;
private String _html;
public SimpleMarkdownParser() {
setDefaultSmpFilter(FILTER_WEB);
}
public SimpleMarkdownParser setDefaultSmpFilter(SmpFilter defaultSmpFilter) {
this.defaultSmpFilter = defaultSmpFilter;
//########################
//## Methods
//########################
public SimpleMarkdownParser setDefaultSmpFilter(SmpFilter _defaultSmpFilter) {
this._defaultSmpFilter = _defaultSmpFilter;
return this;
}
@ -149,7 +158,7 @@ public class SimpleMarkdownParser {
sb.append("\n");
}
} catch (IOException rethrow) {
html = "";
_html = "";
throw rethrow;
} finally {
if (br != null) {
@ -159,47 +168,47 @@ public class SimpleMarkdownParser {
}
}
}
html = parse(sb.toString(), "", smpFilters).getHtml();
_html = parse(sb.toString(), "", smpFilters).getHtml();
return this;
}
public SimpleMarkdownParser parse(String markdown, String lineMdPrefix, SmpFilter... smpFilters) throws IOException {
html = markdown;
_html = markdown;
if (smpFilters.length == 0) {
smpFilters = new SmpFilter[]{defaultSmpFilter};
smpFilters = new SmpFilter[]{_defaultSmpFilter};
}
for (SmpFilter smpFilter : smpFilters) {
html = smpFilter.filter(html).trim();
_html = smpFilter.filter(_html).trim();
}
return this;
}
public String getHtml() {
return html;
return _html;
}
public SimpleMarkdownParser setHtml(String html) {
this.html = html;
_html = html;
return this;
}
public SimpleMarkdownParser removeMultiNewlines() {
html = html.replace("\n", "").replaceAll("(<br/>){3,}", "<br/><br/>");
_html = _html.replace("\n", "").replaceAll("(<br/>){3,}", "<br/><br/>");
return this;
}
public SimpleMarkdownParser replaceBulletCharacter(String replacment) {
html = html.replace("&#8226;", replacment);
_html = _html.replace("&#8226;", replacment);
return this;
}
public SimpleMarkdownParser replaceColor(String hexColor, int newIntColor) {
html = html.replace(hexColor, String.format("#%06X", 0xFFFFFF & newIntColor));
_html = _html.replace(hexColor, String.format("#%06X", 0xFFFFFF & newIntColor));
return this;
}
@Override
public String toString() {
return html != null ? html : "";
return _html != null ? _html : "";
}
}