Skip to content Skip to sidebar Skip to footer

Is There A Better Way To Execute This Code (load Multiple Urls)?

my code is working but when i launch the app, it is not fluent, i was wondering if there is a better way to make this code work or more cleaner to improve quickness ? Please any an

Solution 1:

Ok, so my problem is that every time that I call getInfos method I create a new client..

This is exactly your issue; and there are a few ways of solving it.

The fastest way to solve your issue is to just create the OkHttpClient in your onCreate method as a global variable. You may also want to only check if the network is available a single time.

publicclassMainActivityextendsAppCompatActivity {

    privatestatic final String[] mUrls = newString[] {
        "https://newsapi.org/v1/articles?source=buzzfeed&apiKey=5e08eafaefd44d14ad70ceea834c16bb",
        "https://newsapi.org/v1/articles?source=the-verge&apiKey=5e08eafaefd44d14ad70ceea834c16bb",
        "https://newsapi.org/v1/articles?source=the-lad-bible&apiKey=5e08eafaefd44d14ad70ceea834c16bb"
    };

    privateRecyclerView mRecyclerView;
    privateOkHttpClient mOkHttpClient;
    privateConnectivityManager mConnectivityManager;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        mOkHttpClient = newOkHttpClient();

        loadData();
    }

    privatevoidloadData() {
        if (isNetworkAvailable()) {
            for (String url : mUrls) {
                createRequest(url);
            }
        }
    }

    privatevoidcreateRequest(String url) {
        Request request = newRequest.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(newCallback() {
            @OverridepublicvoidonResponse(Call call, Response response) {
                // Your response implementation
            }

            @OverridepublicvoidonFailure(Call call, IOException exception) {
                // Your failure implementation
            }
        });
    }

    privatebooleanisNetworkAvailable() {
        NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

}

An even more beneficial way to solve this issue (if you use OkHttp in more than one Activity) is to only create a single OkHttpClient for your entire application. Though, this will require dependency injection, which the Android framework can make a bit more complicated; this is a good article that covers the basics.


Also, to make your life even easier, I would recommend a few other libraries that compliment OkHttp. It may take a while to learn some of them, but each will make working with network code significantly easier on Android. You don't need all of them either, you can start with one and work up from there.

  • Retrofit builds upon OkHttp (it is also by Square), and makes interacting with APIs a breeze.

  • Moshi is a JSON parser (also by Square), that works with Retrofit so you can avoid the cumbersome JSONObject and JSONArray code (Google's Gson also works with Retrofit).

  • And finally; RxJava and RxAndroid will make asynchronous calls even easier; you can even zip all three of your requests together, so you receive the results all at once!

Post a Comment for "Is There A Better Way To Execute This Code (load Multiple Urls)?"