IOException解析Android

时间:2015-07-31 15:35:58

标签: java android parsing ioexception

我是Android开发和Java的新手。

我收到以下错误:

Could not load Bitmap from: /images/image.php.......

此代码块中出现错误:

public class JSONImageViewer extends Activity  {

    private GridView gridV;
    private ImageAdapter imageAdapter;

    public int currentPage = 1;
    public int TotalPage = 0;

    public Button btnNext;
    public Button btnPre;

    private final static String TAG_IMG = "CarImageLink";

    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();

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

        // ProgressBar
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.activitymain);

        // GridView and imageAdapter
        gridV = (GridView) findViewById(R.id.gridView1);
        gridV.setClipToPadding(false);
        imageAdapter = new ImageAdapter(getApplicationContext());
        gridV.setAdapter(imageAdapter);


        // Next
        btnNext = (Button) findViewById(R.id.btnNext);
        btnNext.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage + 1;
                ShowData();
            }
        });

        // Previous
       btnPre = (Button) findViewById(R.id.btnPre);
        btnPre.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage - 1;
                ShowData();
            }
        });

        // Show first load
        ShowData();

    }

    public void ShowData()
    {
        btnNext.setEnabled(false);
        btnPre.setEnabled(false);

        setProgressBarIndeterminateVisibility(true);
        new LoadContentFromServer().execute();
    }


    class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {

        @Override
        protected Object doInBackground(Object... params) {

           String url = "http://.....";

           //JSONArray data;
            JSONObject data;
            try {

                //data = new JSONArray(getJSONUrl(url));
                data = new JSONObject(getJSONUrl(url));
                JSONArray dataArray = data.getJSONArray("car_images");
                MyArrList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map;

                    /*
                     * TotalRows = Show for total rows
                     * TotalPage = Show for total page
                     */

                int displayPerPage = 9;   // Per Page
                int TotalRows = data.length();
                int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);

                if (TotalRows <= displayPerPage) {
                    TotalPage = 1;
                } else if ((TotalRows % displayPerPage) == 0) {
                    TotalPage = (TotalRows / displayPerPage);
                } else {
                    TotalPage = (TotalRows / displayPerPage) + 1;
                    TotalPage = (int) TotalPage;
                }
                int indexRowEnd = displayPerPage * currentPage;
                if (indexRowEnd > TotalRows) {
                    indexRowEnd = TotalRows;
                }

                for (int i = 0; i < dataArray.length(); i++) {
                  map = new HashMap<String, Object>();
                    JSONObject c = dataArray.getJSONObject(i);

                    // Thumbnail Get ImageBitmap To Object
                   Bitmap newBitmap = loadBitmap(c.getString(TAG_IMG));
                    map.put("CarImageLink", newBitmap);

                    MyArrList.add(map);
                    Log.v("MyArrList", MyArrList.toString());
                    publishProgress(i);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }


        @Override
        public void onProgressUpdate(Integer... progress) {
            imageAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onPostExecute(Object result) {

            // Disabled Button Next
            if(currentPage >= TotalPage) {
                btnNext.setEnabled(false);
            }
            else {
                btnNext.setEnabled(true);
            }

            // Disabled Button Previous
            if(currentPage <= 1) {
                btnPre.setEnabled(false);
            }
            else {
                btnPre.setEnabled(true);
            }

            setProgressBarIndeterminateVisibility(false); // When Finish
        }
    }


    class ImageAdapter extends BaseAdapter {

        private Context mContext;

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

        public int getCount() {
            return MyArrList.size();
        }

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

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

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

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


            if (convertView == null) {
                convertView = inflater.inflate(R.layout.activity_column, null);
            }


            // ColPhoto
            ImageView imageView = (ImageView) convertView.findViewById(R.id.ColPhoto);
            imageView.getLayoutParams().height = 60;
            imageView.getLayoutParams().width = 60;
            imageView.setPadding(5, 5, 5, 5);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try
            {
                imageView.setImageBitmap((Bitmap)MyArrList.get(position).get("CarImageLink"));
                Log.v("MyArrList2", MyArrList.toString());
            } catch (Exception e) {
                // When Error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            return convertView;

        }

    }

    /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url) {

        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();

            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) {
               // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;

                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    /***** Get Image Resource from URL  *****/
    private static final String TAG = "CarImageLink";
    private static final int IO_BUFFER_SIZE = 4 * 1024;

    public static Bitmap loadBitmap(String url) {

        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

为了数据完整性,我将限制显示的JSON解析数据和网址的数量。

我已经研究过这些错误并尝试应用解决方案但没有成功。

任何建议都表示赞赏。谢谢。

2 个答案:

答案 0 :(得分:0)

您收到的回复不是JSONArray,而是JSONObject。试试这个:new JSONObject(getJSONUrl(url));

答案 1 :(得分:0)

{&#34; car_images&#34;:[{&#34; Car ....}是JSONObject而不是JSONArray

您应该将数据更改为JSONObject

JSONObject data = new JSONObject(getJSONUrl(url));

然后你得到了数组:

JSONArray dataArray = data.getJSONArray("car_images");