如何在列表视图中显示Json url中的图像

时间:2016-03-10 11:06:00

标签: java android json listview imageview

我是android的新手。我有一个关于将图像从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", "launcherImage"};
        int infoTo[] = {R.id.user_name_search, R.id.bookDescriptionSearch, R.id.coverBookSearch};
        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();

            hm.put("urlImage", imgUrl);
            hm.put("position", i);

            imageLoaderTask.execute(hm);

        }
    }
}



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 + ".png");
            FileOutputStream fOutputStream = new FileOutputStream(tmpFile);
            Bitmap b = BitmapFactory.decodeStream(iStream);
           b.compress(Bitmap.CompressFormat.PNG, 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;
}
 }

logcat:

   03-10 12:02:42.088 969-1029/? E/lights: write_led_info failed to open -1
03-10 12:02:42.088 969-1029/? E/lights: write_led_info failed to open -1
03-10 12:02:42.188 969-1065/? E/native: do suspend false
03-10 12:02:42.288 969-1065/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source 10007 txSuccessRate=0,00 rxSuccessRate=0,13 targetRoamBSSID=any RSSI=-73
03-10 12:02:42.388 247-569/? E/qdutils: int qdutils::getHDMINode(): Failed to open fb node 2
03-10 12:02:42.388 247-569/? E/qdutils: int qdutils::getHDMINode(): Failed to find HDMI node
03-10 12:02:42.638 969-1104/? E/lights: write_int failed to open -1
03-10 12:02:42.718 969-969/? E/LocSvc_flp: I/===> int flp_inject_location(FlpLocation*) line 222 
03-10 12:02:42.728 969-1336/? E/LocSvc_ApiV02: I/<--- void globalRespCb(locClientHandleType, uint32_t, locClientRespIndUnionType, void*) line 125 QMI_LOC_INJECT_POSITION_REQ_V02
03-10 12:02:42.738 969-1367/? E/LocSvc_ApiV02: I/<--- void globalRespCb(locClientHandleType, uint32_t, locClientRespIndUnionType, void*) line 125 QMI_LOC_INJECT_POSITION_REQ_V02
03-10 12:02:43.238 274-763/? E/FastThread: did not receive expected priority boost
03-10 12:02:44.138 969-1104/? E/lights: write_int failed to open -1
03-10 12:02:44.838 969-981/? E/PersonaManagerService: inState():  stateMachine is null !!
03-10 12:02:45.078 270-270/? E/SMD: DCD OFF
03-10 12:02:45.568 23494-23494/gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: main
 Process: gamingproject.sellmybooks, PID: 23494
 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.HashMap.get(java.lang.Object)' on a null object reference
 at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.onPostExecute(SearchBooks.java:216)
  at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.onPostExecute(SearchBooks.java:174)
  at android.os.AsyncTask.finish(AsyncTask.java:632)
  at android.os.AsyncTask.access$600(AsyncTask.java:177)
  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:5536)
  at java.lang.reflect.Method.invoke(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
03-10 12:02:45.578 969-31049/? E/android.os.Debug: ro.product_ship = true
03-10 12:02:45.578 969-31049/? E/android.os.Debug: ro.debug_level = 0x4f4c
03-10 12:02:45.668 2326-31050/? E/SQLiteLog: (284) automatic index on crash_info_summary(package_name_touched)
03-10 12:02:45.728 2326-31050/? E/SQLiteLog: (284) automatic index on crash_info_summary(package_name_touched)
03-10 12:02:48.078 270-270/? E/SMD: DCD OFF

我不理解错误。 提前致谢。

3 个答案:

答案 0 :(得分:0)

您无法直接从网址加载图片。 您应该在将其加载到imageview中之前将其转换为drawable。

看一下这个库,在Android中加载图片。 http://square.github.io/picasso/

答案 1 :(得分:0)

为什么你的代码如此复杂?把事情简单化。我有一个演示代码。也许它可以帮到你。只需创建一个您需要的模型类。其他的事情是一样的。

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

}     }

答案 2 :(得分:0)

试试我的适配器代码:

public class MyAdapter extends BaseAdapter implements OnClickListener {

    Context con;
    ArrayList<Model> mlist;
    LayoutInflater inflater=null;

    public MyAdapter(Context con,ArrayList<Model> list,SpinnerInterface sp)
    {
        this.con=con;
        this.mlist=list;  
        inflater=(LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

        // UNIVERSAL IMAGE LOADER SETUP
                DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                        .cacheOnDisc(true).cacheInMemory(true)
                        .imageScaleType(ImageScaleType.EXACTLY)
                        .displayer(new FadeInBitmapDisplayer(300)).build();

               ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(con)
                        .defaultDisplayImageOptions(defaultOptions)
                        .memoryCache(new WeakMemoryCache())
                        .discCacheSize(100 * 1024 * 1024).build();

                ImageLoader.getInstance().init(config);
                // END - UNIVERSAL IMAGE LOADER SETUP

    }   

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mlist.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mlist.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public int getViewTypeCount() {
        if (getCount() != 0)
            return getCount();

        return 1;
    }



    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub


         model=mlist.get(position);
         ViewHolder holder=null;

        if(convertView==null){

          convertView=inflater.inflate(R.layout.product_layour,parent,false);
          holder=new ViewHolder();

            holder.img1=(ImageView)convertView.findViewById(R.id.imageViewProductImage);    


           convertView.setTag(holder);          

         }else{    holder=(ViewHolder)convertView.getTag();   }


        String img_url=model.getPhoto();

        ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
                        .cacheOnDisc(true).resetViewBeforeLoading(true)
                        .showImageForEmptyUri(R.drawable.productimg)
                        .showImageOnFail(R.drawable.productimg)
                        .showImageOnLoading(R.drawable.productimg).build();             
        //download and display image from url
        imageLoader.displayImage(img_url,holder.img1, options);      


        return convertView;

    }


    private class ViewHolder{

         public ImageView img1 ;

    }

}

希望它可以帮到你