在我看来,我并没有真正从MainActivity调用URL,网络操作 。
但异常仍然存在:
public class MainActivity extends ActionBarActivity {
private final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProcessData test = new ProcessData();
test.doInBackground("mysql") ;
}
//separate file ProcessData.java
public class ProcessData extends AsyncTask<String, Void, String> {
public String createValidUrl(String s){
.....//code in this method works fine
}
public String doInBackground(String ...params){
String validUrl = createValidURL(params[0]);
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url = new URL(validUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
urlConnection.disconnect();
reader.close();
return buffer.toString();
}
}
网络主线程异常仍然发生,我读了其他SO帖子。 我可以将我的http连接代码包装到新线程中,但我想找到确切的错误
答案 0 :(得分:5)
您必须在execute
上调用AsyncTask
方法才能在后台线程中运行它。你正在做的是直接从主线程调用doInBackground
。
答案 1 :(得分:3)
你必须致电
test.execute();
而不是
test.doInBackground("mysql") ;