GridView不会显示图像

时间:2016-02-28 13:34:18

标签: android gridview

有没有办法让我的应用加载屏幕上可见的所有图片,而不必旋转设备或滑动?我注意到它适用于某些尺寸而不适用于其他尺寸(但我现在需要更大的尺寸)。此外,如果我没有两组占位符图像(不知道为什么),应用程序不起作用。提前谢谢!

这是我的图像适配器:

res.render('users', {users: users})

这是我的片段:

package tk.talcharnes.popularmovies;

 import android.content.Context; import android.view.View; import
 android.view.ViewGroup; import android.widget.BaseAdapter; import
 android.widget.GridView; import android.widget.ImageView;

 import com.squareup.picasso.Picasso;

 /**  * Created by Tal on 2/24/2016.  */ public class ImageAdapter
 extends BaseAdapter {   //  private static String[] desc = new
 String[9];
     private static String[] desc = {
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
"http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg",
             "http://www.jqueryscript.net/images/jQuery-Ajax-Loading-Overlay-with-Loading-Text-Spinner-Plugin.jpg"
     };
     private static String[] imageArray = getDesc();
     private Context mContext;
     //private String[] asc = new String[PostersFragment.getMovieModelListLength()];
     private static String[] asc = {};

     public ImageAdapter(){

     }


     public int getCount() {
        try{
             return imageArray.length;}
         catch(NullPointerException e){
             e.printStackTrace();
             return 0;
         }
     }

     public ImageAdapter(Context c) {
         mContext = c;
     }

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

public Object getItem(int position) {
         return imageArray[position];
     }

     // create a new ImageView for each item referenced by the Adapter
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
         ImageView imageView;
         if (convertView == null) {
             // if it's not recycled, initialize some attributes
             imageView = new ImageView(mContext);
             int pixels = (int) (mContext.getResources().getDisplayMetrics().density + 0.5f);
             imageView.setLayoutParams(new GridView.LayoutParams(185*pixels, 277*pixels));

             convertView = imageView;
             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
             //  imageView.setPadding(8, 8, 8, 8);
         } else {
             imageView = (ImageView) convertView;
         }
         Picasso.with(mContext).load(imageArray[position])
                 .placeholder(R.drawable.sample_0)
          //       .resize(185,277)
                 .into(imageView);
         //imageView.setImageResource(Integer.parseInt(imageArray[position]));
         return imageView;
     }



     public static String[] getAsc() {
         return asc;
     }

     public static void setAsc(String[] asc) {
         ImageAdapter.asc = asc;
     }

     public static String[] getDesc() {
         return desc;
     }
     public static void setImageArray(String[] arrayName){
         imageArray = arrayName;
     } }

我相信这最后一块应该是最后一点所需的代码,如果完全是布局:

    package tk.talcharnes.popularmovies;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * A placeholder fragment containing a simple view.
 */
public class PostersFragment extends Fragment {
    private static List<MovieModel> movieModelList;
    private static int movieModelListLength;
    GridView gridView;
    private String done = null;
    ImageAdapter adapter;
    public PostersFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        FetchPostersTask fetchPostersTask = (FetchPostersTask) new FetchPostersTask().execute();
        // should find gridview on the view which you are creating
        gridView = (GridView) view.findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(getContext()));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                Toast.makeText(getContext(), "You clicked " + movieModelList.get(position).getTitle() ,
                        Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    private final String BASE_URL = "https://api.themoviedb.org/3/";
    private String middle_section = "discover/movie?sort_by=popularity.desc&api_key=";
    private String jSonUrl = BASE_URL + middle_section + BuildConfig.MOVIE_DB_API_KEY;
    //Get movie posters and data
    public class FetchPostersTask extends AsyncTask<Void,Void,Void> {
        private final String LOG_TAG = FetchPostersTask.class.getSimpleName();
        //will contain raw Json data
        String posterJsonString = null;

        public Void parseMovieJson()
                throws JSONException{
            JSONObject jsonParentObject = new JSONObject(posterJsonString);
            JSONArray movieJSonArray = jsonParentObject.getJSONArray("results");

            movieModelList = new ArrayList<>();
            for(int i = 0; i < movieJSonArray.length(); i++){
                JSONObject movieJsonObject = movieJSonArray.getJSONObject(i);
                MovieModel movieModel = new MovieModel();
                movieModel.setTitle(movieJsonObject.getString("title"));
                movieModel.setOverview(movieJsonObject.getString("overview"));
                movieModel.setPoster_path(movieJsonObject.getString("poster_path"));
                movieModel.setRelease_date(movieJsonObject.getString("release_date"));
                movieModel.setVote_average(movieJsonObject.getString("vote_average"));
                movieModelListLength++;

                movieModelList.add(movieModel);
            }
            return null;
        }
        @Override
        protected Void doInBackground(Void ...params) {

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
//
            //will contain raw Json data
            // String posterJsonString = null;
            try{

                //open connection to api

                URL url = new URL(jSonUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                //read input into string
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if(inputStream == null){
                    //nothing else to do in this case
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while((line = reader.readLine())!= null){
                    buffer.append(line + "\n");
                }

                if(buffer.length()==0){
                    //nothing here, don't parse
                    return null;
                }

                posterJsonString = buffer.toString();
            }
            catch(MalformedURLException e){
                e.printStackTrace();
            }
            catch(IOException e){
                Log.e(LOG_TAG, "Error", e);
                return null;
            }
            finally {
                if(urlConnection != null){
                    urlConnection.disconnect();
                }
                if(reader != null){
                    try{
                        reader.close();

                    }
                    catch (final IOException e){
                        Log.e(LOG_TAG,"Error closing stream", e);
                    }
                }
            }
            try{
                parseMovieJson();;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //ImageAdapter.setAsc(movieModelList.);
            String[] asc = new String[movieModelList.size()];
            for(int i = 0; i < asc.length; i++){
                asc[i]=(getMovieModelList().get(i).getPoster_path());
                //ImageAdapter.setAsc(asc);
            }
            adapter.setImageArray(asc);
        }
    }
    public static List<MovieModel> getMovieModelList(){
        return movieModelList;
    }
    public static int getMovieModelListLength(){
        return movieModelListLength;
    }

}

如果代码有点笨拙,请提前抱歉我是新程序员并且已经注释了一些内容,以确保我可以在以后需要时使用它们。再次提前致谢:D

更新:当我尝试输入代码时:adapter.notifyDataSetChange();在adapter.setImageArray(asc)之后;我收到此错误代码:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PostersFragment">

    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:gravity="center"
        android:horizontalSpacing="0dp"
        android:verticalSpacing="0dp"
        android:layout_margin="0dp"

        />

</FrameLayout>

我确实得到了一个类似的错误代码,这是一个数组的空指针错误,当我将数组设置为我已命名为desc的数组时,我以某种方式得到修复,然后我将postersfragment更改为immagearray为asc数组一旦用asynctask完成。不知道为什么这会阻止错误并且几乎修复了它。

1 个答案:

答案 0 :(得分:1)

添加此类

项时,在适配器上调用notifyDataSetChanged
onPostExecute()

(您可以在{{1}}方法结束时执行此操作)