【问题标题】:Load Images Into ImageAdapter through JSON通过 JSON 将图像加载到 ImageAdapter
【发布时间】:2014-03-04 05:54:41
【问题描述】:

嗨,我正在尝试GridView 演示这个link

它工作得很好,但现在我想获取服务器数据库的图像。为此,我实现了处理程序类,它将传递我的 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)

【问题讨论】:

    标签: android json gridview baseadapter


    【解决方案1】:

    删除这一行

     img =new ImageAdapter(mContext);
    

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

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

    【讨论】:

    • 谢谢它的工作,错误得到解决..现在我得到了我在“Log.d("Response: ", ">"+jsonstr);" 中显示的图像 URL但是我无法在 imageurls 数组中获取该图像..我错了..??
    • @Aksh 如果您有任何新的疑问,可以询问New Question
    猜你喜欢
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2012-04-15
    相关资源
    最近更新 更多