当我在TextView中放置在线文本时应用程序崩溃

时间:2013-03-26 11:38:19

标签: android web textview

运行此代码时,我的应用崩溃了:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_biografie);
        setTitle("Biografie");

        try {
            // Create a URL for the desired page
            URL url = new URL("http://xxx.nl/api/biografie.php?dataid=998");

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline character(s)
                TextView text = (TextView)findViewById(R.id.biografieText);
                text.setText(str);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }

这是我的Logcat输出:

  

03-26 12:35:16.900:E / AndroidRuntime(30127):致命异常:主要   03-26 12:35:16.900:E / AndroidRuntime(30127):   java.lang.RuntimeException:无法启动活动   ComponentInfo {nl.appone.artistone.reneevanginkel / nl.appone.artistone.reneevanginkel.Biografie}:   android.os.NetworkOnMainThreadException 03-26 12:35:16.900:   E / AndroidRuntime(30127):at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   android.app.ActivityThread.access $ 600(ActivityThread.java:123)03-26   12:35:16.900:E / AndroidRuntime(30127):at   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1147)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   android.os.Handler.dispatchMessage(Handler.java:99)03-26   12:35:16.900:E / AndroidRuntime(30127):at   android.os.Looper.loop(Looper.java:137)03-26 12:35:16.900:   E / AndroidRuntime(30127):at   android.app.ActivityThread.main(ActivityThread.java:4429)03-26   12:35:16.900:E / AndroidRuntime(30127):at   java.lang.reflect.Method.invokeNative(Native Method)03-26   12:35:16.900:E / AndroidRuntime(30127):at   java.lang.reflect.Method.invoke(Method.java:511)03-26 12:35:16.900:   E / AndroidRuntime(30127):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:795)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)03-26   12:35:16.900:E / AndroidRuntime(30127):at   dalvik.system.NativeStart.main(Native Method)03-26 12:35:16.900:   E / AndroidRuntime(30127):引起:   android.os.NetworkOnMainThreadException 03-26 12:35:16.900:   E / AndroidRuntime(30127):at   android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   java.net.InetAddress.lookupHostByName(InetAddress.java:391)03-26   12:35:16.900:E / AndroidRuntime(30127):at   java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)03-26   12:35:16.900:E / AndroidRuntime(30127):at   java.net.InetAddress.getAllByName(InetAddress.java:220)03-26   12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpConnection。(HttpConnection.java:71)03-26   12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpConnection。(HttpConnection.java:50)03-26   12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpConnection $ Address.connect(HttpConnection.java:351)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpConnection.connect(HttpConnection.java:128)03-26   12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:312)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpEngine.connect(HttpEngine.java:307)03-26   12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:286)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:236)03-26   12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   java.net.URL.openStream(URL.java:462)03-26 12:35:16.900:   E / AndroidRuntime(30127):at   nl.appone.artistone.reneevanginkel.Biografie.onCreate(Biografie.java:30)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   android.app.Activity.performCreate(Activity.java:4465)03-26   12:35:16.900:E / AndroidRuntime(30127):at   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)   03-26 12:35:16.900:E / AndroidRuntime(30127):at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)   03-26 12:35:16.900:E / AndroidRuntime(30127):... 11更多03-26   12:40:16.960:I / Process(30127):发送信号。 PID:30127 SIG:9

如何将文本从网络放入TextView?这是一个PHP脚本,它有一个带有传记的输出。

谢谢你!

3 个答案:

答案 0 :(得分:1)

这将是一个更好的做法,使用异步任务

AsyncronousTask atask = new AsyncronousTask();          
atask.execute("ur url here");
String res=atask.get();


//Asyncronous taks class goes like

public class AsyncronousTask extends AsyncTask<String, Void, String> {
String response;
Activity c;
//private ProgressDialog dialog;
//String title,msg;


@Override
protected String doInBackground(String... urls) {
    response = "";
    for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse execute = client.execute(httpGet);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader( new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                response += s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return response;
}

}

答案 1 :(得分:0)

使用此代码,您将获得响应此方法调用的响应,然后您可以在textView上设置

public static String HitServerGET(String URL){

    String result = null;

    InputStream is = null;

    StringBuilder sb = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection" + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";

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

        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    return result;

答案 2 :(得分:0)

在onPostExecute中,您可以在TextView中设置文本 我重新使用了Saad Khokhar的HitServerGET函数

此代码可以放在你的onCreate中。

final URL url = new URL("http://xxx.nl/api/biografie.php?dataid=998");
new AsyncTask<String, String, String>()
{
  String text=null;         
  @Override
  protected String doInBackground(String... params)
  {
    text = HitServerGET(url)
  }

  @Override
  protected void onPostExecute(String ret)
  {
    ((TextView)findViewById(R.id.biografieText)).setText(text);
  }
}.execute();