簡體   English   中英

在 listView 中插入來自 json url 的圖像

[英]Insert in listView an image from json url

我是安卓新手。 我在將圖像從 Json Url 加載到ListView遇到問題。 ListView 只能在沒有圖像的情況下工作。

這是我的 json 網址:

{"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"}]}

我的

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();

    }



}


}

這是我的

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;
}



}

這是我的

日志貓:

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

先感謝您。

你為什么把代碼弄得這么復雜? 把事情簡單化。 我有一個演示代碼。 也許它可以幫助你。 只需創建一個您需要的模型類。 其他的事情都是一樣的。

public class MainActivity extends AppCompatActivity {

private Button btnHit;

private HttpURLConnection connection = null;
private URL url;
private BufferedReader reader = null;
private StringBuffer buffer;
private ListView lvMovies;
private ProgressDialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dialog = new ProgressDialog(this);
    dialog.setIndeterminate(true);
    dialog.setCancelable(false);
    dialog.setMessage("Loading !! Please wait..");

    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .build();
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions)
            .build();
    ImageLoader.getInstance().init(config);

    lvMovies = (ListView) findViewById(R.id.lvMovies);
    new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
}


public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.show();
    }

    @Override
    protected List<MovieModel> doInBackground(String... params) {


        try {
            url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {

                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("movies");


            List<MovieModel> movieModelList = new ArrayList<>();

            Gson gson = new Gson();

            for (int i = 0; i < parentArray.length(); i++) {

                JSONObject finalObject = parentArray.getJSONObject(i);
                MovieModel movieModel = gson.fromJson(finalObject.toString(), MovieModel.class);

                movieModelList.add(movieModel);

            }
            return movieModelList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return null;
    }

    @Override
    protected void onPostExecute(List<MovieModel> result) {
        super.onPostExecute(result);

        dialog.dismiss();
        MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
        lvMovies.setAdapter(adapter);


        // TODO Need to set Data on List
    }
}


public class MovieAdapter extends ArrayAdapter {

    private List<MovieModel> movieModelList;
    private int resource;
    private LayoutInflater inflater;

    public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
        super(context, resource, objects);

        movieModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(resource, null);

            holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
            holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
            holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagLine);
            holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
            holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
            holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
            holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
            holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
            holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        final ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);

        ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                progressBar.setVisibility(View.GONE);
            }
        });

        holder.tvMovie.setText(movieModelList.get(position).getMovie());
        holder.tvTagline.setText(movieModelList.get(position).getTagline());
        holder.tvYear.setText("Year : " + movieModelList.get(position).getYear());
        holder.tvDuration.setText(movieModelList.get(position).getDuration());
        holder.tvDirector.setText(movieModelList.get(position).getDirector());


        // Rating Bar
        holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);

        Log.v("Rating is", "" + movieModelList.get(position).getRating() / 2);


        StringBuffer stringBuffer = new StringBuffer();
        for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {

            stringBuffer.append(cast.getName() + ", ");

        }

        holder.tvCast.setText(stringBuffer);
        holder.tvStory.setText(movieModelList.get(position).getStory());

        return convertView;
    }


    class ViewHolder {

        private ImageView ivMovieIcon;
        private TextView tvMovie;
        private TextView tvTagline;
        private TextView tvYear;
        private TextView tvDuration;
        private TextView tvDirector;
        private RatingBar rbMovieRating;
        private TextView tvCast;
        private TextView tvStory;
    }
}
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM