Tech Notes

Convert a Database Cursor to a JSON Array — Android App Development

Java code that converts an Android SQLite cursor into a JSON array, handy for PhoneGap plugins that run raw queries.

This is a great book for learning Android Java programming with little or no programming experience. I recommend it if you’re new to Android development. Buy it on Amazon

This is useful when you build database applications with PhoneGap. PhoneGap’s storage API can sometimes be slow and difficult to work with, so you may prefer to write a separate plugin to run the queries. When you run raw database queries, you get the results back as a Cursor. The code below converts a cursor into a JSON array.

public JSONArray getResults() {
		String myPath = DB_PATH + DB_NAME;// Set path to your database
		SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

		String searchQuery = "SELECT  * FROM ";
		Cursor cursor = myDataBase.rawQuery(searchQuery, null);

		JSONArray resultSet = new JSONArray();
		JSONObject returnObj = new JSONObject();

		cursor.moveToFirst();
		while (cursor.isAfterLast() == false) {

			int totalColumn = cursor.getColumnCount();
			JSONObject rowObject = new JSONObject();

			for (int i = 0; i < totalColumn; i++) {
				if (cursor.getColumnName(i) != null) {

					try {

						if (cursor.getString(i) != null) {
							Log.d("TAG_NAME", cursor.getString(i));
							rowObject.put(cursor.getColumnName(i), cursor.getString(i));
						} else {
							rowObject.put(cursor.getColumnName(i), "");
						}
					} catch (Exception e) {
						Log.d("TAG_NAME", e.getMessage());
					}
				}

			}

			resultSet.put(rowObject);
			cursor.moveToNext();
		}

		cursor.close();
		Log.d("TAG_NAME", resultSet.toString());
		return resultSet;
	}

View this code on GitHub