0

我已经使用 ListView 控件实现了一个下载应用程序但是当我运行该应用程序时NullPointerException出现错误。

我的代码如下::

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

}

我使用了 Main Xml Code::

<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>

我使用了Custome Xml List View Row::

<?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>

当我在下面运行 App NOT Start But Get Error 时:

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)
4

2 回答 2

0

当您的ListAdapter.getView方法返回时会发生这种情况null。在这种情况下,我看到您的ImageAdapter课程正在返回convertView,这可能是null。我认为这意味着返回view而不是返回convertView

于 2013-03-08T05:35:17.743 回答
0

尝试以下方式,

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??

        }
    }
于 2013-03-08T05:45:05.130 回答