1

当我单击下载按钮时,我有listview.in 行项目progressbar,2 按钮和一个图像视图,然后下载过程开始,但是当我向下滚动时应用程序崩溃以及当我向下滚动时如何listview在行项目中保存状态?我的代码如下:: :

public class TestHopeDownload extends Activity {
    private ListView lstView;
    private ImageAdapter imageAdapter;
    private Handler handler = new Handler();
    ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
    File download;
    public static final int DIALOG_DOWNLOAD_THUMBNAIL_PROGRESS = 0;
    String strDownloaDuRL;
    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_hope_download);
        new LoadContentFromServer().execute();

    }

    public void ShowThumbnailData() {
        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listView1);
        lstView.setClipToPadding(false);
        list = DBAdpter.getUrl_Detail();
        imageAdapter = new ImageAdapter(getApplicationContext());
        lstView.setAdapter(imageAdapter);
    }

    public void startDownload(final int position) {

        Runnable runnable = new Runnable() {
            int Status = 0;

            public void run() {

                // String urlDownload = list.get(position).url_video;
                String urlDownload = MyArrList.get(position)
                        .get("VideoPathThum").toString();
                Log.v("log_tag", "urlDownload   ::: " + urlDownload);

                int count = 0;
                try {

                    URL url = new URL(urlDownload);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();

                    int lenghtOfFile = conexion.getContentLength();
                    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                    InputStream input = new BufferedInputStream(
                            url.openStream());

                    // Get File Name from URL
                    String fileName = urlDownload.substring(
                            urlDownload.lastIndexOf('/') + 1,
                            urlDownload.length());
                    download = new File(
                            Environment.getExternalStorageDirectory()
                                    + "/download/");
                    if (!download.exists()) {
                        download.mkdir();
                    }
                    strDownloaDuRL = download + "/" + fileName;
                    OutputStream output = new FileOutputStream(strDownloaDuRL);

                    byte data[] = new byte[1024];
                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        Status = (int) ((total * 100) / lenghtOfFile);
                        output.write(data, 0, count);

                        // Update ProgressBar
                        handler.post(new Runnable() {
                            public void run() {
                                updateStatus(position, Status);
                            }
                        });

                    }

                    output.flush();
                    output.close();
                    input.close();

                } catch (Exception e) {
                }

            }
        };
        new Thread(runnable).start();
    }

    private void updateStatus(int index, int Status) {

        View v = lstView.getChildAt(index - lstView.getFirstVisiblePosition());

        // Update ProgressBar
        ProgressBar progress = (ProgressBar) v.findViewById(R.id.progressBar);
        progress.setProgress(Status);

        // Update Text to ColStatus
        TextView txtStatus = (TextView) v.findViewById(R.id.ColStatus);
        txtStatus.setPadding(10, 0, 0, 0);
        txtStatus.setText("Load : " + String.valueOf(Status) + "%");

        // Enabled Button View
        if (Status >= 100) {
            Button btnView = (Button) v.findViewById(R.id.btnView);
            btnView.setTextColor(Color.RED);
            btnView.setEnabled(true);
        }
    }





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

        protected void onPreExecute() {
            super.onPreExecute();

        }

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

            HashMap<String, Object> map;
            String url = "***** url******";
            String result = "";
            InputStream is = null;
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            // http post
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            try {
                JSONObject json_obj = new JSONObject(result);
                JSONArray j_Arr_fn = json_obj.getJSONArray("children");

                for (int i = 0; i < j_Arr_fn.length(); i++) {
                    JSONObject json_objs = j_Arr_fn.getJSONObject(i);
                    Url_Dto proDto = new Url_Dto();
                    proDto.url_video = json_objs.getString("videoUrl");
                    map = new HashMap<String, Object>();
                    map.put("VideoPathThum", proDto.url_video);
                    MyArrList.add(map);
                }

            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }

            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            ShowThumbnailData();

        }
    }

    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(final 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);
            }

            // ColImage
            ImageView imageView = (ImageView) convertView
                    .findViewById(R.id.ColImgPath);
            imageView.getLayoutParams().height = 110;
            imageView.getLayoutParams().width = 110;
            imageView.setPadding(10, 10, 10, 10);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try {

                imageView.setImageResource(list.get(position).images[position]);
            } catch (Exception e) {
                // When Error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);

            }

            // ColStatus
            TextView txtStatus = (TextView) convertView
                    .findViewById(R.id.ColStatus);
            txtStatus.setPadding(10, 0, 0, 0);
            txtStatus.setText("...");

            // btnDownload
            final Button btnDownload = (Button) convertView
                    .findViewById(R.id.btnDownload);
            btnDownload.setTextColor(Color.RED);
            btnDownload.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // Download
                    btnDownload.setEnabled(false);
                    btnDownload.setTextColor(Color.GRAY);
                    startDownload(position);
                    pbs.setDl(1);

                }
            });

            // btnView
            Button btnView = (Button) convertView.findViewById(R.id.btnView);
            btnView.setEnabled(false);
            btnView.setTextColor(Color.GRAY);
            btnView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    ViewVideoDelete(position);

                }
            });

            // progressBar
            ProgressBar progress = (ProgressBar) convertView
                    .findViewById(R.id.progressBar);
            progress.setPadding(10, 0, 0, 0);
            return convertView;

        }

    }

    public void ViewVideoDelete(int position) {
        String urlDownload = MyArrList.get(position).get("VideoPathThum")
                .toString();

        String fileName = urlDownload.substring(
                urlDownload.lastIndexOf('/') + 1, urlDownload.length());
        download = new File(Environment.getExternalStorageDirectory()
                + "/download/");

        String strPath = download + "/" + fileName;
        Log.v("log_tag", "fileNameDElete :: " + strPath);
        File delete = new File(strPath);
        delete.delete();
    }

}

然后我点击下载按钮然后我向下滚动然后应用程序崩溃。我的错误在下面::

03-05 14:39:15.301: E/AndroidRuntime(4481): FATAL EXCEPTION: main
03-05 14:39:15.301: E/AndroidRuntime(4481): java.lang.NullPointerException
03-05 14:39:15.301: E/AndroidRuntime(4481):     at com.example.testhopedownload.TestHopeDownload.updateStatus(TestHopeDownload.java:142)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at com.example.testhopedownload.TestHopeDownload.access$1(TestHopeDownload.java:137)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at com.example.testhopedownload.TestHopeDownload$1$1.run(TestHopeDownload.java:119)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at android.os.Handler.handleCallback(Handler.java:587)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at android.os.Looper.loop(Looper.java:130)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at java.lang.reflect.Method.invokeNative(Native Method)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at java.lang.reflect.Method.invoke(Method.java:507)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-05 14:39:15.301: E/AndroidRuntime(4481):     at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

0

使用 Activity.runOnUiThread将 ProgressBar 从 Thread 更新为:

TestHopeDownload.this.runOnUiThread(new Runnable() {
    public void run() {
         updateStatus(position, Status); //<<<< call updateStatus method here
    }
});
于 2013-03-05T09:25:51.223 回答