2013-03-05 3 views
1

listview입니다. 행 항목 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) 
아래 다음 응용 프로그램 충돌 누군 오류를 스크롤 한 후 다운로드 버튼을 클릭

답변

0

으로 스레드에서 ProgressBar의 업데이트 사용 Activity.runOnUiThread : 답장을

TestHopeDownload.this.runOnUiThread(new Runnable() { 
    public void run() { 
     updateStatus(position, Status); //<<<< call updateStatus method here 
    } 
}); 
+0

감사하지만 난 점점 핸들러하지만 오류 코드를 넣어 Nullpointer 저를 도와주세요 내 코드에 코드를 넣어 exception.where! – crickpatel0024

+0

@ crickpatel0024 : 처리기 코드를 제거하고 제안 된 코드를 배치하십시오. –

+0

내 코드는 변경하지만 같은 오류가 발생합니다 !!! crickpatel0024 @ – crickpatel0024