android.os.NetworkOnMainThreadException不知道如何解决

时间:2019-03-14 19:43:10

标签: java android

我在网上查找了我的错误,人们告诉人们在另一个线程或asyncTask上运行网络连接,但是我不知道如何解决此问题... 这样一切正常,应用启动,然后崩溃,并告诉我“ android.os.NetworkOnMainThreadException”

这是我的代码:

public class Activity2 extends AppCompatActivity {
    private static final String TAG = Activity2.class.getSimpleName();
    private TextView fileContent;
    String endstring = "";

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
        fileContent = (TextView) findViewById(R.id.content_from_server);
        try {
            loadstuff();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private void loadstuff() throws IOException {


        URL url = new URL("http://ipaddress/login.php"); // URL to your application
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("username", "test"); // All parameters, also easy
        params.put("password", "test");

        StringBuilder postData = new StringBuilder();
        // POST as urlencoded is basically key-value pairs, as with GET
        // This creates key=value&key=value&... pairs
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        // Convert string to byte array, as it should be sent
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        // Connect, easy
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        // Tell server that this is POST and in which format is the data
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        // This gets the output from your server
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)

            endstring = endstring + (char)c;
            fileContent.setText(endstring);


    }
}

3 个答案:

答案 0 :(得分:0)

此异常发生在API 11或Android 3.0版中,例如真实名称,主进程中讨论链消息的过程(因此命名为MainThread),在以前的历史中,尽管不建议这样做,但允许此操作,取决于所需的处理时间,即ANR(应用程序无响应)。

之所以称为理想解决方案,是因为它是android社区指示的形式,要实现此解决方案,我们必须实现AsyncTask类的继承,该类允许在后台执行操作

您可以使用一些库,例如翻新,协程等。

如果您已解决此问题,请告诉我:)

答案 1 :(得分:0)

您好,就像Henrique所说的,您需要使用AsyncTask,它在您的类中是一个这样的类

public class NameOfTask extends AsyncTask<Void, Void, Boolean>{

    @Override
    protected Boolean doInBackground(Void... voids) {
        /*your code goes here*/
        return true;
    }
    @Override
    protected void onPostExecute(final Boolean success) {
       /*If you need to do something after the task*/
    }

    @Override
    protected void onCancelled() {
        //if cancel you may need to do something in here
    }
}

然后调用您只需调用您创建的类。 像这样的东西:

 NameOfTask task = new NameOfTask();
 task.execute((Void)null);

答案 2 :(得分:0)

public class Activity2 extends AppCompatActivity {
    private static final String TAG = Activity2.class.getSimpleName();
    private TextView fileContent;
    String endstring = "";

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

        fileContent = (TextView) findViewById(R.id.content_from_server);

        new AsyncLoadStuff().execute()


    }

    private void loadstuff() throws IOException {


        URL url = new URL("http://ipaddress/login.php"); // URL to your application
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("username", "test"); // All parameters, also easy
        params.put("password", "test");

        StringBuilder postData = new StringBuilder();
        // POST as urlencoded is basically key-value pairs, as with GET
        // This creates key=value&key=value&... pairs
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        // Convert string to byte array, as it should be sent
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        // Connect, easy
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        // Tell server that this is POST and in which format is the data
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        // This gets the output from your server
        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)

            endstring = endstring + (char)c;
            fileContent.setText(endstring);


    }
}


You can do something like this ...

//Its may be a inner class
// LoadStuff inside this class, it will be executed on separated class 
 private class AsyncLoadStuff extends AsyncTask<String, String, String> {


        @Override
        protected String doInBackground(String... params) {
             try {
                loadstuff();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(String result) {
            //put load wait
        }

    }