通过JSON将图像加载到ImageAdapter中

时间:2014-03-04 05:54:42

标签: android json gridview baseadapter

我正在尝试此link

GridView演示版

它工作精湛,但现在我想获取服务器数据库的图像。为此我实现了处理程序类,它将传递我的URL并从服务器获取响应。作为回应,JSON将包含图像的URL。我还实现了一个方法,它将从结果URL下载图像并将它们设置为Bitmap数组。 服务处理程序类工作正常但我不知道我在ImageAdapter类中所做的更改是否正确。请告诉我我哪里出错了.. 以下是ImageAdapter类的代码..

        public class ImageAdapter extends BaseAdapter {
        private Context mContext;
        Bitmap bm[]=new Bitmap[8];
        ImageAdapter img;
        public String[] imageurls=null;

        // Keep all Images in array
        public Integer[] mThumbIds ={
                R.drawable.pic_1, R.drawable.pic_2,
                R.drawable.pic_3, R.drawable.pic_4,
        };


        // Constructor
        public ImageAdapter(Context c){
            mContext = c;
            img =new ImageAdapter(mContext);
            new GetImageUrls(mContext).execute();

        }

        @Override
        public int getCount() {
            return mThumbIds.length;
        }

        @Override
        public Object getItem(int position) {
            return mThumbIds[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {         
            ImageView imageView = new ImageView(mContext);
            if(bm[position]==null)
                    imageView.setImageResource(mThumbIds[position]);
            else
                imageView.setImageBitmap(bm[position]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
            return imageView;
        }


        public class GetImageUrls  extends AsyncTask<Void, Void, Void>
        {
            Context context;
            private ProgressDialog pDialog;
            // URL to get JSON
            private static final String url= "http://192.xxx.x.xxx/Demo_Folder/test.json";
            private static final String RESULT = "mainCategory";
            private static final String URLS = "mcatimage";
            // JSONArray
            JSONArray loginjsonarray=null;
            //result from url
            //public String[] imageurls=null;

            public GetImageUrls(Context c) {
                this.context=c;
            }

            protected void onPreExecute() {
                // Showing progress dialog
                pDialog = new ProgressDialog(context);
                pDialog.setMessage("Loading...");
                pDialog.setCancelable(false);
                //pDialog.show();
            }
            protected Void doInBackground(Void... arg) {
                // Creating service handler class instance
                ServiceHandler sh = new ServiceHandler();
                 // Making a request to url and getting response
                String jsonstr = sh.makeServiceCall(url, ServiceHandler.GET, null);
                Log.d("Response: ", ">"+jsonstr);
                if(jsonstr!=null){
                    try {
                            JSONObject jsonObj =new JSONObject(jsonstr);
                            loginjsonarray=jsonObj.getJSONArray(RESULT);
                            for(int i=0;i<loginjsonarray.length();i++){
                                JSONObject l=loginjsonarray.getJSONObject(i);
                                imageurls[i]=l.getString(URLS);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                }else{
                    Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
                }
                return null;
            }

            protected void onPostExecute(Integer result) {
                // Dismiss the progress dialog
                if(pDialog.isShowing()){
                    pDialog.dismiss();
                    new  ImageDownloader().execute();
                }

            }
        }

        private class ImageDownloader extends AsyncTask<Integer, Integer, String>
        {
            Context context;
            private ProgressDialog pDialog;
            @Override
            public void onPreExecute()
            {
                // Showing progress dialog
                pDialog = new ProgressDialog(context);
                pDialog.setMessage("Loading...");
                pDialog.setCancelable(false);
                //pDialog.show();
            }

            protected void onPostExecute(String result)
            {
                pDialog.hide();
            }
              protected void onProgressUpdate(Integer... progress) {
                  img.notifyDataSetChanged();
                 }
            protected String doInBackground(Integer... a)
            {
                for(int i=0;i<4;i++)
                {
                    bm[i]=downloadBitmap(imageurls[i]);
                    this.publishProgress(i);
                }
                return "";
            }
        }

        Bitmap downloadBitmap(String url) {

            final HttpClient client = new DefaultHttpClient();
            final HttpGet getRequest = new HttpGet(url);

            try {
                HttpResponse response = client.execute(getRequest);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) { 
                    Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
                    return null;
                }

                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = null;
                    try {
                        inputStream = entity.getContent(); 
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();  
                        }
                        entity.consumeContent();
                    }
                }
            } catch (Exception e) {
                // Could provide a more explicit error message for IOException or IllegalStateException
                getRequest.abort();
                Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
            } finally {
                if (client != null) {
                    //client.
                }
            }
            return null;
        }

    }

当我运行代码时,它立即停止......并给出错误,如

FATAL EXCEPTION: main
Process: com.example.androidhive, PID: 1383
java.lang.StackOverflowError
at java.util.AbstractList.<init>(AbstractList.java:376)
at java.util.ArrayList.<init>(ArrayList.java:81)
at android.database.Observable.<init>(Observable.java:34)
at android.database.DataSetObservable.<init>(DataSetObservable.java:24)
at android.widget.BaseAdapter.<init>(BaseAdapter.java:31)
at com.example.androidhive.ImageAdapter.<init>(ImageAdapter.java:40)

1 个答案:

答案 0 :(得分:2)

删除此行

 img =new ImageAdapter(mContext);

来自ImageAdapter的构造函数。它正在尝试创建无限数量的ImageAdapter个实例,导致StackOverflowError ...

为什么在ImageAdapter中需要ImageAdapter的另一个实例?