private
class
LoadList
extends
AsyncTask<Void, Void, ArrayList<ListItem>> {
JSONArray list;
JSONObject row;
Bitmap thumb;
protected
ArrayList<ListItem> doInBackground(Void... params) {
final
ArrayList<ListItem> tempItems =
new
ArrayList<>();
list = getList(getCurrentPage());
if
(list.length() <=
0
) {
endOfList =
true
;
return
tempItems;
}
tempItems.clear();
for
(
int
i =
0
; i < list.length(); i++) {
try
{
final
ListItem item =
new
ListItem(getActivity());
row = list.getJSONObject(i);
item.setData(row);
item.setThumbnailBitmap(loadThumbnailFromUrl(item.getThumbnailUrl()));
getActivity().runOnUiThread(
new
Runnable() {
@Override
public
void
run() {
item.setThumbnail();
item.setItems();
item.setStars();
tempItems.add(item);
}
});
}
catch
(JSONException e) {
e.printStackTrace();
}
}
return
tempItems;
}
@Override
protected
void
onPreExecute() {
super
.onPreExecute();
loading =
true
;
dialog.setMax(
100
);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setTitle(
"Loading list"
);
dialog.setMessage(
"Loading list page "
+ getCurrentPage());
dialog.setCancelable(
false
);
dialog.show();
}
@Override
protected
void
onPostExecute(
final
ArrayList<ListItem> result) {
super
.onPostExecute(result);
items.addAll(result);
gridAdapter.notifyDataSetChanged();
loading =
false
;
dialog.cancel();
dialog.hide();
dialog.dismiss();
lastItemFlag =
false
;
if
(getCurrentPage() ==
1
) {
gridList.smoothScrollToPosition(
0
);
}
}
private
JSONArray getList(
int
page) {
String shelf_url = ((MainActivity) getActivity()).baseUrl +
"/"
+ currentMenu +
"/"
+ page;
JSONObject json;
try
{
HttpClient client =
new
DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
"ComicDBApp"
);
HttpGet request =
new
HttpGet(shelf_url);
request.setHeader(
"http.agent"
,
"ComicDBApp"
);
request.setHeader(
"fb_id"
, ((MainActivity) getActivity()).facebookId);
request.setHeader(
"fb_name"
, ((MainActivity) getActivity()).facebookName);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
json =
new
JSONObject(content);
return
new
JSONArray(json.getString(
"list"
));
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
catch
(JSONException e) {
e.printStackTrace();
}
return
null
;
}
private
Bitmap loadThumbnailFromUrl(String thumbnail_url) {
try
{
URL url =
new
URL(thumbnail_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(
true
);
connection.connect();
InputStream input = connection.getInputStream();
return
BitmapFactory.decodeStream(input);
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
return
BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.no_thumb);
}
}