如何在android gridview中解决我被拒绝的执行异常?

时间:2013-10-29 04:47:18

标签: android

         public class TopMovie extends Activity  
        {
            GridView lv;
           Vibrator vibrator;
    Dialog dialog;
    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        Log.i("Category", MainActivity.movie_Category);`enter code here`
        setContentView(R.layout.new_movie);
        setProgressBarIndeterminateVisibility(true);
        setProgressBarIndeterminateVisibility(false);
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        lv = (GridView) findViewById(R.id.grid_view);

        // URL to the JSON data
        String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
                + MainActivity.movie_Category + "&sub_category=other";
        DownloadTask downloadTask = new DownloadTask();
        downloadTask.execute(strUrl);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // // TODO Auto-generated method stub
                vibrator.vibrate(40);
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.customtoast,
                        (ViewGroup) findViewById(R.id.custom_toast_layout));
                Toast toast = new Toast(getApplicationContext());
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.setView(view);
                toast.show();
                MainActivity.movie_Id = ((TextView) arg1
                        .findViewById(R.id.tv_girdview_content_id)).getText()
                        .toString();
                Log.i("Name is", MainActivity.movie_Id);
                startActivity(new Intent(TopMovie.this, MovieDescription.class));
            }
        });
    }


    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception while downloading url", e.toString());
        } finally {
            iStream.close();
        }

        return data;
    }

    protected void onPreExecute() {
        // SHOW THE SPINNER WHILE LOADING FEEDS
//      linlaHeaderProgress.setVisibility(View.VISIBLE);
        //super.onPreExecute();
        dialog=dialog=ProgressDialog.show(TopMovie.this,"", "Loading...", true);
    }
    /** AsyncTask to download json data */
    private class DownloadTask extends AsyncTask<String, Integer, String> {
        String data = null;

        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);

            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {

            // The parsing of the xml data is done in a non-ui thread
            ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

            // Start parsing xml data
            listViewLoaderTask.execute(result);

        }
    }

    /** AsyncTask to parse json data and load ListView */
    private class ListViewLoaderTask extends
            AsyncTask<String, Void, SimpleAdapter> {

        JSONObject jObject;

        // Doing the parsing of xml data in a non-ui thread
        @Override
        protected SimpleAdapter doInBackground(String... strJson) {
            try {
                jObject = new JSONObject(strJson[0]);
                MovieParser countryJsonParser = new MovieParser();
                countryJsonParser.parse(jObject);
            } catch (Exception e) {
                Log.d("JSON Exception1", e.toString());
            }

            // Instantiating json parser class
            MovieParser countryJsonParser = new MovieParser();

            // A list object to store the parsed countries list
            List<HashMap<String, Object>> countries = null;

            try {
                // Getting the parsed data as a List construct
                countries = countryJsonParser.parse(jObject);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }

            // Keys used in Hashmap
            String[] from = { "image", "id", "year", "duration", "name" };

            // Ids of views in listview_layout
            // int[] to = {
            // R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
            int[] to = { R.id.iv_girdview_content_image,
                    R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
                    R.id.tv_girdview_content_listner,
                    R.id.tv_girdview_content_name };

            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
                    countries, R.layout.grid_view_content, from, to);

            return adapter;
        }

        /** Invoked by the Android on "doInBackground" is executed */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {

            // Setting adapter for the listview
            lv.setAdapter(adapter);
         // Setting adapter for the listview
                    if(dialog!=null)
                        dialog.dismiss();
            for (int i = 0; i < adapter.getCount(); i++) {
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter
                        .getItem(i);
                String imgUrl = (String) hm.get("flag_path");
                ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

                HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                hm.put("flag_path", imgUrl);
                hm.put("position", i);

                // Starting ImageLoaderTask to download and populate image in
                // the listview
                imageLoaderTask.execute(hm);


        }
    }

    /** AsyncTask to download and load an image in ListView */
    private class ImageLoaderTask extends
            AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {

        @Override
        protected HashMap<String, Object> doInBackground(
                HashMap<String, Object>... hm) {

            InputStream iStream = null;
            String imgUrl = (String) hm[0].get("flag_path");
            int position = (Integer) hm[0].get("position");

            URL url;
            try {
                url = new URL(imgUrl);

                // Creating an http connection to communicate with url
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();

                // Connecting to url
                urlConnection.connect();

                // Reading data from url
                iStream = urlConnection.getInputStream();

                // Getting Caching directory
                File cacheDirectory = getBaseContext().getCacheDir();

                // Temporary file to store the downloaded image
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
                        + position + ".png");

                // The FileOutputStream to the temporary file
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                // Creating a bitmap from the downloaded inputstream
                Bitmap b = BitmapFactory.decodeStream(iStream);

                // Writing the bitmap to the temporary file as png file
                b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);

                // Flush the FileOutputStream
                fOutStream.flush();

                // Close the FileOutputStream
                fOutStream.close();

                // Create a hashmap object to store image path and its position
                // in the listview
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

                // Storing the path to the temporary image file
                hmBitmap.put("image", tmpFile.getPath());

                // Storing the position of the image in the listview
                hmBitmap.put("position", position);

                // Returning the HashMap object containing the image path and
                // position
                return hmBitmap;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HashMap<String, Object> result) {
            // Getting the path to the downloaded image
            String path = (String) result.get("image");

            // Getting the position of the downloaded image
            int position = (Integer) result.get("position");

            // Getting adapter of the listview
            SimpleAdapter adapter = (SimpleAdapter) lv.getAdapter();

            // Getting the hashmap object at the specified position of the
            // listview
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter
                    .getItem(position);

            // Overwriting the existing path in the adapter
            hm.put("image", path);
            adapter.notifyDataSetChanged();
        }
    }
}}

我有一个gridview,其中的项目来自json ..,有时我的应用程序运行但有时在“imageLoaderTask.execute(hm);”中给出了REJECTED EXECUTION EXECPTION,我无法理解如何解决这个问题。我有尝试了所有的例子和condiotions.i在我的代码中使用了asynchtask,自定义adapetr,但我的代码中没有解决方案和答案。我怎样才能解决我的错误。请帮助我...... :(

2 个答案:

答案 0 :(得分:0)

首先,您必须了解RejectedExecutionException的含义。然后决定你想如何处理它。

AsyncTaskExecutor中运行其任务。此执行程序使用存储任务的队列,直到执行程序可以自由地关注它们。具有默认任务的默认执行程序可以同时处理10个任务,并在运行完成后执行10个额外任务。一旦完成所有这20个任务(10 + 10)的任务,它就不能再执行任务了,它会通过提出RejectedExecutionException来告诉您。

你怎么处理这个?取决于你需要什么。您可以捕获该异常并稍后再次尝试查看队列是否有空间,或者您可以使用不同配置的执行程序(a)可以同时执行更多任务或(b)具有更多空间的队列任务。一些已经存在的执行程序类可以配置更适合您需要的参数(请参阅Executor的文档),或者您可以编写自己的。一个这样的执行器是ThreadPoolExecutor,你可以告诉我们使用什么类型的队列(这是在某些Android版本中使用的执行器,你没有指定你正在使用哪个版本)。在文档中讨论了有哪些类型的队列。

同样,关于如何配置执行程序和队列的决定取决于您和您的需求。如果你想允许无限制的线程创建,或者有限制。想拥有一长串任务或简短,甚至无约束。

答案 1 :(得分:0)

试试这个..

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)     
    imageLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, hm);          
else
    imageLoaderTask.execute(hm);

适用于所有AsyncTask