-3

I'm trying to run a function inside a thread, and use the data afterwards. The obvious problem is that the main thread isn't waiting (If that's what happens) Though a pretty simple question, searching the internet didn't provide me any solution unfortunately. Any advice how to implement it properly?

Thread:

            MainActivity.this.runOnUiThread(new Runnable() { // A new thread to get the currencies
                @Override
                public void run() {
                    jsonConversion(mMessage);
                }

Function:

    public void jsonConversion(String mMessage) {
    try {

        JSONObject srcJson = new JSONObject(mMessage); // 2 objects, rates and base
        rates = srcJson.getJSONObject("rates"); // Currencies map
        baseCurrency = srcJson.getString("base"); // Base currency
        lastUpdate = srcJson.getString("date"); // Last update


    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Vadix3
  • 25
  • 7
  • You run this function on the main thread because of `runOnUiThread`. You can consider [`AsyncTask`](https://developer.android.com/reference/android/os/AsyncTask), but it is deprecated. On the page over that link, there are other suggestions what to use. – Jenea Vranceanu Aug 09 '20 at 10:33
  • What do you mean by "main thread isn't waiting"? What should the main thread wait for? All you've shown is a function that you run on the main thread, and there's nothing that uses its results – Joni Aug 09 '20 at 11:02

1 Answers1

-1

Consider using callbacks in your code to achieve what you want. letting the program wait for a thread is not good (generally) and using asynchronous threads will not achieve what you want, because you won't get the results from the thread by the time your function is called.

So, by using callbacks, you will ensure that everything will work the way you want and methods will only be called when your parameters are ready.

Have a look at this and this answers.

Murad Alm.
  • 79
  • 9