无法通过自定义列表适配器填充GridView

时间:2015-09-28 21:13:20

标签: android gridview imageview

我是制作Android应用程序的新手。我正在尝试创建一个简单的应用程序,从themoviedb.org提取电影数据,并在主页上显示电影中的海报。我正在使用带有自定义适配器的GridView和ImageView,但屏幕显示为空白。我不确定我需要做些什么才能让图像显示出来。

自定义适配器:

public class CustomImageAdapter extends BaseAdapter {
    private Context mContext;
    private String[] inputs;
    private List<ImageView> imageList;
    LayoutInflater inflater;

    public CustomImageAdapter(Context c, String[] inputs) {
        mContext = c;
        this.inputs = inputs;
        inflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return inputs.length;
    }

    public Object getItem(int position) {
        return imageList.get(position);
    }

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

    public void add(String[] results) {
        inputs = results;
        imageList = new ArrayList<ImageView>();

        for (int i = 0; i < inputs.length; i++){
            ImageView imageView = new ImageView(mContext);
            Picasso.with(mContext)
                    .load(inputs[i])
                    .into(imageView);
            imageList.add(imageView);
        }
    }


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

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View gridView;

        if (convertView == null) {
            gridView = new View(mContext);
            convertView = inflater.inflate(R.layout.grid_layout, null);
            ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_layout_image_view);
            imageView = imageList.get(position);
        } else {
            gridView = (View) convertView;
        }
        return gridView;
    }
}

主要片段:

public class GridFragment extends Fragment {


private static ImageView imageView;
private static String[] jsonStringHolder = new String[1];
private static CustomImageAdapter customImageAdapter;
private static GridView gridView;

public GridFragment() {
}

@Override
public void onStart() {
    super.onStart();
    FetchMovieTask fetchMovieTask = new FetchMovieTask();
    fetchMovieTask.execute();
}

private void loadImageView(String[] result) {
    try {
        getMovieDataFromJson(result);
    } catch (JSONException e) {
        Log.e("LOG_TAG", e.getMessage(), e);
        e.printStackTrace();
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    //customImageAdapter = new CustomImageAdapter(getContext(), null);
    gridView = (GridView) rootView.findViewById(R.id.grid_view);
    //gridView.setAdapter(customImageAdapter);
    return rootView;
}

private void getMovieDataFromJson(String[] jsonStringHolder)
        throws JSONException {

    final String OWM_POSTER_PATH = "poster_path";
    final String OWM_RESULTS = "results";
    String movieJsonStr = jsonStringHolder[0];
    JSONObject movieJsonObject = new JSONObject(movieJsonStr);
    JSONArray movieJsonArray = movieJsonObject.getJSONArray(OWM_RESULTS);

    String[] resultStrs = new String[movieJsonArray.length()];
    for (int i = 0; i < movieJsonArray.length(); i++) {
        JSONObject movieDescriptionJsonObject = movieJsonArray.getJSONObject(i);
        String posterPathPlaceholder =
                movieDescriptionJsonObject.getString(OWM_POSTER_PATH);

        final String FORECAST_BASE_URL =
                "http://api.themoviedb.org/3/movie/";
        final String SIZE = "w185";
        resultStrs[i] = FORECAST_BASE_URL + SIZE + posterPathPlaceholder;
    }
    customImageAdapter = new CustomImageAdapter(getContext(), null);
    customImageAdapter.add(resultStrs);
    gridView.setAdapter(customImageAdapter);
}

public class FetchMovieTask extends AsyncTask<Void, Void, String[]> {

    private final String LOG_TAG = FetchMovieTask.class.getSimpleName();

    @Override
    protected String[] doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String movieJsonStr = null;
        // String format = "json";
        //String units = "metric";
        //int numDays = 7;

        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            final String FORECAST_BASE_URL =
                    "http://api.themoviedb.org/3/movie/";
            final String PREFERENCE = "now_playing?";
            final String API_KEY = "api_key=e0cbb327025cf835dfc53ca51d11db68";
            //final String UNITS_PARAM = "units";
            //final String DAYS_PARAM = "cnt";

            String urlString = FORECAST_BASE_URL + PREFERENCE + API_KEY;
            URL url = new URL(urlString);


            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            movieJsonStr = buffer.toString();

        } catch (IOException e) {
            Log.e(LOG_TAG, "Error pits", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            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);
                }
            }
        }
        String[] movieJsonStrArray = new String[1];
        movieJsonStrArray[0] = movieJsonStr;
        return movieJsonStrArray;
    }

    @Override
    protected void onPostExecute(String[] result) {
        if (result != null) {
            jsonStringHolder[0] = result[0];
        }
        loadImageView(result);
    }
}

XML:

<RelativeLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment">
    <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/grid_view"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true">
    </GridView>
    <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/grid_layout_image_view" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

如果你试图用行填充列表,并且你是android的新手,也许你应该尝试从ListActivity或FragmentList扩展,请参阅http://developer.android.com/guide/topics/ui/layout/listview.html的google指南,ListActivity和FragmentList是帮手clases,他们有一个方法&#34; setListAdapter&#34;这样做。