簡體   English   中英

android應用在啟動時崩潰

[英]android app crashing on start-up

我是android新手。 我正在使用一個正在開發的簡單android應用程序困擾2周。 在我的應用程序中,我試圖從php獲取簡單文本。 但是每次我嘗試啟動該應用程序時,它都會崩潰。 我的代碼如下

package com.example.test;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

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

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
    try {
       HttpResponse response = httpclient.execute(httppost);
       final String str =  EntityUtils.toString(response.getEntity());
       TextView tv = (TextView) findViewById(R.id.textView1);
       tv.setText(str);
    } 
   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;
}

}

我找不到我的問題在哪里。 請有人幫我。

您可能正在獲取NetWorkOnMainThreadException 您應該使用ThreadAsyncTask發出http發布請求,並在ui線程上更新ui。

例:

public class MainActivity extends Activity {

    TextView tv; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        new TheTask().execute();
    }
      class TheTask extends AsyncTask<Void,Void,String>
      {

        @Override
        protected String doInBackground(Void... params) {
            String str = null;
            try
            {
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost("http://logger.net46.net/android/hello.php");
              HttpResponse response = httpclient.execute(httppost);
              str =  EntityUtils.toString(response.getEntity());     
            } 
            catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                }

            return str;

      }

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

      }
}

捕捉

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM