The problem with ACRA

2013/07/03

ACRA is a popular, open-source crash report framework for Android. It however has a fundamental flaw: it is quite likely to cause an ANR when reporting a crash. Here is why …

In a nutshell, ACRA adds an uncaught exception handler, and in the handler starts a thread to do the work of sending the report and return normally from the custom uncaught exception handler method. The work done by the send thread can be arbitrary (it’s a plugin interface), but it will typically send the report to a server somewhere. When the thread is done, it either calls the default uncaught exception handler or calls System.exit(), depending on its configuration.

The problem is what happens when you return from the uncaught exception handler method without either calling the uncaught exception handler, or calling System.exit(). Try it yourself,

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                ex.printStackTrace();
                // don't call default uncaught exception handler
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        throw new AssertionError("hello, assertion.");
    }
}

When run, this causes an ANR. If ACRA’s send thread takes longer than the ANR timeout (~5 seconds), then it too will cause an ANR for the same reason. Since the send thread is typically performing network operations, it is quite common for it to block for longer periods of time. If the use clicks “wait” on the ANR dialog, the app process is killed and the report it not immediately send. This is not a problem, since ACRA won’t delete it’s file cached copy of the crash report until the send thread responds that it successfully sent the report.

This is not all terribly bad. The user will see an ANR dialog in stead of a force close dialog. The report will be sent at a later time, probably the next time the app is started by the user. It could however be fixed. ACRA shouldn’t even try to send the crash report when it’s crashing. It should simply write the cache copy to the file system, on the main thread, and then allow the app to exit normally. It can send the report during normal app operation the next time it is started.

As a side note, ACRA’s “silent mode” should be avoided. This causes ACRA to not call the default Android uncaught exception handler and simply kill the process and call System.exit() (which is redundant, but anyway). However, it skips the logic in the default Android uncaught exception handler. This includes calling out to Google’s crash report service. It also hides the force close dialog which is confusing to the user.


2013/01/18

As many people have noted, my Android application alogcat does not work correctly on Jellybean devices. The reason is that applications can no longer read log entries created by other applications. They can still read log entries created by themselves, but obviously that doesn’t help alogcat.

The logic makes sense I suppose. A poorly written application may log sensitive information. Allowing other applications to read this is a bad thing.

For alogcat, there is a workaround. You must explicitly grant alogcat the READ_LOGS permission from the command line. From the Android shell,

shell@android:/ $ pm grant org.jtb.alogcat android.permission.READ_LOGS    

Or if you have ADB installed, from your computer’s terminal with your device connected,

$ adb shell pm grant org.jtb.alogcat android.permission.READ_LOGS    

This of course requires that you install an Android terminal emulator, or have ADB installed on your computer. Android Terminal Emulator is a good choice for an Android terminal. The Android SDK, which includes ADB can be downloaded here.


Reflective toString()

2013/01/15

Tired of writing toString() on all your classes? Annoyed when your co-workers forget to do so? Here’s a simple solution that uses reflection to implement toString().

Find two source files. ToString.java is a helper class for implementing toString(). It’s a revision of the Google Guava’s ToStringHelper.

public class ToString {
	private final List<ValueHolder> valueHolders = new LinkedList<ValueHolder>();
	private boolean omitNullValues = false;

	protected final Object obj;

	public ToString(Object obj) {
		this.obj = obj;
	}

	public ToString add(String name, Object value) {
		addHolder(value).builder.append(name).append('=').append(value);
		return this;
	}

	public ToString add(String name, boolean value) {
		checkNameAndAppend(name).append(value);
		return this;
	}

	public ToString add(String name, char value) {
		checkNameAndAppend(name).append(value);
		return this;
	}

	public ToString add(String name, double value) {
		checkNameAndAppend(name).append(value);
		return this;
	}

	public ToString add(String name, float value) {
		checkNameAndAppend(name).append(value);
		return this;
	}

	public ToString add(String name, int value) {
		checkNameAndAppend(name).append(value);
		return this;
	}

	public ToString add(String name, long value) {
		checkNameAndAppend(name).append(value);
		return this;
	}

	private StringBuilder checkNameAndAppend(String name) {
		return addHolder().builder.append(name).append('=');
	}

	@Override
	public String toString() {
		// create a copy to keep it consistent in case value changes
		boolean omitNullValuesSnapshot = omitNullValues;
		boolean needsSeparator = false;
		StringBuilder builder = new StringBuilder(32).append(
				obj.getClass().getSimpleName()).append('{');
		for (ValueHolder valueHolder : valueHolders) {
			if (!omitNullValuesSnapshot || !valueHolder.isNull) {
				if (needsSeparator) {
					builder.append(", ");
				} else {
					needsSeparator = true;
				}
				CharSequence sequence = valueHolder.builder;
				builder.append(sequence);
			}
		}
		return builder.append('}').toString();
	}

	private ValueHolder addHolder() {
		ValueHolder valueHolder = new ValueHolder();
		valueHolders.add(valueHolder);
		return valueHolder;
	}

	private ValueHolder addHolder(Object value) {
		ValueHolder valueHolder = addHolder();
		valueHolder.isNull = (value == null);
		return valueHolder;
	}

	private static final class ValueHolder {
		final StringBuilder builder = new StringBuilder();
		boolean isNull;
	}
}

ReflectiveToString.java extends the former, and re-implements toString() to automatically add all (most) fields.

public class ReflectiveToString extends ToString {
	private static final Pattern[] IGNORE_FIELD_PATTERNS = new Pattern[] {
			Pattern.compile("^this\\$\\d+$"),
			Pattern.compile("^serialVersionUID$") };

	public ReflectiveToString(Object obj) {
		super(obj);
	}

	@Override
	public String toString() {
		Set<Field> fields = getFields();
		fields: for (Field f : fields) {
			String fn = f.getName();
			for (Pattern p : IGNORE_FIELD_PATTERNS) {
				Matcher m = p.matcher(fn);
				if (m.matches()) {
					continue fields;
				}
			}

			f.setAccessible(true);
			try {
				add(fn, f.get(obj));
			} catch (IllegalArgumentException e) {
				// silently skip, should never happen
			} catch (IllegalAccessException e) {
				// silently skip, should never happen
			}
		}

		return super.toString();
	}

	private Set<Field> getFields() {
		Set<Field> fields = new HashSet<Field>();
		getFields(obj.getClass(), fields);

		return fields;
	}

	private static void getFields(Class<? extends Object> cls, Set<Field> fields) {
		Class<? extends Object> superclass = cls.getSuperclass();
		if (superclass != null) {
			getFields(superclass, fields);
		}
		fields.addAll(Arrays.asList(cls.getDeclaredFields()));
	}
}

To use it, implement toString() on your classes like this,

@Override
public String toString() {
    return new ReflectiveToString(this).toString();
}

You could of course extend Guava’s ToStringHelper directly. I didn’t want to pull in the entire library however.

Of course the string output can be tuned by modifying ToString.java.


Android Log Message Truncation

2012/09/08

Frustrated by Android’s inability to log messages over 4k? In my case, I had some heft SOAP messages that were getting cut off. The simple solution is to use System.out.println(), but that always logs at the info level. Here’s something neater,

    void v(String msg) {
      println(Log.VERBOSE, msg);
    }

    void d(String msg) { ... }
    void i(String msg) { ... }
    void w(String msg) { ... }
    void e(String msg) { ... }

    private int println(int priority, String msg) {
        int l = msg.length();
        int c = Log.println(priority, TAG, msg);
        if (c < l) {
            return c + println(priority, TAG, msg.substring(c+1));
        } else {
            return c;
        }
    }

In short, take advantage of the fact that the low-level Log.println() call returns the number of bytes written. Use that fact to recursively call ourselves until we log all of the message.


Spiral Order, Java

2012/03/19

This is a problem I’ve heard mentioned but never really had a reason to look into. As they say, the science is gone from computer science. I sat down today and put some thought into it.

Spiral order is what you’d think. Given a 2D array, you move from left to right, top to bottom, right to left, and bottom to top printing out the values in order. For example,

  1  2  3  4
  5  6  7  8
  9 10 11 12
 13 14 15 16

The spiral order of this matrix is,

{  1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 }

The algorithm to walk in spiral order works nicely with recursion. You recursively, “peel” off the top, right, bottom, left portions of the matrix until there’s nothing left. For example (forgive the ASCII art), peel off the top,

  1 2 3 4

  5  6  7  8
  9 10 11 12
 13 14 15 16

peel off the right,

  5  6  7     8
  9 10 11    12
 13 14 15    16

peel off the bottom,

  5  6  7
  9 10 11 

 13 14 15

peel off the left,

 5     6  7
 9    10 11

peel off the top (again, starting over here),

 6 7

 10 11

peel the right again,

 10    11

and finally, one more peel of the bottom gets the last element,

 10

and we are done.

The code is below. spiralOrderR() implements the recursive algorithm. It calls peelTop(), which calls peelLeft(), which calls peelBottom(),which calls peelLeft(), and so on, until it’s done.  The peeling happens in the arguments to the recursive call, where the bounds of the matrix are reduced as appropriate at each pass.

public class SpiralOrder {
	public static <T> List<T> spiralOrderR(T[][] matrix) {
		int startx = 0;
		int starty = 0;
		int endx = matrix.length - 1;
		int endy = matrix.length - 1;

		List<T> spiral = new ArrayList<T>();

		peelTopRight(matrix, startx, endx, starty, endy, spiral);
		return spiral;
	}

	private static <T> void peelTop(T[][] matrix, int startx, int endx, int starty, int endy, List<T> spiral) {
		if (startx > matrix.length / 2) {
			return;
		}
		for (int i = startx; i <= endx; i++) {
			spiral.add(matrix[i][starty]);
		}
		peelRight(matrix, startx, endx, starty+1, endy, spiral);
	}

	private static <T> void peelRight(T[][] matrix, int startx, int endx, int starty, int endy, List<T> spiral) {
		for (int i = starty; i <= endy; i++) {
			spiral.add(matrix[endx][i]);
		}
		peelBottom(matrix, startx, endx-1, starty, endy, spiral);
	}

	private static <T> void peelBottom(T[][] matrix, int startx, int endx, int starty, int endy, List<T> spiral) {
		for (int i = endx; i >= startx; i--) {
			spiral.add(matrix[i][endy]);
		}
		peelLeft(matrix, startx, endx, starty, endy-1, spiral);
	}

	private static <T> void peelLeft(T[][] matrix, int startx, int endx, int starty, int endy, List<T> spiral) {
		for (int i = endy; i >= starty; i--) {
			spiral.add(matrix[startx][i]);
		}
		peelTop(matrix, startx+1, endx, starty, endy, spiral);
	}

	public static void main(String[] args) {
		Integer[][] ints = new Integer[5][5];
		int count = 1;
		for (int i = 0; i < ints.length; i++) {
			for (int j = 0; j < ints[i].length; j++) {
				ints[j][i] = count++;
			}
		}

		List<Integer> spiral = spiralOrder(ints);
		System.out.println(spiral);
		spiral = spiralOrderR(ints);
		System.out.println(spiral);
	}
}

Android Advanced Logger

2012/03/08

The Android Log utility class is simple enough and does the job, but there are a few nagging problems I’ve found with it.

No context. There is no supplied as to what triggered the log statement. This leads to log records like,

D/MyApp: Something happened ...

Great, but happened where? What class? Which method? For small apps with a single developer this isn’t a problem, but for larger projects where the person that’s doing the debugging did not write the code … By convention, developers can add contextual information into the log statements but this requires everyone to remember to do this, consistently. Can’t the log utility do it for us?

Tag inconsistencies. Some apps use different tags for each class, others use the same tag across the entire app. The former makes it impossible to tell which log statements came from the same app, unless you keep a mapping from tab to class to app around. That’s why I prefer the latter. However, now we are forced to pass the exact same argument (TAG) into every log statement. Can the logging framework insert it for us?

Level. The Android logger does not allow me to change the level, only filter the log output by level via logcat arguments. What if i simply want to avoid logging things at particular levels?

Argument evaluation. A common logging anti-pattern,

Log.i("here's the object: " + myObj);

This is problematic because regardless of the level, regardless whether the statement will actually get into the log, myObj.toString() is called and a new String object that is the concatenation of “here’s the object: ” and myObj.toString() is created. Over a large app with many log statements, this can significantly hamper performance. Commonly, the antidote is something like,

if (LOG_LEVEL == Level.INFO) {
    Log.i("here's the object: " + myObj);
}

But this really crufts up the code. Can we avoid this sort of check?

Small log window. The Android log buffer is about 50k. On a device with a good number of apps installed, the entire log window can scroll in a matter of minutes. This makes it impossible to go back and examine the log for specific events.

To solve these problems, I created a simple utility class, ALog (advanced log).

To add context, it automatically appends the class and method name, and line number to the beginning of every statement. The result is clear, contextual log statements like this,

W/my-app(23659): InstallManager.<init>@120: failed to make APK dir: /mnt/sdcard/Download

ALog avoids evaluating arguments by accepting a log pattern plus arguments,

ALog.w("oh noes, a problem occured when i %s and then also at %s", msg1, msg2);

The first argument, the format, must conform to the interface dedefined by String.format().

ALog support setting a global tag for the entire app, and setting the level. Do so in your application class,

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        ALog.setTag("MyApp");
        ALog.setLevel(CLog.Level.D);
    }
}
ALog optionally writes every log record to a file on your SD card, to keep a nearly infinite log of exactly what happened in your app. Just enable file logging like,
ALog.setFileLogging(true);
Files are created at: <Environment.getExternalStorageDirectory()>/alog/<tag>.log
Note that this is extremely inefficient. It should only be used temporarily to find bugs then disabled. It should never be used in production. You can look at the code below, but it starts a thread that take()’s from a blocking queue. Logging a message offers()’s into this queue. The file is opened, appended, and closed at each log statement; it does not keep the file open.
Here’s the source,
public class ALog {
	private static class LogContext {
		LogContext(StackTraceElement element) {
			// this.className = element.getClassName();
			this.simpleClassName = getSimpleClassName(element.getClassName());
			this.methodName = element.getMethodName();
			this.lineNumber = element.getLineNumber();
		}

		// String className;
		String simpleClassName;
		String methodName;
		int lineNumber;
	}

	public enum Level {
		V(1), D(2), I(3), W(4), E(5);

		private int value;

		private Level(int value) {
			this.value = value;
		}

		int getValue() {
			return value;
		}
	};

	private static final DateFormat FLOG_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");
	private static final File LOG_DIR = new File(
			Environment.getExternalStorageDirectory() + File.separator + "alog");
	private static boolean fileLogging = false;
	private static String tag = "<tag unset>";
	private static Level level = Level.V;
	private static final BlockingQueue<String> logQueue = new LinkedBlockingQueue<String>();
	private static Runnable queueRunner = new Runnable() {
		@Override
		public void run() {
			String line;
			try {
				while ((line = logQueue.take()) != null) {

					if (!Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						continue;
					}
					if (!LOG_DIR.exists() && !LOG_DIR.mkdirs()) {
						continue;
					}

					File logFile = new File(LOG_DIR, tag + ".log");
					Writer w = null;
					try {
						w = new FileWriter(logFile, true);
						w.write(line);
						w.close();
					} catch (IOException e) {
					} finally {
						if (w != null) {
							try {
								w.close();
							} catch (IOException e1) {
							}
						}
					}
				}
			} catch (InterruptedException e) {
			}
		}
	};

	static {
		new Thread(queueRunner).start();
	}

	private static LogContext getContext() {
		StackTraceElement[] trace = Thread.currentThread().getStackTrace();
		StackTraceElement element = trace[5]; // frame below us; the caller
		LogContext context = new LogContext(element);
		return context;
	}

	private static final String getMessage(String s, Object... args) {
		s = String.format(s, args);
		LogContext c = getContext();
		String msg = c.simpleClassName + "." + c.methodName + "@"
				+ c.lineNumber + ": " + s;
		return msg;
	}

	private static String getSimpleClassName(String className) {
		int i = className.lastIndexOf(".");
		if (i == -1) {
			return className;
		}
		return className.substring(i + 1);
	}

	public static void setLevel(Level l) {
		level = l;
	}

	public static void setTag(String t) {
		tag = t;
	}

	public static void setFileLogging(boolean enable) {
		fileLogging = enable;
	}

	public static void v(String format, Object... args) {
		if (level.getValue() > Level.V.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.v(tag, msg);
		if (fileLogging) {
			flog(Level.V, msg);
		}
	}

	public static void d(String format, Object... args) {
		if (level.getValue() > Level.D.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.d(tag, msg);
		if (fileLogging) {
			flog(Level.D, msg);
		}
	}

	public static void i(String format, Object... args) {
		if (level.getValue() > Level.I.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.i(tag, msg);
		if (fileLogging) {
			flog(Level.I, msg);
		}
	}

	public static void w(String format, Object... args) {
		if (level.getValue() > Level.W.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.w(tag, msg);
		if (fileLogging) {
			flog(Level.W, msg);
		}
	}

	public static void w(String format, Throwable t, Object... args) {
		if (level.getValue() > Level.W.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.w(tag, msg, t);
		if (fileLogging) {
			flog(Level.W, msg, t);
		}
	}

	public static void e(String format, Object... args) {
		if (level.getValue() > Level.E.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.e(tag, msg);
		if (fileLogging) {
			flog(Level.E, msg);
		}
	}

	public static void e(String format, Throwable t, Object... args) {
		if (level.getValue() > Level.E.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.e(tag, msg, t);
		if (fileLogging) {
			flog(Level.E, msg, t);
		}
	}

	public static void trace() {
		try {
			throw new Throwable("dumping stack trace ...");
		} catch (Throwable t) {
			ALog.e("trace:", t);
		}
	}

	public static String getStackTraceString(Throwable tr) {
		if (tr == null) {
			return "";
		}

		Throwable t = tr;
		while (t != null) {
			if (t instanceof UnknownHostException) {
				return "";
			}
			t = t.getCause();
		}

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		tr.printStackTrace(pw);
		return sw.toString();
	}

	private static void flog(Level l, String msg) {
		flog(l, msg, null);
	}

	private static void flog(Level l, String msg, Throwable t) {
		String timeString = FLOG_FORMAT.format(new Date());
		String line = timeString + " " + l.toString() + "/" + tag + ": " + msg
				+ "\n";
		if (t != null) {
			line += getStackTraceString(t) + "\n";
		}
		logQueue.offer(line);
	}
}

JSON Flattener

2012/01/21

I recently ran into the problem of needing to store a JSON object in a key, value store. I pasted a little utility class that does the job below. Here’s an example run against some nasty JSON,

ORIGINAL:

{ string: 'aString', integer: -1, nested: { x: 1, y: 2, z: 3}, moreNested: { a: [1,2,3], b: [4,5,6], c: [7,8,9]}, arrayFromHell: [{ innerArray: [{ innerInnerArray: [1,2,3]}]}]}

ENCODED:

{"arrayFromHell.0.innerArray.0.innerInnerArray.0":1,"arrayFromHell.0.innerArray.0.innerInnerArray.1":2,"arrayFromHell.0.innerArray.0.innerInnerArray.2":3,"nested.z":3,"nested.y":2,"nested.x":1,"integer":-1,"string":"aString","moreNested.b.0":4,"moreNested.b.1":5,"moreNested.b.2":6,"moreNested.c.0":7,"moreNested.c.1":8,"moreNested.c.2":9,"moreNested.a.0":1,"moreNested.a.1":2,"moreNested.a.2":3}

DECODED:

{"nested":{"z":3,"y":2,"x":1},"arrayFromHell":[{"innerArray":[{"innerInnerArray":[1,2,3]}]}],"integer":-1,"string":"aString","moreNested":{"b":[4,5,6],"c":[7,8,9],"a":[1,2,3]}}

As you can see, it simply looks at every leaf value (string, int) and derives the key path and stores the value there. For example,

{ x: { y: { z: 1 } } }

becomes,

{ x.y.z: 1 }

Arrays are a special case. Each value in an array becomes the path so far to the array appended with the array index. For example,

{ anArray: [1,2,3] }

becomes,

{ anArray.0: 1, anArray.1: 2, anArray.2: 3 }
Of course this isn’t foolproof. If you have dots in your key names, it will break. If you use numbers as keys, it will break as it makes an assumption that a numbered key path element indicates an array. Here’s the source.
package org.test.flatjson;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonFlattener {
	public static String encode(JSONObject jo) throws JSONException {
		String s = "{" + encode(null, jo) + "}";
		return s;

	}

	public static String encode(String json) throws JSONException {
		JSONObject jo = new JSONObject(json);
		return encode(jo);
	}

	private static String encode(String parent, Object val)
			throws JSONException {
		StringBuilder sb = new StringBuilder();
		if (val instanceof JSONObject) {
			JSONObject jo = (JSONObject) val;
			for (Iterator<String> i = jo.keys(); i.hasNext();) {
				String key = i.next();
				String hkey = (parent == null) ? key : parent + "." + key;
				Object jval = jo.get(key);
				String json = encode(hkey, jval);
				sb.append(json);
				if (i.hasNext()) {
					sb.append(",");
				}
			}
		} else if (val instanceof JSONArray) {
			JSONArray ja = (JSONArray) val;
			for (int i = 0; i < ja.length(); i++) {
				String hkey = (parent == null) ? "" + i : parent + "." + i;
				Object aval = ja.get(i);
				String json = encode(hkey, aval);
				sb.append(json);
				if (i < ja.length() - 1) {
					sb.append(",");
				}
			}
		} else if (val instanceof String) {
			sb.append("\"").append(parent).append("\"").append(":");
			String s = (String) val;
			sb.append(JSONObject.quote(s));
		} else if (val instanceof Integer) {
			sb.append("\"").append(parent).append("\"").append(":");
			Integer integer = (Integer) val;
			sb.append(integer);
		}

		return sb.toString();
	}

	public static String decode(String flatJson) throws JSONException {
		JSONObject encoded = new JSONObject(flatJson);
		return decodeToString(encoded);
	}

	public static String decodeToString(JSONObject encoded)
			throws JSONException {
		return decodeToObject(encoded).toString();
	}

	public static JSONObject decodeToObject(JSONObject encoded)
			throws JSONException {
		JSONObject decoded = new JSONObject();

		for (Iterator<String> i = encoded.keys(); i.hasNext();) {
			String hkey = i.next();
			String[] keys = hkey.split("\\.");

			Object json = decoded;

			for (int j = 0; j < keys.length; j++) {
				if (j == keys.length - 1) {
					Object val = encoded.get(hkey);
					if (json instanceof JSONObject) {
						JSONObject jo = (JSONObject)json;
						jo.put(keys[j], val);
					} else if (json instanceof JSONArray) {
						JSONArray ja = (JSONArray)json;
						int index = Integer.parseInt(keys[j]);
						ja.put(index, val);
					}
				} else {
					// we're NOT at a leaf key

					if (!isNumber(keys[j + 1])) {
						// next index is an object

						JSONObject joChild;

						if (json instanceof JSONObject) {
							// last index was an object
							// we're creating an object in an object
							JSONObject jo = (JSONObject)json;
							if (jo.has(keys[j])) {
								joChild = jo.getJSONObject(keys[j]);
							} else {
								joChild = new JSONObject();
								jo.put(keys[j], joChild);
							}
						} else if (json instanceof JSONArray) {
							// last index was an array
							// we're creating an object in an array
							JSONArray ja = (JSONArray)json;
							int index = Integer.parseInt(keys[j]);
							if (!ja.isNull(index)) {
								joChild = ja.getJSONObject(index);
							} else {
								joChild = new JSONObject();
								ja.put(index, joChild);
							}
						} else {
							throw new AssertionError("unhandled object type");
						}
						json = joChild;
					} else {
						// next index is an array element

						JSONArray jaChild;

						if (json instanceof JSONObject) {
							// last index was an object,
							// we're creating an array in an object
							JSONObject jo = (JSONObject)json;
							if (jo.has(keys[j])) {
								jaChild = jo.getJSONArray(keys[j]);
							} else {
								jaChild = new JSONArray();
								jo.put(keys[j], jaChild);
							}
						} else if (json instanceof JSONArray) {
							// last index was an array
							// we're creating an array in an array
							JSONArray ja = (JSONArray)json;
							int index = Integer.parseInt(keys[j + 1]);
							if (!ja.isNull(index)) {
								jaChild = ja.getJSONArray(index);
							} else {
								jaChild = new JSONArray();
								ja.put(index, jaChild);
							}
						} else {
							throw new AssertionError("unhandled object type");
						}
						json = jaChild;
					}
				}
			}
		}
		return decoded;
	}

	private static boolean isNumber(String s) {
		try {
			Integer.parseInt(s);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}

	}
}

Follow

Get every new post delivered to your Inbox.