gpt4 book ai didi

java - NetworkOnMainThreadException 尽管有 AsyncTask

转载 作者:行者123 更新时间:2023-11-29 06:35:23 26 4
gpt4 key购买 nike

我是 android 的新手,正在开发一个测试应用程序来访问服务器并获取 json 响应。这是我的主要 Activity -

public class MainPageActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_layout);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
return false;
}

@Override
public boolean onQueryTextSubmit(String query) {
new DownloadWebpageTask().doInBackground("http://49.139.144.194:8080/ServerForMyAndroid/MusicServlet");
return false;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}

AsyncTask 类是-

public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String result) {
ResultMainVO resultVO = new Gson().fromJson(result, ResultMainVO.class);
System.out.println("test" + resultVO);
}

@Override
protected String doInBackground(String... urls) {
InputStream is = null;
StringBuilder builder = new StringBuilder();

try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Accept", "*/*");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}

我还在 AndroidManifest.xml 文件中添加了权限-

当我在模拟器上运行应用程序时出现以下异常-

02-22 21:49:41.989: E/AndroidRuntime(734): 致命异常: main02-22 21:49:41.989: E/AndroidRuntime(734): android.os.NetworkOnMainThreadException02-22 21:49:41.989: E/AndroidRuntime(734): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)

最佳答案

改变这个

new DownloadWebpageTask().doInBackground("http://49.139.144.194:8080/ServerForMyAndroid/MusicServlet");

new DownloadWebpageTask().execute("http://49.139.144.194:8080/ServerForMyAndroid/MusicServlet");

关于java - NetworkOnMainThreadException 尽管有 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com