使用库“Picaaso”和ViewPager滑动图像

时间:2016-08-03 11:02:16

标签: android json android-volley picasso

我正在制作图像的滑块,图像来自网址。我正在使用Picasso库和ViewPager。

我没有通过点击网址获取任何图片。请帮我解释为什么图片不是滑块。

MainActivity

public class MainActivity extends Activity {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String url = "http://3359eb12.ngrok.io/api/v1/restaurants/get_featured_restaurants";

    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    //private ListView listView;
    ViewPager viewPager;
    //private SliderLayout imageSlider;
    private CustomListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.view_pager);

        //listView = (ListView) findViewById(R.id.list);
        //imageSlider = (SliderLayout)findViewById(R.id.slider);

        adapter = new CustomListAdapter(this, movieList);
        //listView.setAdapter(adapter);
        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        // handler to set duration and to upate animation
        final Handler mHandler = new Handler() {
            @Override
            public void close() {

            }

            @Override
            public void flush() {

            }

            @Override
            public void publish(LogRecord record) {

            }
        };

        // Create runnable for posting
        /*final Runnable mUpdateResults = new Runnable() {
            public void run() {
                AnimateandSlideShow();
            }


        };*/


        pDialog.show();
        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));
        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                //movie.setTitle(obj.getString("title"))
                                //movie.setName(obj.getString("name"));
                                //movie.setThumbnailUrl(obj.getString("image"));

                                movie.setThumbnailUrl(obj.getString("org_image_url").toString());
                                //movie.setAverage_ratings(obj.getString("average_ratings"));
                                //movie.setCuisine(obj.getString("cuisine"));
                                //movie.setAddress(obj.getJSONObject("address").getString("area"));
                                //movie.setAddress(obj.getString("address"));
                                //movie.setYear(obj.getInt("releaseYear"));
                                // Genre is json array
                                /*JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);*/
                                // adding movie to movies array
                                movieList.add(movie);


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                        setFlipperImage(movieList);
                    }

                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();


                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }



    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }*/

    private void setFlipperImage(List<Movie> movieList) {

        for(int i=0;i<movieList.size();i++){
            Log.i("Set Filpper Called", movieList.get(i).toString()+"");
            ImageView org_image_url = new ImageView(getApplicationContext());
            //com.android.volley.toolbox.NetworkImageView thumbnail = (NetworkImageView) new ImageView(getApplicationContext());
// image.setBackgroundResource(res);
            Picasso.with(MainActivity.this)
                    .load(movieList.get(i).toString())
                    .placeholder(R.drawable.bc)
                    .error(R.drawable.bc)
                    .into(org_image_url);
            viewPager.addView(org_image_url);
        }
        //viewPager.setAutoStart(true);
    }
    // method to show slide show
/*  private void AnimateandSlideShow() {
        viewPager.showNext();
    }*/
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="match_parent"


    >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:orientation="vertical"
        >
        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="150dp"></android.support.v4.view.ViewPager>
    </LinearLayout>
</LinearLayout>

customlistAdapter

 public class CustomListAdapter extends PagerAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

    @Override
    public int getCount() {
        return movieItems.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object o) {
        return false;
    }


    public Object getItem(int location) {
        return movieItems.get(location);
    }

    public long getItemId(int position) {
        return position;
    }


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

        if (inflater == null)
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        /*ImageView img;
        img = (ImageView)convertView
                .findViewById(R.id.img);

        img.setImageResource(R.drawable.bc);
        else {*/

        NetworkImageView _ImageView = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
         _ImageView.setDefaultImageResId(R.drawable.bc);
        //NetworkImageView.setImageUrl(m.getThumbnailUrl(), ImageLoader);
        /*NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);*/
    //  TextView name = (TextView) convertView.findViewById(R.id.name);
    //  TextView average_ratings = (TextView) convertView.findViewById(R.id.average_ratings);
        //TextView address=(TextView) convertView.findViewById(R.id.area);
    //  TextView cuisine =(TextView) convertView.findViewById(R.id.cuisine);
        //TextView genre = (TextView) convertView.findViewById(R.id.genre);
        //TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        Movie m = movieItems.get(position);

        // thumbnail image
        //_ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader);
        /*if (TextUtils.isEmpty(m.getThumbnailUrl()))
            thumbNail.setImageResource(R.drawable.bc);



        else
            //Log.d("KeyHash:","Neeraj");*/
        _ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader);
        /*if (m.getThumbnailUrl().compareTo("")!=0)
            thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
        //else{
        //thumbNail.setImageResource(R.drawable.bc);

            else {

                thumbNail.setDefaultImageResId(R.drawable.bc);
                //thumbNail.setErrorImageResId(R.drawable.bc);

        }*/


        // title
        //name.setText(m.getName());

        // rating
    //  average_ratings.setText("Rating: " + String.valueOf(m.getAverage_ratings()));
        //address.setText("Area: " + String.valueOf(m.getAddress()));
        //cuisine.setText("Cusine: " + String.valueOf(m.getCuisine()));
        /*// genre
        String genreStr = "";
        for (String str : m.getGenre()) {
            genreStr += str + ", ";
        }
        genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
        year.setText(String.valueOf(m.getYear()));*/

        return convertView;
    }



}

logcat的

08-03 16:30:33.600 30944-30944/info.androidhive.customlistviewvolley W/System: ClassLoader referenced unknown path: /data/app/info.androidhive.customlistviewvolley-1/lib/x86
08-03 16:30:35.259 30944-30944/info.androidhive.customlistviewvolley W/System: ClassLoader referenced unknown path: /data/app/info.androidhive.customlistviewvolley-1/lib/x86
08-03 16:30:35.381 30944-31003/info.androidhive.customlistviewvolley D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                                                                                       [ 08-03 16:30:35.395 30944:30944 D/         ]
                                                                                       HostConnection::get() New Host Connection established 0xafec9330, tid 30944


                                                                                       [ 08-03 16:30:35.466 30944:31003 D/         ]
                                                                                       HostConnection::get() New Host Connection established 0xae4c7330, tid 31003
08-03 16:30:35.473 30944-31003/info.androidhive.customlistviewvolley I/OpenGLRenderer: Initialized EGL, version 1.4
08-03 16:30:36.064 30944-30950/info.androidhive.customlistviewvolley W/art: Suspending all threads took: 44.543ms
08-03 16:30:41.172 30944-30997/info.androidhive.customlistviewvolley D/Volley: [142] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://3359eb12.ngrok.io/api/v1/restaurants/get_featured_restaurants 0x810b962b NORMAL 1> [lifetime=5705], [size=12695], [rc=200], [retryCount=1]
08-03 16:30:41.307 30944-30954/info.androidhive.customlistviewvolley I/art: Background sticky concurrent mark sweep GC freed 15441(1298KB) AllocSpace objects, 3(108KB) LOS objects, 62% free, 1379KB/3MB, paused 7.149ms total 117.493ms
08-03 16:30:41.538 30944-30944/info.androidhive.customlistviewvolley D/MainActivity: [{"id":209,"name":"Aer - Four Seasons","description":"Romantic, Happy Hours, Rooftops, Summer Cocktails","restaurant_type":null,"restaurant_url":null,"restaurant_facebook_url":null,"restaurant_google_url":null,"restaurant_zomato_url":"https:\/\/www.zomato.com\/mumbai\/aer-four-seasons-worli","average_ratings":"4.5","profile_image_file_name":"209.jpg","profile_image_content_type":"image\/jpeg","cover_image_file_name":null,"cover_image_content_type":null,"establishment_type":"Lounge,Fine Dining","cost":"4000","cuisine":"Spanish, Italian, European, Lebanese","timing":"5 PM to 1:30 AM","extras":null,"phone_numbers":[{"id":281,"restaurant_id":209,"number":"022 33126112","created_at":"2016-07-26T06:38:07.864-04:00","updated_at":"2016-07-26T06:38:07.864-04:00"}],"org_image_url":"http:\/\/comida-dev.s3.amazonaws.com\/res_pro_images\/209.jpg","thumb_image_url":"http:\/\/comida-dev.s3.amazonaws.com\/res_pro_thumb_images\/209.jpg","address":{"area":"Four Seasons, Worli","full_address":"Four Seasons Hotel, 114, E Moses Road, Worli, Mumbai,Four Seasons, Worli,mumbai,maharashtra,india,"},"menus":[],"restaurant_offers":[]},{"id":1191,"name":"Citrus - The Leela","description":"Sunday Brunches, All-day Dining","restaurant_type":null,"restaurant_url":null,"restaurant_facebook_url":null,"restaurant_google_url":null,"restaurant_zomato_url":"https:\/\/www.zomato.com\/mumbai\/citrus-the-leela-chakala","average_ratings":"4.0","profile_image_file_name":"1191.jpg","profile_image_content_type":"image\/jpeg","cover_image_file_name":null,"cover_image_content_type":null,"establishment_type":"Fine Dining","cost":"5000","cuisine":"Spanish, Italian, North Indian, American, Mediterranean, Continental, Japanese","timing":"24 Hours","extras":null,"phone_numbers":[{"id":1668,"restaurant_id":1191,"number":"022 33126849","created_at":"2016-07-26T06:38:19.929-04:00","updated_at":"2016-07-26T06:38:19.929-04:00"}],"org_image_url":"http:\/\/comida-dev.s3.amazonaws.com\/res_pro_images\/1191.jpg","thumb_image_url":"http:\/\/comida-dev.s3.amazonaws.com\/res_pro_thumb_images\/1191.jpg","address":{"area":"The Leela, Chakala","full_address":"The Leela, Andheri-Kurla Road, Sahar, Andheri East, Chakala, Mumbai,The Leela, Chakala,mumbai,maharashtra,india,"},"menus":[],"restaurant_offers":[{"id":536,"text":"Breakfast Buffet @ Rs. 1413 AI","offer_link":"https:\/\/www.dineout.co.in\/mumbai\/citrus-the-leela-mumbai-andheri-east-western-suburbs-1135","resource":"dineout"},{"id":537,"text":"\"Enjoy 10% off on food bill (Mon-Fri) lunch\"","offer_link":"https:\/\/www.eazydiner.com\/\/mumbai\/citrus-andheri-west-223109","resource":"eazydiner"}]},{"id":7952,"name":"Bombay Brew","description":null,"restaurant_type":null,"restaurant_url":null,"restaurant_facebook_url":null,"restaurant_google_url":null,"restaurant_zomato_url":"https:\/\/www.zomato.com\/mumbai\/bombay-brew-juhu","average_ratings":"-","profile_image_file_name":"7952.jpg","profile_image_content_type":"image\/jpeg","cover_image_file_name":null,"cover_image_content_type":null,"establishment_type":"Café,Quick Bites","cost":"1000","cuisine":"Cafe, Fast Food","timing":"12 Noon to 12 Midnight","extras":null,"phone_numbers":[{"id":12461,"restaurant_id":7952,"number":"022 26163636","created_at":"2016-07-26T06:39:40.510-04:00","updated_at":"2016-07-26T06:39:40.510-04:00"}],"org_image_url":"http:\/\/comida-dev.s3.amazonaws.com\/res_pro_images\/7952.jpg","thumb_image_url":"http:\/\/comida-dev.s3.amazonaws.com\/res_pro_thumb_images\/7952.jpg","address":{"area":"Juhu","full_address":"Bawa Continental, Opposite Theosophical Society, Juhu Tara Road, Juhu, Mumbai,Juhu,mumbai,maharashtra,india,"},"menus":[],"restaurant_offers":[{"id":1070,"text":"\"Enjoy 15% off on food & beverage\"","offer_link":"https:\/\/www.eazydiner.com\/\/mumbai\/bombay-brew-juhu-224184","resource":"eazydiner"}]},{"id":1980,"name":"Yuuka - The St. Regis Mumbai","description":"Super Sushi","restaurant_type":null,"restaurant_url":null,"restaurant_facebook_url":null,"restaurant_google_url":null,"restaurant_zomato_url":"https:\/\/ww
08-03 16:30:41.559 30944-31003/info.androidhive.customlistviewvolley E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa29702a0
08-03 16:30:41.588 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@b97585d
08-03 16:30:41.604 30944-30944/info.androidhive.customlistviewvolley W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
08-03 16:30:41.832 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@e47a9ff
08-03 16:30:41.843 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@ce23615
08-03 16:30:41.846 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@476e71b
08-03 16:30:41.853 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@4bd1e91
08-03 16:30:41.876 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@a59b9ce
08-03 16:30:41.876 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@ccb37fc
08-03 16:30:41.877 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@85ba4da
08-03 16:30:41.877 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@891d7e8
08-03 16:30:41.881 30944-30944/info.androidhive.customlistviewvolley I/Set Filpper Called: info.androidhive.customlistviewvolley.model.Movie@45f34a6
08-03 16:30:41.903 30944-30944/info.androidhive.customlistviewvolley D/Volley: [1] Request.finish: 6487 ms: [ ] http://3359eb12.ngrok.io/api/v1/restaurants/get_featured_restaurants 0x810b962b NORMAL 1

2 个答案:

答案 0 :(得分:1)

替换代码:

Picasso.with(MainActivity.this)
                .load(movieList.get(i).toString())
                .placeholder(R.drawable.bc)
                .error(R.drawable.bc)
                .into(org_image_url);

这一个:

Picasso.with(MainActivity.this)
                .load(movieList.get(i).getThumbnailUrl().toString())
                .placeholder(R.drawable.bc)
                .error(R.drawable.bc)
                .into(org_image_url);

答案 1 :(得分:0)

Picasso不会加载1MB以上的图片,在毕加索中使用DISK_CACHE或在Google上搜索此内容。