java – Please tell me how can I add data from JSON to SQLite?

Question:

public class MainActivity extends ListActivity implements LocationListener {
// JSON Node names

private static final String TAG_POINTS = "Points";
private static final String TAG_NAME = "name";
private static final String TAG_ADRESS = "adress";
private static final String TAG_PARTNER_NAME = "partner_name";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
private static final String TAG_DISTANCE = "distance";
private static final String TAG_IMAGE = "image";
private static String url = "http://80.78.46.241:48090/ConditionallyConstantInformation/SnapshotDatabase/Points.JSON";
long startTime = System.nanoTime();
LocationManager locationManager;
Location location;
String provider;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new GetPoints().execute();

    SQLiteDatabase database = openOrCreateDatabase("DB", MODE_PRIVATE, null);


    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Criteria c = new Criteria();
    provider = locationManager.getBestProvider(c, false);
    location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
    }
}


@Override
public void onLocationChanged(Location location) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

public ArrayList<HashMap<String, String>> ParseJSON(String json) {
    if (json != null) try {

        Location startLocation = new Location("startLocation");
        double lng = location.getLongitude();
        double lat = location.getLatitude();

        startLocation.setLatitude(lat);
        startLocation.setLongitude(lng);


        ArrayList<HashMap<String, String>> PointsList = new ArrayList<HashMap<String, String>>();
        JSONObject jsonObj = new JSONObject(json);


        // Getting JSON Array node
        JSONArray Points = jsonObj.getJSONArray(TAG_POINTS);

        for (int i = 0; i < Points.length(); i++) {
            JSONObject c = Points.getJSONObject(i);

            String name = c.getString(TAG_NAME);
            String adress = c.getString(TAG_ADRESS);
            String partner_name = c.getString(TAG_PARTNER_NAME);


            double latitude = c.getDouble(TAG_LATITUDE);
            double longitude = c.getDouble(TAG_LONGITUDE);
            Location endLocation = new Location("endLocation");
            endLocation.setLatitude(latitude);
            endLocation.setLongitude(longitude);
            float distance = startLocation.distanceTo(endLocation) / 1000;

            HashMap<String, String> points = new HashMap<String, String>();


            Collections.sort(PointsList, new Comparator<HashMap<String, String>>() {

                @Override
                public int compare(HashMap<String, String> a, HashMap<String, String> b) {
                    return a.get(TAG_DISTANCE).compareTo(b.get(TAG_DISTANCE));
                }
            });

            points.put(TAG_NAME, name);
            points.put(TAG_ADRESS, adress);
            points.put(TAG_PARTNER_NAME, partner_name);
            points.put(TAG_DISTANCE, String.valueOf(distance) + " km");
            points.put(TAG_IMAGE, String.valueOf(R.drawable.logo));

            PointsList.add(points);
        }
        return PointsList;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
    else {
        Log.e("ServiceHandler", "Couldn't get any data from the url");
        return null;
    }
}


/**
 * Async task class to get json by making HTTP call
 */
public class GetPoints extends AsyncTask<Void, Void, Void> {

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> PointsList;
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();


    }

    @Override
    protected Void doInBackground(Void... arg0) {
        WebRequest webreq = new WebRequest();

        String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);

        Log.d("Response: ", "> " + jsonStr);

        PointsList = ParseJSON(jsonStr);

        return null;
    }

    @Override
    public void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */

        long endTime = System.nanoTime();
        long duration = endTime - startTime;

        Toast.makeText(MainActivity.this, "Time passed: " + duration / 1000000000 + " sec", Toast.LENGTH_LONG).show();


        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, PointsList,
                R.layout.list_item, new String[]{TAG_NAME, TAG_ADRESS, TAG_PARTNER_NAME, TAG_DISTANCE, TAG_IMAGE}, new int[]{R.id.name,
                R.id.adress, R.id.partner_name, R.id.distance, R.id.imageView});


        setListAdapter(adapter);
    }

}

}

Answer:

The beauty of JSON is that it can be saved as text.
If the data size is small, then SQLite not needed, save it to SharedPreferences . If the size is large, create a table with two fields like this:

private static final String TABLE_CREATE = 
    "create table JsonData (jsonKey text primary key, jsonData text not null);";

by a unique key, write-read.
If the data size is VERY large, then it is better to save and read as a file.

Scroll to Top