0

HttpGet と HttpClient を使用して、インターネットからデータを取得しようとしています。ただし、エミュレーターで実行すると、「残念ながら、AppName は停止しました」と言ってすぐにシャットダウンします。これを解決する方法はありますか?

コード:

public class MainActivity extends Activity {

    final String httpPath = "http://www.google.com";    


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView txtContent = (TextView) findViewById(R.id.txtContent);

        TextView tvHttp = (TextView) findViewById(R.id.tvHttp);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(httpPath);
        try {

            HttpEntity httpEntity = httpclient.execute(httpget).getEntity();

           if (httpEntity != null){
            InputStream inputStream = httpEntity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();

            String line = null;

            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }

            inputStream.close();

            tvHttp.setText(stringBuilder.toString());
           }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
      }
AssetManager assetManager = getAssets();


// To load text file
InputStream input;
try {
    input = assetManager.open("dummytext.txt");

     int size = input.available();
     byte[] buffer = new byte[size];
     input.read(buffer);
     input.close();

     // byte buffer into a string
     String text = new String(buffer);

     txtContent.setText(text);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();}

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

LogCat:

03-08 03:31:17.762: D/AndroidRuntime(892): Shutting down VM
03-08 03:31:17.762: W/dalvikvm(892): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-08 03:31:17.952: E/AndroidRuntime(892): FATAL EXCEPTION: main
03-08 03:31:17.952: E/AndroidRuntime(892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appname/com.example.appname.MainActivity}: android.os.NetworkOnMainThreadException
4

3 に答える 3

1

android.os.NetworkOnMainThreadException

Main UIこれは、スレッドでネットワーク関連の呼び出しを行っていることを意味します。

のすべてのHttp関連の呼び出しは、onCreate()に移動する必要がありAsyncTaskます。

于 2013-03-08T04:01:12.513 に答える
0

これは、AndroidでAsynckTaskを使用する方法を理解するためのvogelaによる優れた例です

あなたはそれを投げて、あなたのネットワーク関連の呼び出しをそのタスクのdoBackgroundに置くことができます。

あなたがポイントを得たことを願っています。

于 2013-03-08T04:14:30.217 に答える
0
    class DownloadTask extends AsyncTask<Void,Void,Void>
{
  protected void onPreExecute() 
  {
  super.onPreExecute();  
    //show progress dialog()
  }

 @Override
 protected Void doInBackground(Void... params) {
   //get data form internet here
   // put all downloading related code in a method getDownload()
   // call  getDownload() here
 return null;
 }

 @Override
  protected void onPostExecute(Void result) {
  super.onPostExecute(result);
   //dismiss dialog update ui here
   // uodate ur ui with the downloaded data here
   }
 }

上記を AsyncTask に使用します

別の方法として、長期実行オペレーションに robospice を使用する gitup のこのオープン ソース プロジェクトを見ることができます。https://github.com/octo-online/robospice .

于 2013-03-08T04:13:17.057 に答える