Like the title says, I am trying to retrieve data from a connection and save the data (which is just some values) to the shared preference.
The connection is working if I test and just run with main() method but it doesn't work within the app if I call the code with the onCreate() event. It won't save the data and it will always be null.
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPref.edit();
try {
String link = "...";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output, totalString = "";
while ((output = bufferedReader.readLine()) != null) {
totalString += output;
}
Log.d(TAG, totalString);
com.google.gson.JsonObject jsonObject = new JsonParser().parse(totalString)
.getAsJsonObject();
String time = jsonObject.getAsJsonObject("data").getAsJsonObject("timings")
.get("Fajr").getAsString();
Log.d(TAG, "Fajr: " + time);
editor.putString("key_fajr", time);
editor.apply();
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
The code I use to retrieve data:
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String value = sharedPref.getString("key_fajr", null);
Exception:
java.io.IOException: Cleartext HTTP traffic to api.aladhan.com not permitted
I expect it will get the data from the connection and save it in shared preference within the app.