Reputation: 365
Second Activity in my project starts very slow, and I don't know how to fix it. How it works (everything's in onCreate()): firstly it does get-request to the page with json:
try {
DefaultHttpClient hc = new DefaultHttpClient();
ResponseHandler<String> res = new BasicResponseHandler();
HttpGet getMethod = new HttpGet(url);
String response = hc.execute(getMethod, res);
resStr = response.toString();
} catch (Exception e) {
System.out.println("Exp=" + e);
}
I know some methods from here are deprecated, but I don't know how to make it more optimized. As a result it returns a string with JSON array of about 32 Objects. Then I fill 6 arrays to pass them to ArrayAdapter for filling ListView. Methods of getting different types of data looks like this:
public static String GetWantedType(String resStr, int num) {
String jsonvalues = "";
try {
JSONArray json_Array = new JSONArray(resStr);
JSONObject json_data = json_Array.getJSONObject(num);
jsonvalues = json_data.getString("wanted_type");
} catch (JSONException e) {
e.printStackTrace();
}
return jsonvalues;
}
Maybe I should have created json_Array one time outside filling arrays and just pass it to those methods as a JSONArray, not as a string - I don't know if it influence the speed. In the ArrayAdapter everything seems to be all right, I'm using ViewHolder and my scrolling is excelent. Unlike starting Activity.
How to make it better and more optimized?
Upvotes: 0
Views: 1333
Reputation: 131
As Gaurav said the problem is that the network request is called on the main thread. At the time you ask a network call your program say : OK STOP I WAIT THE RESPONSE. So if you want to change this you can do various things. For example you can use a Asynchronous Network call with a lib (loopj lib) or you can simply open a Thread : do the network call.
With that your UI will not freeze
Upvotes: 1
Reputation: 407
First, don't do all operations in onCreate()
, prefer to do in onResume()
Second, all server call should be in background thread using Async and use result for displaying user.
If you don't want to call multiple times API for data during onResume()
and onPause()
, you can consume result of data in array or something and when onResume()
call, you can check whether it has data, just load it, else fetch from server.
Upvotes: 1
Reputation: 7737
Are you doing the network call on the main thread? Please don't do it. Instead do the network operations on different thread.
For networking you can use a library retrofit. It also makes it easy for you do the operations asynchronously, by using callbacks or using Observables from RxJava
Upvotes: 0