2
  1. 我正在尝试在 android 中下载文件并在进度条中显示下载进度

    1. 在 textview 中显示下载速度
    2. 在 textview 中显示文件的大小

    在下载文件时

我已经能够同时显示进度条,但是在 for 循环中,在我运行代码的那一刻给我错误:NullPointerExceptoin。但没有说它在哪一行也给了我FileNotFoundException。而且我不知道我做错了什么。我对 Android 很陌生,所以如果有人可以提供帮助,那就太好了。这是代码。我已经在清单文件中提供了权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
     <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

这是活动,我只使用这个活动。

public class DownloadActivity extends Activity implements OnClickListener {

    TextView view1;
    TextView view2;
    TextView view3;
    ProgressBar bar;
    Button startButton;
    String contents;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        startButton = (Button) findViewById(R.id.button1);
        bar = (ProgressBar) findViewById(R.id.progressBar1);
        startButton.setOnClickListener((OnClickListener) this);
//        contents = urlToString("https://www.dropbox.com/home/Music/FOX%20-%20Pokazn%D0%BE%CC%81%20(2012)");
        contents = "http://sdlc-esd.sun.com/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe?AuthParam=1355055216_89a14482cb59e95946db732dc4341468&GroupName=JSC&FilePath=/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe&File=jre-7u9-windows-i586.exe&BHost=javadl.sun.com";
        urlToString(contents);
//        http://ipv4.download.thinkbroadband.com/10MB.zip
//        http://sdlc-esd.sun.com/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe?AuthParam=1355055216_89a14482cb59e95946db732dc4341468&GroupName=JSC&FilePath=/ESD6/JSCDL/jdk/7u9-b05/jre-7u9-windows-i586.exe&File=jre-7u9-windows-i586.exe&BHost=javadl.sun.com
    }


    public void onClick(View view) {

        // detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            new LongOperation().execute(1000 + "");
            break;
        }
    }

    private class LongOperation extends AsyncTask<String, Integer, String> {


        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL(sUrl[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a typical 0-100% progress bar
                int fileLength = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(contents);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) 
                {
                    total += count;
                    // publishing the progress.... triggers the onProgressUpdate!
                    publishProgress((int) (total * 100 / fileLength));

                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }

            for (int i = 0; i < 100; i++) {
                try {


                    Thread.sleep(500);
                     publishProgress(i+1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "URL:" + contents;
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.textView1);
            txt.setText(result);
        }

        @Override
          protected void onProgressUpdate(Integer... values) {
           // TODO Auto-generated method stub
            bar.setProgress(values[0]);
            view1 = (TextView) findViewById(R.id.textView1);
            view2 = (TextView) findViewById(R.id.textView2);
            view3 = (TextView) findViewById(R.id.textView3);


            view1.setText("URL: " +  contents);
            view2.setText("File Size: "  + "x");
            view3.setText("Transfer Rate: "  + "y" );
          }
    }



//  Log.v("********", getLinkRate());

    private String urlToString(String address) {
        HttpURLConnection con = null;
        URL url;
        InputStream is = null;
        try {
            url = new URL(address);
            con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(10000);
            con.setConnectTimeout(15000);
            con.setRequestMethod("GET");
            con.connect();
            is = con.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);

                Log.d("*******", line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }
}

日志猫:

12-09 12:53:57.608: D/*******(824): Ty���mk�B$1�-2
12-09 12:53:57.648: D/dalvikvm(824): GC_FOR_MALLOC freed 202K, 62% free 7797K/20487K, external 1625K/2137K, paused 31ms
12-09 12:53:57.648: I/dalvikvm-heap(824): Forcing collection of SoftReferences for 7981588-byte allocation
12-09 12:53:57.669: D/dalvikvm(824): GC_FOR_MALLOC freed 1K, 62% free 7796K/20487K, external 1625K/2137K, paused 26ms
12-09 12:53:57.669: E/dalvikvm-heap(824): Out of memory on a 7981588-byte allocation.
12-09 12:53:57.669: I/dalvikvm(824): "main" prio=5 tid=1 RUNNABLE
12-09 12:53:57.678: I/dalvikvm(824):   | group="main" sCount=0 dsCount=0 obj=0x4001f1a8 self=0xce48
12-09 12:53:57.678: I/dalvikvm(824):   | sysTid=824 nice=0 sched=0/0 cgrp=default handle=-1345006528
12-09 12:53:57.678: I/dalvikvm(824):   | schedstat=( 6672852716 8933397811 8674 )
12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:~95)
12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:153)
12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.StringBuilder.append(StringBuilder.java:217)
12-09 12:53:57.678: I/dalvikvm(824):   at tees.ac.uk.L1087591.DownloadActivity.urlToString(DownloadActivity.java:156)
12-09 12:53:57.678: I/dalvikvm(824):   at tees.ac.uk.L1087591.DownloadActivity.onClick(DownloadActivity.java:54)
12-09 12:53:57.678: I/dalvikvm(824):   at android.view.View.performClick(View.java:2485)
12-09 12:53:57.678: I/dalvikvm(824):   at android.view.View$PerformClick.run(View.java:9080)
12-09 12:53:57.678: I/dalvikvm(824):   at android.os.Handler.handleCallback(Handler.java:587)
12-09 12:53:57.678: I/dalvikvm(824):   at android.os.Handler.dispatchMessage(Handler.java:92)
12-09 12:53:57.678: I/dalvikvm(824):   at android.os.Looper.loop(Looper.java:123)
12-09 12:53:57.678: I/dalvikvm(824):   at android.app.ActivityThread.main(ActivityThread.java:3683)
12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.reflect.Method.invokeNative(Native Method)
12-09 12:53:57.678: I/dalvikvm(824):   at java.lang.reflect.Method.invoke(Method.java:507)
12-09 12:53:57.678: I/dalvikvm(824):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-09 12:53:57.678: I/dalvikvm(824):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-09 12:53:57.678: I/dalvikvm(824):   at dalvik.system.NativeStart.main(Native Method)
12-09 12:53:57.688: D/AndroidRuntime(824): Shutting down VM
12-09 12:53:57.688: W/dalvikvm(824): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-09 12:53:57.688: E/AndroidRuntime(824): FATAL EXCEPTION: main
12-09 12:53:57.688: E/AndroidRuntime(824): java.lang.OutOfMemoryError
12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:153)
12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.StringBuilder.append(StringBuilder.java:217)
12-09 12:53:57.688: E/AndroidRuntime(824):  at tees.ac.uk.L1087591.DownloadActivity.urlToString(DownloadActivity.java:156)
12-09 12:53:57.688: E/AndroidRuntime(824):  at tees.ac.uk.L1087591.DownloadActivity.onClick(DownloadActivity.java:54)
12-09 12:53:57.688: E/AndroidRuntime(824):  at android.view.View.performClick(View.java:2485)
12-09 12:53:57.688: E/AndroidRuntime(824):  at android.view.View$PerformClick.run(View.java:9080)
12-09 12:53:57.688: E/AndroidRuntime(824):  at android.os.Handler.handleCallback(Handler.java:587)
12-09 12:53:57.688: E/AndroidRuntime(824):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-09 12:53:57.688: E/AndroidRuntime(824):  at android.os.Looper.loop(Looper.java:123)
12-09 12:53:57.688: E/AndroidRuntime(824):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.reflect.Method.invokeNative(Native Method)
12-09 12:53:57.688: E/AndroidRuntime(824):  at java.lang.reflect.Method.invoke(Method.java:507)
12-09 12:53:57.688: E/AndroidRuntime(824):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-09 12:53:57.688: E/AndroidRuntime(824):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-09 12:53:57.688: E/AndroidRuntime(824):  at dalvik.system.NativeStart.main(Native Method)
12-09 12:53:59.688: I/Process(824): Sending signal. PID: 824 SIG: 9
4

4 回答 4

1

您必须调试您的活动以找出哪一行引发 NullPointerException。

于 2012-12-09T12:34:25.213 回答
1

在您的 OnCreate 函数中,您正在使用一种名为 urlToString 的方法,该方法创建一个 HTTPURLConnection,如果您在 4.0 以上运行它,那么您的代码将崩溃,因为 HHTP 连接应该在后台线程而不是主线程中处理

于 2012-12-09T12:39:47.323 回答
1

检查您正在运行的代码是否实际通过try{}catch(){}块,然后才继续执行其余代码,因为如果找不到文件,您应该停止 AsyncTask 并显示错误消息

你正在像这样调用你的 AsyncTask

new LongOperation().execute(1000 + "");

所以你是1000 + ""作为 url 参数传递的?当您像这样声明 AsyncTAsk

private class LongOperation extends AsyncTask<String, Integer, String>

您假设将 String 作为参数传递,您将 Integer 作为 onProgressUpdate() 的进度,最后将 String 作为 AsyncTask 的结果

你也不能在onCreate()你调用的主线程上有网络

urlToString(contents);
于 2012-12-09T12:43:14.577 回答
1

您正在使用“new LongOperation().execute(1000 + "")”启动 AsyncTask,因此字符串“1000”被传递给 doInBackground 方法,然后您使用字符串“1000”启动了一个 URLConnection,但是“1000”是无效的网址。也许这就是错误。

于 2012-12-09T12:56:49.283 回答