Android 应用程序常用工具类及功能包


记得我刚进公司实习的时候,总喜欢逮个人就问android应用程序是怎么样一步一步架构起来的,得到的却总是不太懂的回答。眨眼间已经毕业近半年
多,接触过 两个慢慢成形的应用后,打算写一下自己的见解。

、应用包目录

做过android应用开发的应该都知道,开发初期会大体上给应用分几个包,用来存储不同类别的.java文件,比如说com.lto.views用来 存放自定义View, com.lto.adapter用来存放应用中各种AdapterView需要用到的Adapter等等。下面分下大家看看合理不。

1. ***.***.adapter
应用中会使用到的所有Adapter,尽量作为一个单独的类存放在此包中,能够让整个应用更清晰,后来者读起来也更易懂。
2.***.***.base
正如字面意思,这个包存放基础的东西,比如说整个应用的自定义Application、应用经常使用的Activity基类BaseActivity、自己应用整 体配置aseConfig、以及其他类似的类。
3.***.***.activities
存放应用中所有的activity。
4.***.***.fragments
存放fragment。
5.***.***.utils
存放系统中常用的工具类,后面会详细介绍。
6.***.***.views
存放自定义View(ViewGroup)
7.***.***.db
存放与操作数据库相关的类。
8.***.***.model
存放数据类。
9.***.***.web
存放与网络访问有关的类。
10.***.***.manager
存放管理类,例如***ActivityManager,***DataManager,***SessionManager,***LocationManager……
11.***.***.custom.api
存放第三方api。
12.***.***.anim
存放各种动画类。
13.***.***.pay & ***.***.***.push
如果有需要涉及支付或者推送服务的,可以新建一个这样的包。

可能每个项目团队建包方式都不一样,博主这边也是根据自己项目给出的,大家可以看一下,如果有什么更好的建议可以给博主提一下,万分感谢 。

二、应用常用工具类(***.***.utils)

1.Constants
<span style="font-size:14px;"><span style="font-size:14px;">public class Constants {
    /***************
     * Log
     ********************/
    public static final String LOG_TAG = "Note";
    public static final String PREFERENCES_KEY = "note_heart";
    /***************
     * Calendar Events
     ********************/
    public static final int MAX_EVENTS_COUNT = 15;
    public static final int MAX_EVENTS_SCROLL_COUNT = 84000;// must include
    public static final int MAX_WEEK_SCROLL_COUNT = MAX_EVENTS_SCROLL_COUNT / 7;
    public static final int MAX_MONTH_SCROLL_COUNT = MAX_EVENTS_SCROLL_COUNT / 30;
    public static final int MAX_EVENT_VIEWPAGER_COUNT = 3;
    public static final int MONTH_CALENDAR_COLUMN = 7;
    public static final int ROWS_OF_MONTH_CALENDAR = 6;

    public final static int SELECT_TYPE_FROM_EVENTS_SCROLL = 0x0;
    public final static int SELECT_TYPE_FROM_WEEK_CLICK = 0x1;
    public final static int SELECT_TYPE_FROM_WEEK_SCROLL = 0x2;
    public final static int SELECT_TYPE_FROM_MONTH_CLICK = 0x3;
    public final static int SELECT_TYPE_FROM_MONTH_SCROLL = 0x4;
    public final static int SELECT_TYPE_FROM_JUMP_TO = 0x5;

    public final static int CALENDAR_UPDATE_CALENDAR = 0x7;
    public final static int CALENDAR_UPDATE_WEEK = 0x9;
    public final static int CALENDAR_UPDATE_MONTH = 0x10;
    public final static int UPDATE_DATA = 0x11;
    public final static int CALENDAR_UPDATE_EVENT_LIST = 0x12;

    public static final int FIRST_DAY_OF_WEEK = Calendar.MONDAY;

    /***************Intent Key********************/

    /***************Net Url********************/

    /***************Preferences********************/

    /******************Net Post/Get Params*****************/
    
}</span></span>
2.LogUtils
<span style="font-size:14px;">public class LogUtils {</span>
<span style="font-size:14px;">        //自己修改Log Id</span>
<span style="font-size:14px;">	public static final String LOG_ID = "Note";

	public static final boolean V = Log.VERBOSE >= NoteConfig.MIN_LOG_LEVEL;
	public static final boolean D = Log.DEBUG >= NoteConfig.MIN_LOG_LEVEL;
	public static final boolean I = Log.INFO >= NoteConfig.MIN_LOG_LEVEL;
	public static final boolean W = Log.WARN >= NoteConfig.MIN_LOG_LEVEL;
	public static final boolean DW = NoteConfig.DEV_BUILD
			&& Log.WARN >= NoteConfig.MIN_LOG_LEVEL;
	public static final boolean E = Log.ERROR >= NoteConfig.MIN_LOG_LEVEL;

	private LogUtils() {
	}

	@SuppressWarnings("unused")
	private static void log(int priority, String msg, Throwable throwable) {
		try {
			if (throwable != null)
				Log.println(
						priority,
						LOG_ID,
						new StringBuilder()
								.append(msg)
								.append(", exception:\n\t")
								.append((priority >= Log.ERROR || NoteConfig.DEV_BUILD) ? Log
										.getStackTraceString(throwable)
										: throwable.toString()).toString());
			else
				Log.println(priority, LOG_ID, new StringBuilder().append(msg)
						.toString());

		} catch (Exception e) {
			Log.e(LOG_ID, "Failed to log: " + e.getMessage());
		}
	}

	/**
	 * Warn the incomplete implemented of methods.
	 */
	public static void warnIncomplete() {
		if (NoteConfig.LOG_LINE_NUMBER) {
			StackTraceElement[] sts = Thread.currentThread().getStackTrace();
			StackTraceElement st = null;
			for (int i = 2; i < sts.length; ++i) {
				StackTraceElement tmp = sts[i];
				if (!tmp.getClassName().contains("LogUtils")) {
					st = tmp;
					break;
				}
			}
			if (st != null)
				Log.println(
						Log.WARN,
						LOG_ID,
						new StringBuilder().append(st.getFileName())
								.append(" line").append(st.getLineNumber())
								.append(", ").append(st.getMethodName())
								.append("(): incomplete implementation")
								.toString());
			else
				Log.println(Log.WARN, LOG_ID, "incomplete implementation");
		} else
			Log.println(Log.WARN, LOG_ID, "incomplete implementation");
	}

	/**
	 * Output VERBOSE information in log.
	 *
	 * @param throwable
	 * @param format
	 * @param args
	 */
	@SuppressWarnings("unused")
	public static void v(Throwable throwable, String format, Object... args) {
		if (Log.VERBOSE >= NoteConfig.MIN_LOG_LEVEL)
			try {
				log(Log.VERBOSE, String.format(format, args), throwable);
			} catch (Exception e) {
				Log.e(LOG_ID, "Failed to v: " + e.getMessage());
			}
	}

	/**
	 * Output VERBOSE information in log.
	 *
	 * @param format
	 * @param args
	 */
	public static void v(String format, Object... args) {
		v(null, format, args);
	}

	/**
	 * Output DEBUG information in log.
	 *
	 * @param throwable
	 * @param format
	 * @param args
	 */
	public static void d(Throwable throwable, String format, Object... args) {
		if (Log.DEBUG >= NoteConfig.MIN_LOG_LEVEL)
			try {
				if (args == null || args.length == 0)
					log(Log.DEBUG, format, throwable);
				else
					log(Log.DEBUG, String.format(format, args), throwable);
			} catch (Exception e) {
				Log.e(LOG_ID, "Failed to d: " + e.getMessage());
			}
	}

	/**
	 * Output DEBUG information in log.
	 *
	 * @param format
	 * @param args
	 */
	public static void d(String format, Object... args) {
		d(null, format, args);
	}

	/**
	 * Output INFO information in log.
	 *
	 * @param throwable
	 * @param format
	 * @param args
	 */
	public static void i(Throwable throwable, String format, Object... args) {
		if (Log.INFO >= NoteConfig.MIN_LOG_LEVEL)
			try {
				if (args == null || args.length == 0)
					log(Log.INFO, format, throwable);
				else
					log(Log.INFO, String.format(format, args), throwable);
			} catch (Exception e) {
				Log.e(LOG_ID, "Failed to i: " + e.getMessage());
			}
	}

	/**
	 * Output INFO information in log.
	 *
	 * @param format
	 * @param args
	 */
	public static void i(String format, Object... args) {
		i(null, format, args);
	}

	/**
	 * Output WARN information in log.
	 *
	 * @param throwable
	 * @param format
	 * @param args
	 */
	public static void w(Throwable throwable, String format, Object... args) {
		if (Log.WARN >= NoteConfig.MIN_LOG_LEVEL)
			try {
				if (args == null || args.length == 0)
					log(Log.WARN, format, throwable);
				else
					log(Log.WARN, String.format(format, args), throwable);
			} catch (Exception e) {
				Log.e(LOG_ID, "Failed to w: " + e.getMessage());
			}
	}

	/**
	 * Output WARN information in log.
	 *
	 * @param format
	 * @param args
	 */
	public static void w(String format, Object... args) {
		w(null, format, args);
	}

	/**
	 * Output ERROR information in log
	 *
	 * @param throwable
	 * @param format
	 * @param args
	 */
	public static void e(Throwable throwable, String format, Object... args) {
		if (Log.ERROR >= NoteConfig.MIN_LOG_LEVEL)
			try {
				String msg = format;
				if (args != null && args.length > 0)
					msg = String.format(format, args);

				log(Log.ERROR, msg, throwable);
				// if (NoteConfig.DEV_BUILD)
				// ViewUtils.showToast(throwable == null ? msg : msg + " : " +
				// throwable, Toast.LENGTH_LONG,
				// true);

			} catch (Exception e) {
				Log.e(LOG_ID, "Failed to e: " + e.getMessage());
			}
	}

	/**
	 * Output ERROR information in log.
	 *
	 * @param format
	 * @param args
	 */
	public static void e(String format, Object... args) {
		e(null, format, args);
	}

	/**
	 * Output the assertion that something is true in log.
	 *
	 * @param bool
	 */
	public static void assertTrue(boolean bool) {
		if (!bool)
			LogUtils.e("Assertion failed");
	}

	/**
	 * Out put WARN & DEV_BUILD information in log.
	 *
	 * @param throwable
	 * @param format
	 * @param args
	 */
	public static void dw(Throwable throwable, String format, Object... args) {
		if (DW)
			try {
				String msg = format;
				if (args != null && args.length > 0)
					msg = String.format(format, args);

				log(Log.WARN, msg, throwable);

				// if (NoteConfig.DEV_BUILD)
				// ViewUtils.showToast(throwable == null ? msg : msg + " : " +
				// throwable, Toast.LENGTH_LONG,
				// true);
			} catch (Exception e) {
				Log.e(LOG_ID, "Failed to w: " + e.getMessage()); //$NON-NLS-1$
			}
	}

	/**
	 * Out put WARN & DEV_BUILD information in log.
	 *
	 * @param format
	 * @param args
	 */
	public static void dw(String format, Object... args) {
		dw(null, format, args);
	}

	/**
	 * Output in log that a specific feature is not supported.
	 *
	 * @param feature
	 */
	public static void missedFeature(String feature) {
		e("%s is not supported in Social SDK", feature);
	}
}</span><span style="font-size:18px;">
</span>
3.SystemUtils

<span style="font-size:14px;">public class SystemUtils {

	public static String TELE_DEVICE_ID;
	public static String ANDROID_ID;
	public static String DEVICE_NAME;
	public static String VERSION_NAME;
	public static String WIFI_MAC;
	public static String PHONE_NUMBER;
	public static int WIDTH;
	public static int HEIGHT;
	public static float DENSITY;
	public static boolean EXTERNAL_STORAGE_WRITABLE = false;

	public static final int NETWORK_TYPE_NULL = 0;
	public static final int NETWORK_TYPE_WIFI = 1;
	public static final int NETWORK_TYPE_WAP = 2;
	public static final int NETWORK_TYPE_NET = 3;

	private SystemUtils() {
	}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public static void initialize(Context ctx) {
		try {
			TelephonyManager tm = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			TELE_DEVICE_ID = tm.getDeviceId();
			DEVICE_NAME = tm.getSubscriberId();
		} catch (Exception e) {
			LogUtils.d("Failed to get tele info: " + e);
		}

		try {
			ANDROID_ID = Settings.Secure.getString(ctx.getContentResolver(),
					Settings.Secure.ANDROID_ID);
		} catch (Exception e) {
			LogUtils.w(e, "Failed to get ANDROID_ID");
		}

		if (LangUtils.isEmpty(ANDROID_ID))
			ANDROID_ID = "emulator";

		if (DEVICE_NAME == null)
			DEVICE_NAME = "";

		VERSION_NAME = Build.VERSION.RELEASE;

		try {
			WindowManager wm = (WindowManager) ctx
					.getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();
			if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
				WIDTH = display.getWidth();
				HEIGHT = display.getHeight();
			} else {
				Point size = new Point();
				display.getSize(size);
				WIDTH = size.x;
				HEIGHT = size.y;
			}
			DisplayMetrics metric = new DisplayMetrics();
			display.getMetrics(metric);
			DENSITY = metric.densityDpi;
		} catch (Exception e) {
			LogUtils.e(e, "Failed to get display info");
		}

		try {
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				File tmp = new File(Environment.getExternalStorageDirectory(),
						"note_tmp");
				if (tmp.exists())
					tmp.delete();
				if (tmp.createNewFile()) {
					EXTERNAL_STORAGE_WRITABLE = true;
					tmp.delete();
				}
			}
		} catch (Exception e) {
			LogUtils.d("Failed to test external storage writable: " + e);
		}
		try {
			WifiManager wifi = (WifiManager) ctx
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			if (info.getMacAddress() != null) {
				WIFI_MAC = info.getMacAddress();
			} else {
				WIFI_MAC = "";
			}
		} catch (Exception e) {
			LogUtils.d("Failed to get WIFI MAC: " + e);
		}

		try {
			TelephonyManager tm = (TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE);
			if (tm.getLine1Number() != null) {
				PHONE_NUMBER = tm.getLine1Number();
			} else {
				PHONE_NUMBER = "";
			}
		} catch (Exception e) {
			LogUtils.d("Failed to get phone number: " + e);
		}

	}

	/**
	 * get the ID of android device
	 * 
	 * @param c
	 * @return
	 */
	public static String getDeviceID(Context c) {
		String duid = Settings.Secure.getString(c.getContentResolver(),
				Settings.Secure.ANDROID_ID);
		return LangUtils.isEmpty(duid) ? "emulator" : duid;
	}

	/**
	 * get version name
	 * 
	 * @param c
	 * @return
	 */
	public static String getVersionName(Context c) {
		if (c == null)
			c = NoteManager.getApplicationContext();
		if (c == null)
			Log.e(Constants.LOG_TAG, "made mistakes when getVersion name");
		PackageManager pm = c.getPackageManager();
		String versionName = "";
		try {
			PackageInfo info = pm.getPackageInfo(c.getPackageName(), 0);
			versionName = info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * get the type of network
	 * 
	 * @return
	 */
	public static int getNetWorkType() {
		Context con = NoteManager.getApplicationContext();
		ConnectivityManager conn = (ConnectivityManager) con
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conn == null)
			return NETWORK_TYPE_NULL;
		NetworkInfo info = conn.getActiveNetworkInfo();
		if (info == null)
			return NETWORK_TYPE_NULL;
		String type = info.getTypeName();
		if ("wifi".equals(type) || "WIFI".equals(type))
			return NETWORK_TYPE_WIFI;
		else if ("mobile".equals(type) || "MOBILE".equals(type)) {
			String apn = info.getExtraInfo();
			if (apn.contains("wap") && apn != null)
				return NETWORK_TYPE_WAP;
			else
				return NETWORK_TYPE_NET;
		}
		return NETWORK_TYPE_NULL;
	}
}</span>
4.ViewUtils
<span style="font-size:14px;">public class ViewUtils {

	private static BaseHandler mHandler;
	private static boolean initialized = false;
	private static WeakReference<Thread> thread_ref;

	private static Typeface lightTypeface, boldTypeface;

	private ViewUtils() {
	}

	public static void initialize() {
		if (!initialized) {
			mHandler = new BaseHandler();
			thread_ref = new WeakReference<Thread>(Thread.currentThread());
			lightTypeface = Typeface.DEFAULT;
			boldTypeface = Typeface.DEFAULT_BOLD;
			initialized = true;
		}
	}

	/**
	 * Get roboto-light typeface
	 */
	public static Typeface getLightTypeface() {
		return lightTypeface;
	}

	/**
	 * Get roboto-medium typeface
	 */
	public static Typeface getBoldTypeface() {
		return boldTypeface;
	}

	/**
	 * Post a command in handler thread.
	 * 
	 * @param r
	 */
	public static void post(Runnable r) {
		if (mHandler != null)
			mHandler.post(r);
	}

	/**
	 * run in main thread
	 * 
	 * @param r
	 */
	public static void runInMainThread(Runnable r) {
		if (mHandler != null)
			mHandler.runInMainThread(r);
	}

	public static void removeRunnable(Runnable r) {
		if (mHandler != null)
			mHandler.removeCallbacks(r);
	}

	/**
	 * judge if now in MainThreadd or not
	 * 
	 * @return
	 */
	public static boolean isInMainThread() {
		if (!initialized)
			return true;
		else if (thread_ref != null) {
			return thread_ref.get() == Thread.currentThread();
		}
		return false;
	}

	/**
	 * remove view from its parent
	 * 
	 * @param o
	 */
	private static void removeFromSuperView(Object o) {
		if (o == null)
			return;
		if (o instanceof View) {
			View view = (View) o;
			final ViewParent parent = ((View) o).getParent();
			if (parent == null)
				return;
			if (parent instanceof ViewGroup)
				((ViewGroup) parent).removeView(view);
			else
				Log.e(Constants.LOG_TAG, String.format(
						"the parent of view %s is not a viewgroup: %s", view,
						parent));
		} else if (o instanceof Dialog) {
			((Dialog) o).hide();
		}
	}

	/**
	 * add view to parent
	 * 
	 * @param parent
	 * @param view
	 */
	public static void addView(ViewGroup parent, View view) {
		addView(parent, view, false);
	}

	private static void addView(ViewGroup parent, View view, boolean force) {
		if (parent == null || view == null)
			return;
		try {
			if (view.getParent() == null) {
				parent.addView(view);
			}
			if (force) {
				if (view.getParent() != parent) {
					removeFromSuperView(view);
					parent.addView(view);
				}
			}
		} catch (Exception e) {
			Log.e(Constants.LOG_TAG,
					String.format(
							"Failed to addView, parent %s, view %s, force %b, layoutParams %s",
							parent, view, force, view.getLayoutParams()));
		}
	}

	/**
	 * convert dp to pixels
	 * 
	 * @param dp
	 * @return
	 */

	public static int dp2pix(float dp) {
		return dp2pix(NoteManager.getApplicationContext(), dp);
	}

	private static int dp2pix(Context c, float dp) {
		if (c == null) {
			c = NoteManager.getApplicationContext();
		}
		if (c == null) {
			Log.e(Constants.LOG_TAG, "context is null for dp2pix");
			return (int) dp;
		}
		return (int) (dp > 0 ? (c.getResources().getDisplayMetrics().density
				* dp + 0.5f) : dp);
	}

	/**
	 * convert drwable to bitmap
	 * 
	 * @param d
	 * @return
	 */
	public static Bitmap drawable2Bitmap(Drawable d) {
		int height = d.getIntrinsicHeight();
		int width = d.getIntrinsicWidth();
		Bitmap bitmap = null;
		try {
			bitmap = Bitmap.createBitmap(width, height,
					d.getOpacity() == PixelFormat.OPAQUE ? Config.ARGB_8888
							: Config.RGB_565);
			Canvas canvas = new Canvas(bitmap);
			d.setBounds(0, 0, width, height);
			d.draw(canvas);
		} catch (IllegalArgumentException e) {
			Log.e(Constants.LOG_TAG, String.format(
					"to bitmap error w = %d h = %d", width, height));
			return null;
		}
		return bitmap;
	}

	public static void showSoftKeyBoard(EditText et) {
		try {
			et.requestFocusFromTouch();
			((InputMethodManager) et.getContext().getSystemService(
					Context.INPUT_METHOD_SERVICE)).showSoftInput(et, 0);
		} catch (Exception e) {
			Log.e(Constants.LOG_TAG, "Failed to show soft keyboard");
		}
	}

	public static void hideSoftKeyboard(Activity activity) {
		InputMethodManager imm = (InputMethodManager) activity
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (null != imm && imm.isActive()) {
			View view = activity.getCurrentFocus();
			if (null != view) {
				imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T find(Activity a, int id) {
		return (T) a.findViewById(id);
	}

	@SuppressWarnings("unchecked")
	public static <T> T find(View v, int id) {
		return (T) v.findViewById(id);
	}

	/**
	 * every Parent View can set only one time
	 * 
	 * @param view
	 */
	public static void extendTouchArea(final View view) {
		if (view == null)
			return;
		View parent = (View) view.getParent();
		parent.post(new Runnable() {

			@Override
			public void run() {
				Rect delegete = new Rect();
				view.getHitRect(delegete);
				delegete.bottom += 50;
				delegete.top -= 50;
				delegete.left -= 100;
				delegete.right += 100;
				TouchDelegate t = new TouchDelegate(delegete, view);
				if (View.class.isInstance(view.getParent())) {
					((View) view.getParent()).setTouchDelegate(t);
				}
			}
		});
	}

	/**
	 * get color
	 * 
	 * @param r
	 * @param g
	 * @param b
	 * @return
	 */
	public static int int2Color(int r, int g, int b) {
		int R = Math.round(255 * r);
		int G = Math.round(255 * g);
		int B = Math.round(255 * b);

		R = (R << 16) & 0x00FF0000;
		G = (G << 8) & 0x0000FF00;
		B = B & 0x000000FF;

		return 0xFF000000 | R | G | B;
	}

	/**
	 * get picture by string
	 * 
	 * @param s
	 * @return
	 */
	public static Drawable getDrawableByString(String s) {
		Context ctx = NoteManager.getApplicationContext();
		Resources res = ctx.getResources();
		int resID = res.getIdentifier(s, "drawable", ctx.getPackageName());
		try {
			return ctx.getResources().getDrawable(resID);
		} catch (NotFoundException e) {
			return null;
		}
	}
}
</span>
5.WebUtils
<span style="font-size:14px;">public class WebUtils {
	private WebUtils() {
	}

	public static boolean isNetWorkConnected(Context context) {
		if (context != null) {
			@SuppressWarnings("static-access")
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (networkInfo != null)
				return networkInfo.isAvailable();
		}
		return false;
	}

	/**
	 * parse String to JSONObject
	 * 
	 * @param str
	 * @return
	 */
	public static JSONObject parseJsonObject(String json) {
		if (isEmpty(json)) {
			return null;
		}
		try {
			return new JSONObject(json);
		} catch (Exception e) {
			w(e, "Failed to parseJsonObject, %s", json);
			return null;
		}
	}

	/**
	 * parse String to JSONArray
	 * 
	 * @param str
	 * @return
	 */
	public static JSONArray parseJsonArray(String json) {
		if (isEmpty(json)) {
			return null;
		}
		try {
			return new JSONArray(json);
		} catch (JSONException e) {
			w(e, "Failed to parseJsonArray, %s", json);
			return null;
		}
	}

	public static ArrayList<?> jsonToArrayString(JSONArray array) {

		try {
			ArrayList<Object> ret = new ArrayList<Object>(array.length());
			for (int i = 0; i < array.length(); i++) {
				Object v = array.get(i);
				if (v instanceof JSONArray) {
					v = jsonToArrayString((JSONArray) v);
				} else if (v instanceof JSONObject) {
					v = jsonToMap((JSONObject) v);
				}
				ret.add(v);
			}

			return ret;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Get Boolean from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @return Boolean
	 */
	public static Boolean getJsonBoolean(JSONObject json, String key) {
		return getJsonBoolean(json, key, false);
	}

	/**
	 * Get Boolean from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @param defaultValue
	 * @return Boolean
	 */
	public static Boolean getJsonBoolean(JSONObject json, String key,
			Boolean defaultValue) {
		if (json == null)
			return defaultValue;
		try {
			if (json.has(key)) {
				Boolean value = json.getBoolean(key);
				return value == null ? defaultValue : value;
			}
		} catch (JSONException e) {
			e(e, "Failed to getJsonBoolean %s", key);
		}

		return defaultValue;
	}

	/**
	 * Get String from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @return String
	 */

	public static String getJsonString(JSONObject json, String key) {
		return getJsonString(json, key, null);
	}

	/**
	 * Get String from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @param defaultValue
	 * @return String
	 */

	public static String getJsonString(JSONObject json, String key,
			String defaultValue) {
		if (json == null)
			return defaultValue;
		try {
			if (json.has(key)) {
				String value = json.getString(key);
				return value == null ? defaultValue : value;
			}
		} catch (JSONException e) {
			e(e, "Failed to getJsonString %s", key);
		}

		return defaultValue;
	}

	/**
	 * Get int from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @return int
	 */
	public static int getJsonInt(JSONObject json, String key) {
		return getJsonInt(json, key, -1);
	}

	/**
	 * Get int from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @param defaultValue
	 * @return int
	 */
	public static int getJsonInt(JSONObject json, String key, int defaultValue) {
		if (json == null)
			return defaultValue;
		if (json.has(key)) {
			try {
				int value = json.getInt(key);
				return value;
			} catch (JSONException e) {
				e(e, "Failed to getJsonInt %s", key);
			}
		}

		return defaultValue;
	}

	/**
	 * get float from json
	 * 
	 * @param json
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static double getJsonDouble(JSONObject json, String key,
			double defaultValue) {
		if (json == null)
			return defaultValue;
		if (json.has(key)) {
			try {
				double value = json.getDouble(key);
				return value;
			} catch (JSONException e) {
				e(e, "Failed to getJsonInt %s", key);
			}
		}

		return defaultValue;
	}

	/**
	 * 
	 * @param json
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static double getJsonFloat(JSONObject json, String key,
			float defaultValue) {
		if (json == null)
			return defaultValue;
		if (json.has(key)) {
			try {
				double value = json.getDouble(key);
				return value;
			} catch (JSONException e) {
				e(e, "Failed to getJsonInt %s", key);
			}
		}

		return defaultValue;
	}

	/**
	 * Get int from a JSON object.
	 * 
	 * @param json
	 * @param key
	 * @param defaultValue
	 * @return int
	 */
	public static long getJsonLong(JSONObject json, String key,
			Long defaultValue) {
		if (json == null)
			return defaultValue;
		if (json.has(key)) {
			try {
				long value = json.getLong(key);
				return value;
			} catch (JSONException e) {
				e(e, "Failed to getJsonInt %s", key);
			}
		}

		return defaultValue;
	}

	/**
	 * get String from a JSONArray
	 * 
	 * @param array
	 * @param index
	 * @return
	 */
	public static String getJsonString(JSONArray array, int index) {
		return getJsonString(array, index, null);
	}

	public static String getJsonString(JSONArray array, int index,
			String defaultValue) {
		if (array == null)
			return defaultValue;
		try {
			return array.getString(index);
		} catch (JSONException e) {
			e(e, "Failed to getJsonString %d, %d", array.length(), index);
		}
		return defaultValue;
	}

	/**
	 * Get int from a JSONArray.
	 * 
	 * @param array
	 * @param index
	 * @return int
	 */
	public static int getJsonInt(JSONArray array, int index) {
		return getJsonInt(array, index, -1);
	}

	/**
	 * Get int from a JSONArray.
	 * 
	 * @param array
	 * @param index
	 * @param defaultValue
	 * @return int
	 */
	public static int getJsonInt(JSONArray array, int index, int defaultValue) {
		if (array == null)
			return defaultValue;
		try {
			return array.getInt(index);
		} catch (JSONException e) {
			e(e, "Failed to get JsonInt %d, %d", array.length(), index);
		}

		return defaultValue;
	}

	/**
	 * Get long from a JSONArray.
	 * 
	 * @param array
	 * @param index
	 * @param defaultValue
	 * @return long
	 */
	public static long getJsonLong(JSONArray array, int index, long defaultValue) {
		if (array == null)
			return defaultValue;
		try {
			return array.getLong(index);
		} catch (JSONException e) {
			e(e, "Failed to get JsonInt %d, %d", array.length(), index);
		}

		return defaultValue;
	}

}
</span>

以上工具类已经可以满足大多数android应用了,一般来说工具类中的每一个方法都需要深入研究一下,光会用肯定是不行的,你得了解其中的每个方法原理是怎么样的,在工作中不要总问别人或者百度找论坛解决,你得学着“Read the fucking source code”,不会阅读源码,就很难接近真相。
下次博客会挑取其中的某个知识点分析下,大家如果有什么见解或疑惑,欢迎留言,谢谢。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值