0

我正在尝试将处理位图的谷歌示例 BitmapFun 改编为我自己的代码。我通过异步任务(SearchDaMovies)通过 JSON 从 mysql 数据库中获取图片 url。问题是,我无法将图片加载到图像适配器中。它适用于示例数组“imageThumbUrls”。但是当我用我需要的字符串数组“arrayS”替换“imageThumbUrls”字符串数组时,它给了我一个 NullPointerException。我该怎么做?我已经坚持了一周。

public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final String TAG = "ImageGridFragment";
private static final String IMAGE_CACHE_DIR = "thumbs";

private int mImageThumbSize;
private int mImageThumbSpacing;
private ImageAdapter mAdapter;
private ImageFetcher mImageFetcher;

String id, name, year, genre, known, tag1, tag2, tag3, poster, oster, description, vote ;
private ProgressDialog pDialog;
jParser parser = new jParser();
ArrayList<HashMap<String, String>> movies;
private static final String urlGetPid = "http://linkpictures.com";
private static final String TAG_SUCCESS = "success";
JSONArray jArray = null;
private static final String TAG_PID = "pid";
private static final String TAG_POSTER = "poster";
int success;


/**
 * Empty constructor as per the Fragment documentation .
 */
public ImageGridFragment() {}

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



    mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
    mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

    mAdapter = new ImageAdapter(getActivity());

    ImageCacheParams cacheParams = new ImageCacheParams(getActivity(), IMAGE_CACHE_DIR);

    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

    // The ImageFetcher takes care of loading images into our ImageView children asynchronously
    mImageFetcher = new ImageFetcher(getActivity(), mImageThumbSize);
    mImageFetcher.setLoadingImage(R.drawable.empty_photo);
    mImageFetcher.addImageCache(getActivity().getSupportFragmentManager(), cacheParams);
}

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

    movies = new ArrayList<HashMap<String, String>>();
    new SearchDaMovies().execute();

    final View v = inflater.inflate(R.layout.activity_show_movies, container, false);
    final ListView mGridView = (ListView) v.findViewById(R.id.listView1);

    Bundle extras = getActivity().getIntent().getExtras();
    name = extras.getString("name");
    year = extras.getString("year");
    known = extras.getString("known");
    genre = extras.getString("genre");
    tag1 = extras.getString("tag1");
    tag2 = extras.getString("tag2");
    tag3 = extras.getString("tag3");
    vote = extras.getString("vote");
    description = extras.getString("description");



    mGridView.setAdapter(mAdapter);
    mGridView.setOnItemClickListener(this);
    mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int scrollState) {
            // Pause fetcher to ensure smoother scrolling when flinging
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                mImageFetcher.setPauseWork(true);
            } else {
                mImageFetcher.setPauseWork(false);
            }
        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
        }
    });


    return v;
}

@Override
public void onResume() {
    super.onResume();
    mImageFetcher.setExitTasksEarly(false);
    mAdapter.notifyDataSetChanged();
}

@Override
public void onPause() {
    super.onPause();
    mImageFetcher.setPauseWork(false);
    mImageFetcher.setExitTasksEarly(true);
    mImageFetcher.flushCache();
}

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

@TargetApi(16)
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

    if (Utils.hasJellyBean()) {

        ActivityOptions options =
                ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), `v.getHeight());`

    } else {

    }
}

public class SearchDaMovies extends AsyncTask<String, String, String[]>{

String[] arrayS;

    @Override
    protected String[] doInBackground(String... args) {



        try {

        // send the query to JSON 
        List<NameValuePair> params = new ArrayList<NameValuePair>();            
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("year", year));
        params.add(new BasicNameValuePair("genre", genre));
        params.add(new BasicNameValuePair("known", known));
        params.add(new BasicNameValuePair("tag1", tag1));
        params.add(new BasicNameValuePair("tag2", tag2));
        params.add(new BasicNameValuePair("tag3", tag3));
        params.add(new BasicNameValuePair("vote", vote));

        params.add(new BasicNameValuePair("poster", poster));
        params.add(new BasicNameValuePair("description", description));


        //receive the JSON data
        JSONObject json = parser.makeHttpRequest(urlGetPid, params);

        success = json.getInt(TAG_SUCCESS);
        if (success == 1){
             jArray = json.getJSONArray("Table");

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

                JSONObject c = jArray.getJSONObject(i); 
                String id = c.getString("pid");
                String ame = c.getString("name");
                String ear = c.getString("year");
                String enre = c.getString("genre");
                String nown = c.getString("known");
                String ag1 = c.getString("tag1");

                String ote = c.getString("vote");


                if (ote.length()>14){

                ote = ote.substring(0, ote.length() - 14);
                }

                 oster = c.getString("poster");

                 //get the posters in an array
                 arrayS= new String[100];
                 arrayS[i]=oster;
                 Log.d("weird array  ", arrayS[i]);
                String escription = c.getString("description");


                HashMap<String, String> map = new HashMap<String, String>();
                map.put("pid", id);
                map.put("name", ame);
                map.put("year", ear);
                map.put("genre", enre);
                map.put("known",nown);
                map.put("tag1", ag1);

                map.put("vote", ote);
                map.put("poster", oster);
                map.put("description", escription);
                movies.add(map);




            }


        }
        } catch (JSONException e) {

            e.printStackTrace();
        }

        return arrayS;

    }


}


/**
 * The main adapter that backs the GridView. This is fairly standard except the number of
 * columns in the GridView is used to create a fake top row of empty views as we use a
 * transparent ActionBar and don't want the real top row of images to start off covered by it.
 */
public final static String[] imageThumbUrls = new String[] {
    "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s160-c/A%252520Photographer.jpg",
    "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s160-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
    "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s160-c/Another%252520Rockaway%252520Sunset.jpg",
    "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s160-c/Antelope%252520Butte.jpg",
    "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s160-c/Antelope%252520Hallway.jpg",
    "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s160-c/Antelope%252520Walls.jpg",
};
private class ImageAdapter extends BaseAdapter {

    private final Context mContext;
    private int mItemHeight = 0;
    private int mNumColumns = 0;
    private int mActionBarHeight = 0;
    private GridView.LayoutParams mImageViewLayoutParams;
   // private ArrayList<HashMap<String, String>> movies = new ArrayList<HashMap<String, String>>();


    public ImageAdapter(Context context) {
        super();
        mContext = context;
        mImageViewLayoutParams = new GridView.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        // Calculate ActionBar height
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(
                android.R.attr.actionBarSize, tv, true)) {
            mActionBarHeight = TypedValue.complexToDimensionPixelSize(
                    tv.data, context.getResources().getDisplayMetrics());
        }
    }

    @Override
    public int getCount() {
        // Size + number of columns for top empty row
        return imageThumbUrls.length;
    }

    @Override
    public Object getItem(int position) {
        return position < mNumColumns ?
                null : imageThumbUrls[position];
    }

    @Override
    public long getItemId(int position) {
        return position < mNumColumns ? 0 : position - mNumColumns;
    }

    @Override
    public int getViewTypeCount() {
        // Two types of views, the normal ImageView and the top row of empty views
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        return (position < mNumColumns) ? 1 : 0;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        // First check if this is the top row
        if (position < mNumColumns) {
            if (convertView == null) {
                convertView = new View(mContext);
            }
            // Set empty view with height of ActionBar
            convertView.setLayoutParams(new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, mActionBarHeight));
            return convertView;
        }

        // Now handle the main ImageView thumbnails
        ImageView imageView;
        if (convertView == null) { // if it's not recycled, instantiate and initialize
            imageView = new RecyclingImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(mImageViewLayoutParams);
        } else { // Otherwise re-use the converted view
            imageView = (ImageView) convertView;
        }

        // Check the height matches our calculated column width
        if (imageView.getLayoutParams().height != mItemHeight) {
            imageView.setLayoutParams(mImageViewLayoutParams);
        }

        // Finally load the image asynchronously into the ImageView, this also takes care of
        // setting a placeholder image while the background thread runs
        mImageFetcher.loadImage(imageThumbUrls[position],
                 imageView);
        return imageView;
    }


    // * Sets the item height. Useful for when we know the column width so the height can be set
    // * to match.
   //
    // * @param height

    public void setItemHeight(int height) {
        if (height == mItemHeight) {
            return;
        }
        mItemHeight = height;
        mImageViewLayoutParams =
                new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
        mImageFetcher.setImageSize(height);
        notifyDataSetChanged();
    }

    public void setNumColumns(int numColumns) {
        mNumColumns = numColumns;
    }

    public int getNumColumns() {
        return mNumColumns;
    }
}
4

1 回答 1

1

您需要覆盖onPostExecute异步任务SearchDaMovies才能实际使用arrayS. 它在doInBackground完成后调用。

@Override
protected void onPostExecute(String[] result) {
    // result is your arrayS
    // Perform actions with it
}
于 2013-06-14T02:27:21.170 回答