Java android.os.NetworkOnMainThreadException不知道如何解决
我在网上查到了我的错误,人们告诉我在另一个线程或异步任务上运行网络,但我不知道如何解决这个问题。。。 所以一切正常,应用程序启动后崩溃,并告诉我android.os.NetworkOnMainThreadException 这是我的密码:Java android.os.NetworkOnMainThreadException不知道如何解决,java,android,Java,Android,我在网上查到了我的错误,人们告诉我在另一个线程或异步任务上运行网络,但我不知道如何解决这个问题。。。 所以一切正常,应用程序启动后崩溃,并告诉我android.os.NetworkOnMainThreadException 这是我的密码: public class Activity2 extends AppCompatActivity { private static final String TAG = Activity2.class.getSimpleName(); priv
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);
}
}
API 11或Android版本3.0出现此异常,例如实名,主进程中讨论链消息的进程,因此称为MainThread,在以前的历史记录中,此操作是允许的,尽管不建议这样做,但这取决于需要进程的时间,ANR应用程序不响应 理想的解决方案是这样命名的,因为它是android社区指定的形式,要实现这个解决方案,我们必须实现AsyncTask类的继承,这个类允许在后台执行操作 您也可以使用一些库,如改装、协同程序等
如果您解决了这个问题,请告诉我:您好,就像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
}
}
是的,我读过,但我不知道如何在我自己的代码中实现它,我仍然是Java的初学者运行你的loadstuff;AsyncTask中的代码。这是我不理解的,这意味着什么,我应该把loadstuff放在哪里?whatLook是一个例子。所以我应该把loadstuff放在AsyncTask类中,但是我应该把这个类放在哪里?我如何把它称为我以前的loadstuff?
NameOfTask task = new NameOfTask();
task.execute((Void)null);
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
}
}