1

リモートtxtファイルを取得しようとするとアプリがクラッシュします。URLを解析しようとしても、クラッシュします。インターネット許可が設定され、デバイス/仮想マシンがインターネットに接続しています。

LogCat: ここに画像の説明を入力してください

コードスニペット:

try {
    // the following line is enough to crash the app
    URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");


    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        //get lines
    }
    in.close();


    } catch (MalformedURLException e) {

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

        e.printStackTrace();
    }

私は自分が間違っていることを理解していません。事前に助けてくれてありがとう。

//編集:ログ猫スニペットを追加

4

1 に答える 1

1

アプリケーションが応答を停止し、OS によって強制終了される可能性があるため、メイン UI スレッドでのネットワーク アクティビティが多いためにアプリケーションがクラッシュしています。これ自体はあまり良い方法ではありません。バックグラウンド処理は、メインの UI スレッドではなく、別のスレッドで行うようにしてください。

ファイルをフェッチするコードをAsyncTaskdoInBackground()内に配置します。

private class DownloadFile extends AsyncTask<String, Integer, Void> {
     protected void doInBackground() {
         try {

       URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");       

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        //get lines
    }
    in.close();


    } catch (MalformedURLException e) {

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

        e.printStackTrace();
    }
 }

 protected void onProgressUpdate() {
    //called when the background task makes any progress
 }

  protected void onPreExecute() {
     //called before doInBackground() is started
 }
 protected void onPostExecute() {
     //called after doInBackground() has finished 
 }
  }

このタスクを呼び出して、ファイルを取得しnew DownloadFile().execute("");たい場所でファイルを取得できます。

于 2012-09-21T16:06:40.727 に答える