Страницы

Поиск по вопросам

понедельник, 15 июля 2019 г.

Подскажите пожалуйста как мне добавить данные с JSON в SQLite?

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> 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> PointsList = new ArrayList>(); 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 points = new HashMap();
Collections.sort(PointsList, new Comparator>() {
@Override public int compare(HashMap a, HashMap 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 {
// Hashmap for ListView ArrayList> 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); }
}
}


Ответ

Прелесть JSON в том, что его можно сохранять как текст. Если размер данных небольшой, то и SQLite не нужна, сохраняйте в SharedPreferences. Если же размер большой, создайте таблицу с двумя полями типа такой:
private static final String TABLE_CREATE = "create table JsonData (jsonKey text primary key, jsonData text not null);";
по уникальному ключу пишите-читайте. Если же размер данных ОЧЕНЬ большой, то лучше сохранять и читать как файл.

Комментариев нет:

Отправить комментарий