0

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.

aminography
  • 21,986
  • 13
  • 70
  • 74
Hadif Hatta
  • 75
  • 1
  • 11
  • Have you declared the INTERNET permission in your manifest ? – Ezio Sep 26 '19 at 17:41
  • I see you have logs. What is the problem here? Is the connection not working or is the value not saved in SharedPreferences? – Yoav Gibri Sep 26 '19 at 17:46
  • does your `Log.d(TAG, "Fajr: " + time);` show anything? Also... when are you reading from the sharedPref? – remedy. Sep 26 '19 at 17:47
  • I suggest to use `getApplicationContext().getSharedPreferences(TAG, Context.MODE_PRIVATE);` and `commit();` instead of `apply();` – Raskilas Sep 26 '19 at 17:50
  • @Ezio yes i did! – Hadif Hatta Sep 26 '19 at 18:54
  • @YoavGibri I think the connection is not working when call using onCreate() :( – Hadif Hatta Sep 26 '19 at 18:55
  • @remedy. No :( I also can't find the log, I think it is not executed – Hadif Hatta Sep 26 '19 at 19:01
  • @Raskilas I have tried but it is still the same :( – Hadif Hatta Sep 26 '19 at 19:04
  • @hadif First, you can see the log in the LogCat section in the bottom of Android Studio. Can you add the log (set on Debug) to your question? Second, does the app crashes? – Yoav Gibri Sep 26 '19 at 20:32
  • Try reading [this answer](https://stackoverflow.com/a/29466338/6519248) and using the code from there, it is very similar you yours. – Yoav Gibri Sep 26 '19 at 20:50
  • @YoavGibri thanks that is a bit helpful, now i found that the problem is it doesnt go to the if statement which is the connection response.. then it just direct to the catch statement. This is my code with the log.d https://pastebin.com/eBWuSX6b – Hadif Hatta Sep 27 '19 at 03:52
  • @YoavGibri I tried to follow the answer but it always throw the exception.. :( – Hadif Hatta Sep 27 '19 at 04:09
  • Founded error: java.io.IOException: Cleartext HTTP traffic to api.aladhan.com not permitted – Hadif Hatta Sep 27 '19 at 04:22
  • @YoavGibri nvm fix it, the only problem is that on Android 9 cleartext support is disabled by default, thats the problem came from... I really appreciate your help sir! ty – Hadif Hatta Sep 27 '19 at 04:36

2 Answers2

0

Create editor and preferences

private var preferences: SharedPreferences? = null
private var editor: SharedPreferences.Editor? = null

Init editor and preferences

preferences = activity!!.getSharedPreferences("key_fajr", Context.MODE_PRIVATE)
//In fragment
//preferences = getActivity()!!.getSharedPreferences("key_fajr",     Context.MODE_PRIVATE)
editor = preferences!!.edit()

Save Data

editor!!.putString("email", mEtEmail!!.text.toString())
editor!!.commit()

Load Data

preferences!!.getString("email", "")
0

Since I have found the solution, I just write it here for some other future programmer use.

The problem is that I'm in Android 9 which is...

Starting with Android 9 (API level 28), cleartext support is disabled by default.

That's why in my case the exception occurs as follows:

java.io.IOException: Cleartext HTTP traffic to url not permitted

Plus, there's nothing to do with Shared Preferences. Everything is working as it supposed to be.

Solutions

Just add this line in AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>
Hadif Hatta
  • 75
  • 1
  • 11