Android应用程序崩溃,但代码没有显示错误

Android应用程序崩溃,但代码没有显示错误,android,Android,好的,我正在尝试制作一个应用程序,它能够从web服务器检索数据,然后在文本视图上显示数据,如果web服务器上的数据发生变化,它会不断更新。经过多次尝试,我得到的结果如下所示 public class HttpTest extends AppCompatActivity { TextView text = (TextView) this.findViewById(R.id.textView3); @Override protected void onCreate(Bundle savedIns

好的,我正在尝试制作一个应用程序,它能够从web服务器检索数据,然后在文本视图上显示数据,如果web服务器上的数据发生变化,它会不断更新。经过多次尝试,我得到的结果如下所示

public class HttpTest extends AppCompatActivity {

TextView text = (TextView) this.findViewById(R.id.textView3);

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

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL("http://IPGOESHERE/");

        HttpURLConnection urLConnection = (HttpURLConnection) url.openConnection();
        InputStream in = urLConnection.getInputStream();
        BufferedReader data = new BufferedReader(new InputStreamReader(in));

        StringBuilder total = new StringBuilder();
        String line;
        while ((line = data.readLine()) != null) {
            total.append(line).append('\n');
        }
        String result = total.toString();
        text.setText(result);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

我不认为我所写的允许不断更新,但我至少希望能够在文本视图上显示某种数据,并确保它不会首先崩溃。因此,如果有人能指出我做错了什么,我将不胜感激。

你需要在另一个线程上进行这种工作。尝试使用异步任务。
创建一个扩展AsyncTask的类,然后使doInBackground方法中的url连接成为在工作线程上调用的方法。然后可以在ui线程上调用的onPostExecute方法中更新textview。祝你好运:

应用程序崩溃,因为你正在主线程上发出HTTP请求。改为使用AsyncTask

看起来像networkingOnMainThread错误那么我该如何解决这个问题呢?忘了提到我是这方面的新手…你在你的清单上设置权限了吗?另外,你能发布你的登录吗?我不确定这是确切的错误。你必须出示你的航海日志。你肯定会在那里看到一些东西。但是,使用您获得的代码,您可能只在主线程上实现了联网。尝试创建一个新线程,并在该线程中执行网络操作