I'm new in android. I have a problem about loading the image from Json Url to ListView
. ListView works only without image.
This is my json url:
{"infoBooks":[{"user_name":"carlo","title":"Title: Il potere del cane\nAuthor\/s: Don Winslow","author":"","urlImage":"https:\/\/books.google.it\/books\/content?id=qiLanQEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"},{"user_name":"ff","title":"Title: Incontro con la storia. Con espansione online. Per la Scuola media\nAuthor\/s: Luisa Benucci","author":"","urlImage":"https:\/\/books.google.it\/books\/content?id=qTzFSgAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"}]}
My
SearchBooks.java :
public class SearchBooks extends AppCompatActivity {
ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_books);
String strUrl = "http://192.168.1.118:8888/webappdb/listViewBooks.php";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
mListView = (ListView) findViewById(R.id.listView);
}
private String downloadUrl (String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
}catch (Exception e){
Log.d("Exception while downloading url", e.toString());
}finally {
iStream.close();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (IOException e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
customAdapter customAdapter = new customAdapter();
customAdapter.parse(jObject);
} catch (JSONException e) {
Log.d("JSON Exception1", e.toString());
}
customAdapter customAdapter = new customAdapter();
List<HashMap<String, Object>> books = null;
try {
books = customAdapter.parse(jObject);
} catch (Exception e){
Log.d("Exception", e.toString());
}
String infoFrom[] = {"user_name", "details"};
int infoTo[] = {R.id.user_name_search, R.id.bookDescriptionSearch};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), books, R.layout.row_list_books, infoFrom, infoTo);
return adapter;
}
@Override
protected void onPostExecute(SimpleAdapter adapter) {
mListView.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("urlImage");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("urlImage", imgUrl);
hm.put("position", i);
imageLoaderTask.execute();
}
}
}
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("urlImage");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
File cacheDirectory = getBaseContext().getCacheDir();
File tmpFile = new File (cacheDirectory.getPath() + "/wpta_" + position + ".jpeg");
FileOutputStream fOutputStream = new FileOutputStream(tmpFile);
Bitmap b = BitmapFactory.decodeStream(iStream);
b.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
hmBitmap.put("launcherImage", tmpFile.getPath());
hmBitmap.put("position", position);
return hmBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
String path = (String) result.get("launcherImage");
int position = (Integer) result.get("position");
SimpleAdapter simpleAdapter = (SimpleAdapter) mListView.getAdapter();
HashMap<String, Object> hm = (HashMap<String, Object>) simpleAdapter.getItem(position);
hm.put("launcherImage", path);
simpleAdapter.notifyDataSetChanged();
}
}
}
this is my
customAdapter.java :
public class customAdapter{
public List<HashMap<String, Object>> parse(JSONObject JObject) {
JSONArray infoBooks = null;
try {
infoBooks = JObject.getJSONArray("infoBooks");
} catch (JSONException e) {
e.printStackTrace();
}
return getBooks(infoBooks);
}
private List<HashMap<String, Object>> getBooks(JSONArray infoBooks){
int booksCount = infoBooks.length();
List<HashMap<String, Object>> bookList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> book;
for(int i = 0; i < booksCount; i++) {
try {
book = getBook((JSONObject) infoBooks.get(i));
bookList.add(book);
} catch (JSONException e) {
e.printStackTrace();
}
}
return bookList;
}
private HashMap<String, Object> getBook(JSONObject jBook){
HashMap<String, Object> book = new HashMap<String, Object>();
String user_name = "";
String title = "";
String author = "";
String urlImage = "";
try {
user_name = jBook.getString("user_name");
title = jBook.getString("title");
author = jBook.getString("author");
urlImage = jBook.getString("urlImage");
String details = "Title: " + title + "\n" +
"Author/s: " + author;
book.put("user_name", user_name);
book.put("details", details);
book.put("launcherImage", R.mipmap.ic_launcher);
book.put("urlImage", urlImage);
} catch (JSONException e) {
e.printStackTrace();
}
return book;
}
}
This is my
logcat :
03-10 08:56:13.194 969-1433/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 08:56:13.994 969-1585/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 08:56:14.134 5005-5562/gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: gamingproject.sellmybooks, PID: 5005
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.doInBackground(SearchBooks.java:176)
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.doInBackground(SearchBooks.java:169)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
03-10 08:56:14.244 969-1049/? E/InputDispatcher: channel '14e67292 gamingproject.sellmybooks/gamingproject.sellmybooks.Profile (server)' ~ Channel is unrecoverably broken and will be disposed!
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.264 5566-5566/? E/Zygote: v2
03-10 08:56:14.274 5566-5566/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
03-10 08:56:14.774 270-270/? E/SMD: DCD OFF
03-10 08:56:17.784 270-270/? E/SMD: DCD OFF
Thank you in advance.