Android应用程序在下载页面时崩溃

时间:2013-10-01 18:00:28

标签: android url file-io crash

当我尝试下载页面时,我的Android应用程序崩溃,我给了应用程序的互联网权限和读/写外部存储,我正在尝试制作一个简单的应用程序,有两个选项,下载的URL和保存的位置该页面,但当我点击下载按钮时,应用程序崩溃。

导致应用崩溃的原因是什么? 下载网址的正确方法是什么?

package com.downloadfile;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void saveButton(View v) throws MalformedURLException, IOException
    {
        EditText pageurl = (EditText) findViewById(R.id.page_url);
        String PageUrl = pageurl.getText().toString();
        EditText filePath = (EditText) findViewById(R.id.save_path);
        String FilePath = filePath.getText().toString();

        if (FilePath.startsWith("/"))
        {

            URL url = new URL(PageUrl);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            String data = new java.util.Scanner(in).useDelimiter("\\A").next();
            PrintWriter writer = new PrintWriter(FilePath, "UTF-8"); 
            writer.println(data); 
            writer.close();
            urlConnection.disconnect();


            Context context = getApplicationContext(); 
            CharSequence text = FilePath;
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration); 
            toast.show();
        }
        else
        {
            Context context = getApplicationContext(); 
            CharSequence text = "Please enter file path";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration); 
            toast.show();
        } 
    }
}

这是我的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="300dp"
    android:padding="5dp">

    <EditText
        android:id="@+id/page_url"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="url"
        android:inputType="textUri"/>

    <EditText
        android:id="@+id/save_path"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="save path"
        android:inputType="textUri"/>

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:id="@+id/linearLayout1"
        android:layout_marginTop="4dp"/>

    <Button
        android:id="@+id/download"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Download"
        android:onClick="saveButton"/>

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

您正在ui线程上运行与网络相关的操作。使用ThreadAsynctask

您可能正在NetWorkOnMainThreadExceptionhttp://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

将视图初始化移至onCreate。在按钮上单击从Edittext获取文本。无需在按钮点击时每次初始化。

EditText pageurl;
EditText filePath;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    pageurl = (EditText) findViewById(R.id.page_url);
    filePath = (EditText) findViewById(R.id.save_path);
}

http://developer.android.com/reference/android/os/AsyncTask.html

点击按钮

   public void saveButton(View v) 
   {
      String PageUrl = pageurl.getText().toString();
      String FilePath = filePath.getText().toString();
      new DownloadTask().execute(PageURl,FilePath);
   }

的AsyncTask

    class DownloadTask extends AsyncTask<String,Void,Void>
    {

@Override
protected void onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
    // TODO Auto-generated method stub
       if (params[1].startsWith("/"))
       {
        try
        {

        URL url = new URL(params[0]);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        String data = new java.util.Scanner(in).useDelimiter("\\A").next();
        PrintWriter writer = new PrintWriter(FilePath, "UTF-8"); 
        writer.println(data); 
        writer.close();
        urlConnection.disconnect();
        }catch(Exception e)
        {
            e.printstackTrace()
        } 
       return null;
}

 }