Skip to content

Instantly share code, notes, and snippets.

@gturedi
Last active February 10, 2016 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gturedi/83726eb2d3bc5ed4d7bf to your computer and use it in GitHub Desktop.
Save gturedi/83726eb2d3bc5ed4d7bf to your computer and use it in GitHub Desktop.
utility classes for android development
package gturedi.gist;
import android.app.Activity;
import android.support.annotation.StringRes;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
@SuppressWarnings("ResourceType")
public class ActivityUtil {
private static final int LOADING_PANEL_ID = 12;
private static final int MESSAGE_PANEL_ID = 13;
private static final int PROGRESS_SIZE = 50;
private final Activity activity;
private ViewGroup root;
public ActivityUtil(Activity activity) {
this.activity = activity;
root = (ViewGroup) activity.findViewById(android.R.id.content);
}
public AlertDialog createAlert(@StringRes int title, @StringRes int msg) {
return createAlert(activity.getString(title), activity.getString(msg));
}
public AlertDialog createAlert(String title, String msg) {
return new AlertDialog.Builder(activity)
.setTitle(title)
.setMessage(msg)
.setNegativeButton(android.R.string.cancel, null)
.create();
}
public void showLoading() {
AndroidUtil.setVisibilityForChildren(root, View.GONE);
View loadingPanel = root.findViewById(LOADING_PANEL_ID);
if (loadingPanel == null) root.addView(createLoadingPanel());
else loadingPanel.setVisibility(View.VISIBLE);
}
public void hideLoading() {
View panel = root.findViewById(LOADING_PANEL_ID);
if (panel != null) root.removeView(panel);
AndroidUtil.setVisibilityForChildren(root, View.VISIBLE);
}
public void showMessage(@StringRes int stringRes) {
showMessage(activity.getString(stringRes));
}
public void showMessage(String msg) {
AndroidUtil.setVisibilityForChildren(root, View.GONE);
View panel = root.findViewById(MESSAGE_PANEL_ID);
if (panel == null) root.addView(createMessagePanel(msg));
else panel.setVisibility(View.VISIBLE);
}
public void hideMessage() {
View panel = root.findViewById(MESSAGE_PANEL_ID);
if (panel != null) root.removeView(panel);
AndroidUtil.setVisibilityForChildren(root, View.VISIBLE);
}
// helpers //
private View createLoadingPanel() {
ProgressBar progressBar = new ProgressBar(activity);
int size = new ContextUtil(activity.getApplication()).convertDpToPixel(PROGRESS_SIZE);
progressBar.setLayoutParams(new ViewGroup.LayoutParams(size, size));
return createPanel(progressBar, LOADING_PANEL_ID);
}
private View createMessagePanel(String msg) {
TextView tv = new TextView(activity);
tv.setText(msg);
return createPanel(tv, MESSAGE_PANEL_ID);
}
private LinearLayout createPanel(View child, int id) {
LinearLayout lnr = new LinearLayout(activity);
lnr.setId(id);
lnr.setGravity(Gravity.CENTER);
lnr.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
lnr.addView(child);
return lnr;
}
}
package gturedi.gist;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.IntRange;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import java.util.List;
import gturedi.gist.BuildConfig;
public class AndroidUtil {
public static boolean isSdCardvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static Intent createShareIntent(String subject, String text) {
return new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, subject)
.putExtra(Intent.EXTRA_TEXT, text);
}
public static Intent createMailIntent(String subject, String text, String... receivers) {
return new Intent(Intent.ACTION_SEND)
.setType("plain/text")
.putExtra(Intent.EXTRA_SUBJECT, subject)
.putExtra(Intent.EXTRA_TEXT, text)
.putExtra(Intent.EXTRA_EMAIL, receivers);
}
public static Intent createMarketIntent() {
String url = "market://details?id=" + BuildConfig.APPLICATION_ID;
return createBrowserIntent(url);
}
public static Intent createBrowserIntent(String url) {
return new Intent(Intent.ACTION_VIEW, Uri.parse(url));
}
public static Intent createMusicPlayerIntent(String url) {
return new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setType("audio/*");
}
public static Intent createVideoPlayerIntent(String url) {
return new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setType("video/*");
}
public static void navigate(FragmentManager fm, Fragment fragment, boolean addToBackStack) {
FragmentTransaction trans = fm.beginTransaction()
.replace(android.R.id.content, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack) trans.addToBackStack(fragment.getClass().getSimpleName());
trans.commit();
}
public static void navigate(FragmentManager fm, Fragment fragment) {
fm.beginTransaction()
.replace(android.R.id.content, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
}
public static void bindDataForSpinner(Spinner spinner, List items) {
ArrayAdapter adapter = new ArrayAdapter<>(
spinner.getContext(),
android.R.layout.simple_spinner_dropdown_item,
items);
//adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public static void bindDataForListView(ListView listView, List items) {
ArrayAdapter adapter = new ArrayAdapter<>(
listView.getContext(),
android.R.layout.simple_list_item_1,
items);
listView.setAdapter(adapter);
}
public boolean isApiLevelSupported(@IntRange(from = 2, to = 23) int target) {
return Build.VERSION.SDK_INT >= target;
}
public static void setVisibilityForChildren(ViewGroup parent, int visibility) {
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).setVisibility(visibility);
}
}
public static void setEnabledForChildren(ViewGroup parent, boolean enabled) {
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).setEnabled(enabled);
}
}
public static String getTimeAgoString(long time) {
return DateUtils.getRelativeTimeSpanString(
time,
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS).toString();
}
}
package gturedi.gist;
import android.app.DownloadManager;
import android.content.Context;
import android.graphics.Point;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
public class ContextUtil {
private final Context ctx;
public ContextUtil(Context ctx) {
this.ctx = ctx;
}
public void showToast(@StringRes int resId) {
showToast(ctx.getString(resId));
}
public void showToast(String msg) {
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}
// requires permission: ACCESS_NETWORK_STATE
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected();
}
// requires permission: ACCESS_FINE_LOCATION (for pre-lollipop)
public boolean isGpsAvailable() {
LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public Point getScreenDimensions() {
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = ctx.getResources().getDisplayMetrics();
return (int) (dp * (metrics.densityDpi / 160f));
}
public int convertPixelsToDp(int px) {
DisplayMetrics metrics = ctx.getResources().getDisplayMetrics();
return (int) (px / (metrics.densityDpi / 160f));
}
public void hideKeyboard(View target) {
try {
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(target.getApplicationWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public void startDownloadManager(String url) {
DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
dm.enqueue(request);
}
public String str(@StringRes int id) {
return ctx.getString(id);
}
public int color(@ColorRes int id) {
return ctx.getResources().getColor(id);
}
}
package gturedi.gist;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
public class FileUtil {
public static final String UTF_8 = "utf-8";
public static void deleteRecursively(File dir) {
if (dir.isDirectory()) {
for (String item : dir.list()) {
deleteRecursively(new File(dir, item));
}
}
dir.delete();
}
public static String convertStreamToString(InputStream in) {
try {
return new String(convertStreamToByteArray(in), UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
public static byte[] convertStreamToByteArray(InputStream in) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copyStream(in, out);
return out.toByteArray();
}
public static void copyStream(InputStream in, OutputStream out) {
try {
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package gturedi.gist;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class GeneralUtil {
public static String replaceIfEmpty(String input, String defaultValue) {
return isNullOrEmpty(input) ? defaultValue : input;
}
public static boolean isNullOrEmpty(String target) {
return target == null || target.equals("");
}
public static boolean isNullOrEmpty(List target) {
return target == null || target.size() == 0;
}
public static boolean isNullOrEmpty(Object[] target) {
return target == null || target.length == 0;
}
public static List<String> selectField(List items, String fieldName) {
List<String> result = new ArrayList<>(items.size());
for (Object item : items) {
try {
Field field = item.getClass().getField(fieldName);
String val = field.get(item).toString();
result.add(val);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return result;
}
public static void runAsync(Runnable runnable) {
new Thread(runnable).start();
}
}
package gturedi.gist;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class HttpUtil {
public static final String UA_ANDROID_LG = "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
public static String makePost(String url, Map<String, String> headers, byte[] params) {
try {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("User-Agent", UA_ANDROID_LG);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
if (headers != null)
for (Map.Entry<String, String> item : headers.entrySet())
con.setRequestProperty(item.getKey(), item.getValue());
OutputStream os = con.getOutputStream();
os.write(params);
os.close();
return FileUtil.convertStreamToString(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static String makeGet(String url, Map<String, String> headers, Map<String, String> params) {
try {
url = url + createUrlParams(params);
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.addRequestProperty("User-Agent", UA_ANDROID_LG);
addHeaders(conn, headers);
return FileUtil.convertStreamToString(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static void downloadFile(String url, String path) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.addRequestProperty("User-Agent", UA_ANDROID_LG);
FileOutputStream out = new FileOutputStream(path);
FileUtil.copyStream(conn.getInputStream(), out);
} catch (Exception e) {
e.printStackTrace();
}
}
// helpers //
private static String createUrlParams(Map<String, String> params) {
StringBuilder result = new StringBuilder("?");
for (Map.Entry<String, String> item : params.entrySet()) {
String charset = "utf-8";
try {
result.append(URLEncoder.encode(item.getKey(), charset))
.append("=")
.append(URLEncoder.encode(item.getValue(), charset))
.append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result.toString();
}
private static void addHeaders(HttpURLConnection conn, Map<String, String> headers) {
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> item : headers.entrySet()) {
conn.addRequestProperty(item.getKey(), item.getValue());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment