Skip to content

Instantly share code, notes, and snippets.

@jabubuck
Created February 25, 2019 00:25
Show Gist options
  • Save jabubuck/6fb76d36a63beb11a167e9f9c4e6ff56 to your computer and use it in GitHub Desktop.
Save jabubuck/6fb76d36a63beb11a167e9f9c4e6ff56 to your computer and use it in GitHub Desktop.
Useful android java snippets
//JSON Load from file to object
public JSONObject loadJSONFromAsset() {
String json = null;
try {
//Points towards top level assets folder
InputStream is = getApplicationContext().getAssets().open("filename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return JSONObject object = new JSONObject(json);
}
//Download JSON from API
private void downloadData() {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
String dataString = "";
URL url = new URL("DATAURL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int responseCode = conn.getResponseCode();
System.out.println("Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream is = new BufferedInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
dataString += line;
}
//... Process data here
br.close();
is.close();
conn.disconnect();
} else {
throw new IllegalStateException("HTTP response: " + responseCode);
}
} catch (IOException e) {
System.out.println("Error Downloading Json");
e.printStackTrace();
}
}
});
}
//Read and write JSON and strings to Shared prefs
//Instantiate prefs
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("MYPREFS", getApplicationContext().MODE_PRIVATE);
//Get String
String dataString = sharedPref.getString("STRINGNAME", "");
//IFJSON
JSONArray dataArray = new JSONArray();
if (!dataString.isEmpty()) {
dataArray = new JSONArray(dataString);
}
//Update JSON
JSONObject json = new JSONObject();
json.put("KEY", "ITEMTOSTORE");
dataArray.put(json);
//Write JSON to Prefs
String newDataString = dataArray.toString();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("STRINGNAME", newDataString);
editor.apply();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment