2013-03-08 4 views
0

ListView 컨트롤을 사용하여 다운로드 응용 프로그램을 구현했습니다. 응용 프로그램을 실행할 때 NullPointerException 오류가 발생합니다.응용 프로그램을 실행할 때 NullPointer 예외가 발생합니다

아래 :: 내 코드

public class TestDownload 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_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 = 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); } }); 
         */ 

         TestDownload.this.runOnUiThread(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 = "http://imprintingdesign.com/hiren_testing/TestHopeNew/testHope/data/url.json"; 
      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 
      View view = null; 
      if (convertView == null) { 
       LayoutInflater inflater = (LayoutInflater) mContext 
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       view = inflater.inflate(R.layout.activity_column, null); 
       final ViewHolder viewHolder = new ViewHolder(); 
       viewHolder.imageView = (ImageView) view 
         .findViewById(R.id.ColImgPath); 

       viewHolder.txtStatus = (TextView) view 
         .findViewById(R.id.ColStatus); 
       viewHolder.txtHidden = (TextView) view.findViewById(R.id.Txtv); 
       viewHolder.btnDownload = (Button) view 
         .findViewById(R.id.btnDownload); 

       viewHolder.btnView = (Button) view.findViewById(R.id.btnView); 

       viewHolder.progress = (ProgressBar) view 
         .findViewById(R.id.progressBar); 
       // ColImage 

       viewHolder.imageView.getLayoutParams().height = 110; 
       viewHolder.imageView.getLayoutParams().width = 110; 
       viewHolder.imageView.setPadding(10, 10, 10, 10); 
       viewHolder.imageView 
         .setScaleType(ImageView.ScaleType.CENTER_CROP); 
       try { 

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

       viewHolder.txtStatus.setPadding(10, 0, 0, 0); 
       viewHolder.txtStatus.setText("..."); 

       viewHolder.txtHidden.setVisibility(View.GONE); 
       viewHolder.txtHidden.setText(String.valueOf(position)); 

       viewHolder.btnDownload.setTextColor(Color.RED); 
       viewHolder.btnDownload 
         .setOnClickListener(new View.OnClickListener() { 
          public void onClick(View v) { 
           // Download 
           viewHolder.btnDownload.setEnabled(false); 
           viewHolder.btnDownload.setTextColor(Color.GRAY); 
           startDownload(position); 
          } 
         }); 

       viewHolder.btnView.setEnabled(false); 
       viewHolder.btnView.setTextColor(Color.GRAY); 
       viewHolder.btnView 
         .setOnClickListener(new View.OnClickListener() { 
          public void onClick(View v) { 
           ViewVideoDelete(position); 
           viewHolder.btnDownload.setEnabled(true); 
           updateStatus(position, 0); 
          } 
         }); 

       viewHolder.progress.setPadding(10, 0, 0, 0); 

       viewHolder.imageView.setTag(MyArrList.get(position)); 
       viewHolder.txtStatus.setTag(MyArrList.get(position)); 
       viewHolder.txtHidden.setTag(MyArrList.get(position)); 
       viewHolder.btnDownload.setTag(MyArrList.get(position)); 
       viewHolder.btnView.setTag(MyArrList.get(position)); 
       viewHolder.progress.setTag(MyArrList.get(position)); 

       view.setTag(viewHolder); 

      } else { 
       view = convertView; 
       ((ViewHolder) view.getTag()).imageView.setTag(MyArrList 
         .get(position)); 
       ((ViewHolder) view.getTag()).txtStatus.setTag(MyArrList 
         .get(position)); 
       ((ViewHolder) view.getTag()).txtHidden.setTag(MyArrList 
         .get(position)); 
       ((ViewHolder) view.getTag()).btnDownload.setTag(MyArrList 
         .get(position)); 
       ((ViewHolder) view.getTag()).btnView.setTag(MyArrList 
         .get(position)); 
       ((ViewHolder) view.getTag()).progress.setTag(MyArrList 
         .get(position)); 

      } 
      ViewHolder holder = (ViewHolder) view.getTag(); 
      holder.imageView.getLayoutParams().height = 110; 
      holder.imageView.getLayoutParams().width = 110; 
      holder.imageView.setPadding(10, 10, 10, 10); 
      holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
      try { 

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

      holder.txtStatus.setPadding(10, 0, 0, 0); 
      holder.txtStatus.setText("..."); 

      holder.txtHidden.setVisibility(View.GONE); 
      holder.txtHidden.setText(String.valueOf(position)); 

      holder.btnDownload.setTextColor(Color.RED); 

      holder.btnView.setEnabled(false); 
      holder.btnView.setTextColor(Color.GRAY); 

      holder.progress.setPadding(10, 0, 0, 0); 

      return convertView; 

     } 
    } 

    static class ViewHolder { 
     protected ImageView imageView; 
     protected TextView txtStatus; 
     protected TextView txtHidden; 
     protected Button btnDownload; 
     protected Button btnView; 
     protected ProgressBar progress; 

    } 

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

} 

는 그리고 메인 XML의 코드 ::

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/tableLayout1" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <LinearLayout 
     android:id="@+id/main_lay" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:background="#437654" > 

     <Button 
      android:id="@+id/all_btn" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="BACk" /> 

     <TextView 
      android:id="@+id/accepted_all" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="DownLoad Video" /> 

     <Button 
      android:id="@+id/not_shown" 
      android:layout_width="100dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:text="All DOwnload" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.1" 
     android:orientation="horizontal" > 

     <ListView 
      android:id="@+id/listView1" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:focusable="false" > 
     </ListView> 
    </LinearLayout> 

</LinearLayout> 

을 사용 그리고

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:descendantFocusability="blocksDescendants" 
    android:orientation="horizontal" > 

    <ImageView 
     android:id="@+id/ColImgPath" 
     android:layout_width="50dp" 
     android:layout_height="50dp" /> 

    <TextView 
     android:id="@+id/Txtv" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:visibility="gone" 
     /> 

    <TableLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" > 

     <TableRow 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dip" > 

      <TextView 
       android:id="@+id/ColStatus" 
       android:text="Status" 
       android:textAppearance="?android:attr/textAppearanceSmall" /> 

      <ProgressBar 
       android:id="@+id/progressBar" 
       style="?android:attr/progressBarStyleHorizontal" 
       android:layout_width="100dp" 
       android:layout_height="wrap_content" /> 
     </TableRow> 

     <TableRow 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dip" > 

      <Button 
       android:id="@+id/btnDownload" 
       style="?android:attr/buttonStyleSmall" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Download" /> 

      <Button 
       android:id="@+id/btnView" 
       style="?android:attr/buttonStyleSmall" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Delete" /> 
     </TableRow> 
    </TableLayout> 

</LinearLayout> 

그리고 때를 손님 여러분 XML을 목록보기 행을 :: 사용 앱 시작을 시작하지만 아래에서 오류가 발생합니다.

03-08 10:51:59.757: E/AndroidRuntime(549): FATAL EXCEPTION: main 
03-08 10:51:59.757: E/AndroidRuntime(549): java.lang.NullPointerException 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.AbsListView.obtainView(AbsListView.java:1432) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.ListView.measureHeightOfChildren(ListView.java:1216) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.ListView.onMeasure(ListView.java:1127) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.View.measure(View.java:8313) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:701) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.onMeasure(LinearLayout.java:311) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.View.measure(View.java:8313) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:701) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.onMeasure(LinearLayout.java:311) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.View.measure(View.java:8313) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.View.measure(View.java:8313) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.View.measure(View.java:8313) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.View.measure(View.java:8313) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.ViewRoot.performTraversals(ViewRoot.java:839) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.os.Handler.dispatchMessage(Handler.java:99) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.os.Looper.loop(Looper.java:130) 
03-08 10:51:59.757: E/AndroidRuntime(549): at android.app.ActivityThread.main(ActivityThread.java:3683) 
03-08 10:51:59.757: E/AndroidRuntime(549): at java.lang.reflect.Method.invokeNative(Native Method) 
03-08 10:51:59.757: E/AndroidRuntime(549): at java.lang.reflect.Method.invoke(Method.java:507) 
03-08 10:51:59.757: E/AndroidRuntime(549): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 
03-08 10:51:59.757: E/AndroidRuntime(549): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
03-08 10:51:59.757: E/AndroidRuntime(549): at dalvik.system.NativeStart.main(Native Method) 
+0

() return 문을 변경할 수는'convertView를 반환' – Shoshi

+0

감사 서사하지만 돌아 covertView하지만 목록보기 항목이 표시되지 변경 .. !!! – crickpatel0024

+0

안녕하세요, 다운로드 버튼을 클릭하면 잘못된 코드가 표시되는 경우가 있습니다. – crickpatel0024

답변

0

ListAdapter.getView 메서드가 null을 반환 할 때 이러한 현상이 발생합니다. 이 경우에 귀하의 ImageAdapter 클래스가 , 즉 null 일 수 있습니다. 나는 convertView보다는 view을 반환한다는 의미라고 생각합니다. 반환보기`에`; 방법은 다음

+0

Replay를 주셔서 감사합니다 !!하지만 내 코드에서 변경 ConvertView에서보기를 바꾸지 만 ListView에서는 표시하지 않습니다! – crickpatel0024

0

보십시오, 당신의 getView에서

public View getView(final int position, View convertView, 
       ViewGroup parent) { 
      // TODO Auto-generated method stub 
      View view = null; 
      if (convertView == null) { 
       ...... 

       view.setTag(viewHolder); 

      } else { 
       view = convertView;  
       ... 
      } 
      ViewHolder holder = (ViewHolder) view.getTag(); 
      ..... 

      return convertView; // if convertView == null , where convertView is instanced?? 

     } 
    } 
+0

Replay Jake에게 감사하지만 변화는 무엇인가? 내 코드 그리고 뭐라고 말 할까 !! – crickpatel0024

+0

안녕 Raynold 나는 너의 길을 따른다 너는 나의 코드를 체크하지 않는다 너는 나에게 말하지 않는다 !! 적당한 해결책을 내놔 너는 내 잘못한 것을 확인해? – crickpatel0024

관련 문제