Hi guys.
Within this post you can find a group of utilities or methods to reduce time while developing your apps.
These utilities were written when i first started coding 😛
This is the list of utilities:
- Shared preferences
- Hide/Show the keyboard
- Hide/Show the title bar
- Logging
Shared Preferences
When creating applications, most of the time you will need to store information within the device in order to use at different stages. The info is stored by name which will be used to extract it. An example of things which can be stored is the session in the http web application.
In the shared pref’s class, you can set/get any int, string, bool, double type value or you can add your own type.
The Instance
This is the instance of the SharedPreferences class which is needed in order to access it from the application. It can be accessed from any place in order to set/get your info.
public class SharedPrefs {
private static SharedPreferences instance;
private static int NULLINT = -794613258;
}
Constructor
Constructor method: The current context of the application is passed when creating the instance. Usually it is created from the global class application which allows us to access it from all the activities.
public SharedPrefs(Context ctx) {
if (instance == null)
instance = ctx.getSharedPreferences("Agenda", Context.MODE_PRIVATE);
}
public static SharedPreferences getInstance() {
return instance;
}
Setting Data
These are the methods which allow you to save each object based on it’s type such as integer, boolean, string, or float. You can also add your predefined type as well.
public static void saveString(String key, String val) {
SharedPreferences.Editor editor = instance.edit();
editor.putString(key, val);
editor.apply();
}
public static void saveInt(String key, int val) {
SharedPreferences.Editor editor = instance.edit();
editor.putInt(key, val);
editor.apply();
}
public static void saveBoolean(String key, Boolean val) {
SharedPreferences.Editor editor = instance.edit();
editor.putBoolean(key, val);
editor.apply();
}
public static void saveFloat(String key, float val) {
SharedPreferences.Editor editor = instance.edit();
editor.putFloat(key, val);
editor.apply();
}
public static void save(String key, Object val) {
if (val instanceof String)
saveString(key, String.valueOf(val));
else if (val instanceof Boolean)
saveBoolean(key, Boolean.valueOf(val.toString()));
else if (val instanceof Integer)
saveInt(key, Integer.parseInt(val.toString()));
else if (val instanceof Double || val instanceof Float)
saveFloat(key, Float.parseFloat(val.toString()));
}
Getting Data
These are the methods which can be used to get the value depending on its type.
public static String loadString(String key) {
return instance.getString(key, null);
}
public static int loadInt(String key) {
return instance.getInt(key, NULLINT);
}
public static Boolean loadBoolean(String key) {
return instance.getBoolean(key, false);
}
public static float loadFloat(String key) {
return instance.getFloat(key, -0.0f);
}
}
Other useful utilities to:
- log
- sysout
- toJSon
- getMimeType
- getExtension
- getFileName
- NumberFormater
- hideTiTleBar
- hidekeyboardv2
- hideKeyboard
- showKeyboard
- hideSoftKeyboard
- showtoast
- getScreenWH
- getToday
/**
* print a message in the debug
*
* @param msg
*/
public static void log(String msg) {
Log.d("[" + appName + "]", msg);
}
/**
* print a message in the debug
*
* @param msg
*/
public static void sysout(String msg) {
System.out.println(appName + " --> " + msg);
}
/**
* convert Object to json string
*
* @param o Object to convert
* @return
*/
public static String toJSon(Object o) {
Gson json = new Gson();
String s = json.toJson(o);
return s;
}
/**
* get the mime type of the file
*
* @param url = file path or whatever suitable URL you want
* @return
*/
public static String getMimeType(String url) {
String type = null;
String extension = getExtension(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
/**
* get the extension of the file
*
* @param url = file path or whatever suitable URL you want
* @return
*/
public static String getExtension(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return extension;
}
/**
* get the name of the file
*
* @param url = file path or whatever suitable URL you want
* @return
*/
public static String getFileName(String url) {
File f = new File(url);
return f.getName();
}
/**
* format a number to 00,00,00.00
*
* @param t number
* @return
*/
public static String NumberFormater(Double t) {
NumberFormat formatter = new DecimalFormat("###,###,###.##");
return formatter.format(t);
}
/**
* hide the title bar of the activity
*
* @param A activity to hide the title bar.
*/
public static void hideTiTleBar(Activity A) {
A.requestWindowFeature(Window.FEATURE_NO_TITLE);
A.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/**
* hide keyboard
*
* @param A activity to hide the title bar.
*/
public static void hidekeyboardv2(Activity A) {
A.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
/**
* hide keyboard
*
* @param activity A activity to hide the keyboard.
* @param view view of the activity
*/
public static void hideKeyboard(Context activity, View view) {
InputMethodManager in = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* show keyboard
*
* @param activity activity
* @param view view to show keyboard for
*/
public static void showKeyboard(Context activity, View view) {
InputMethodManager in = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
in.showSoftInput(view, 0);
}
/**
* @param activity activity to hide the keybord
*/
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
/**
* show toast message
*
* @param activity activity to show toast for
* @param msg the message to show
*/
public static void showtoast(Context activity, String msg) {
Toast.makeText(activity.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
/**
* get screen height and width
*
* @param context context
* @return a json object {width: 1234, height: 2432}
*/
public static JsonObject getScreenWH(Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
JsonObject json = new JsonObject();
json.addProperty("width", width);
json.addProperty("height", height);
return json;
}
/**
* round a number
*
* @param value
* @param places
* @return rounded number
*/
public static double round(double value, int places) {
if (places < 0)
return 0.0;
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
/**
* get today date in your format
*
* @param format of the date you want to get
* @return String of the date in the format given
*/
public static String getToday(String format) {
SimpleDateFormat dfDate = new SimpleDateFormat(format);
String data = "";
Calendar c = Calendar.getInstance();
data = dfDate.format(c.getTime());
return data;
}