0

我尝试下载文件并将其保存在内部存储中。这是我的代码:

public class PLSParser {

public String pls_path;
public String pls_content;

public PLSParser () {
    pls_path = "http://rhemafm.serverroom.us:5858/listen.pls";
}

public void getPLSFile () {
    try {
        URL url = new URL (pls_path);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("GET");
        con.setDoOutput(true);
        con.connect();

        File cacheDir = Environment.getDataDirectory();
        File storage = new File (cacheDir, "temp.dat");

        InputStream in = new BufferedInputStream (url.openStream());
        OutputStream out = new FileOutputStream(storage);

        int downloaded = 0;
        byte[] buff = new byte[1024];
        int buffLength = 0;

        while ((buffLength = in.read(buff)) != -1) {
            out.write(buff, 0, buffLength);
            downloaded += buffLength;
        }

        out.flush();
        out.close();
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
 }
}

问题是,它总是会出错。我犯了什么错误?


编辑:

public class PLSParser {

    PLSParser () {}

    void getFile() {
        String url = "http://rhemafm.serverroom.us:5858/listen.pls";
        new DownloadFileAsync().execute(url);
    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... aurl) {
            int count;

            try {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lengthOfFile = conexion.getContentLength();

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream("/temporary_pls.pls");

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

                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

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

        }
    }
}

这段代码仍然有错误......我该怎么办?


编辑2:

07-16 09:19:23.260: WARN/dalvikvm(717): threadid=3: thread exiting with uncaught exception (group=0x4001aa28)
07-16 09:19:23.260: ERROR/AndroidRuntime(717): Uncaught handler: thread main exiting due to uncaught exception
07-16 09:19:23.299: ERROR/AndroidRuntime(717): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.radio.streamingradio/com.radio.streamingradio.Tune_in}: java.lang.RuntimeException: Binary XML file line #50: You must supply a layout_width attribute.
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.os.Looper.loop(Looper.java:123)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.ActivityThread.main(ActivityThread.java:4203)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at java.lang.reflect.Method.invokeNative(Native Method)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at java.lang.reflect.Method.invoke(Method.java:521)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at dalvik.system.NativeStart.main(Native Method)
07-16 09:19:23.299: ERROR/AndroidRuntime(717): Caused by: java.lang.RuntimeException: Binary XML file line #50: You must supply a layout_width attribute.
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:438)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:3433)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:3513)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.widget.LinearLayout$LayoutParams.<init>(LinearLayout.java:1265)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1191)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:45)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:619)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:313)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.Activity.setContentView(Activity.java:1620)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at com.radio.streamingradio.Tune_in.onCreate(Tune_in.java:24)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
07-16 09:19:23.299: ERROR/AndroidRuntime(717):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)

这是我的 logCat 错误。


编辑 3: @lbyrdie:啊,感谢您的解决方案。我已经添加了布局属性并设法达到了目的。但是每当我尝试按下下载按钮时,它仍然会出错。这是我的 logCat:

07-16 10:19:04.930: ERROR/AndroidRuntime(998): Uncaught handler: thread main exiting due to uncaught exception
07-16 10:19:04.950: ERROR/AndroidRuntime(998): java.lang.NullPointerException
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.radio.streamingradio.PLSParser.<init>(PLSParser.java:17)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.radio.streamingradio.Tune_in.onClick(Tune_in.java:41)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.View.performClick(View.java:2344)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.View.onTouchEvent(View.java:4133)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.widget.TextView.onTouchEvent(TextView.java:6504)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.View.dispatchTouchEvent(View.java:3672)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1712)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1202)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.app.Activity.dispatchTouchEvent(Activity.java:1987)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1696)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1658)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.os.Looper.loop(Looper.java:123)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at android.app.ActivityThread.main(ActivityThread.java:4203)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at java.lang.reflect.Method.invokeNative(Native Method)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at java.lang.reflect.Method.invoke(Method.java:521)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
07-16 10:19:04.950: ERROR/AndroidRuntime(998):     at dalvik.system.NativeStart.main(Native Method)

我不明白;有人可以解释一下吗?

4

3 回答 3

0

这是使用进度条从服务器下载文件的示例

公共类主扩展活动{

 public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "http://rhemafm.serverroom.us:5858/listen.pls";
        new DownloadFileAsync().execute(url);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try {

    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
    FileOutputStream obj;
    InputStream input = new BufferedInputStream(url.openStream());
    //obj=openFileOutput("some_photo_from_gdansk_poland.jpg", Context.MODE_PRIVATE);


    OutputStream output = new FileOutputStream("/sdcard/yourfile.dat");//obj

    byte data[] = new byte[1024];

    long total = 0;

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

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

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
}

}

并且还使用以下权限

于 2011-08-19T09:07:15.853 回答
0

如果您在 UI 线程上进行此网络下载,您将冻结您的应用程序。创建一个后台任务来执行此操作。

    theBackground = new Background();                       // Start the background task
    theBackground.execute("");

public static Background theBackground;                 // Background task ID
private class Background extends AsyncTask<String, String, String>{

...ETC

于 2011-07-15T15:41:56.737 回答
0

仔细阅读 LogCat 输出。您的布局文件中存在解析错误。“二进制 XML 文件第 50 行:您必须提供 layout_width 属性。”

于 2011-07-16T02:40:35.423 回答