以下是我的应用的JAVA代码:
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetUrl().execute(20);
}
private class GetUrl extends AsyncTask<Integer, Integer, BufferedReader> {
@Override
protected BufferedReader doInBackground(Integer... params) {
BufferedReader reader = null;
try {
URL url = null;
url = new URL("http://www.google.com");
URLConnection conn = url.openConnection();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
catch (Exception e) {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("Error");
}
return reader;
}
@Override
protected void onPostExecute(BufferedReader reader) {
TextView tv = (TextView) findViewById(R.id.textView1);
String line = null;
try {
line = reader.readLine().toString(); /*This line if removed removes the error. Whenever i try to work with the reader, it stops working for 4.2.2 but works fine for 2.3.3*/
tv.setText(line);
}
catch( Exception e) {
tv.setText(e.getMessage());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
每当我尝试使用阅读器时,它都会停止工作4.2.2但适用于2.3.3。我之前发过一个类似的问题,我被要求使用asyncTask解决问题,但这并没有真正帮助我。
答案 0 :(得分:0)
您应该只在doInBackground方法中访问阅读器,该方法在后台线程上执行。
onPostExecute方法在UI线程上运行,并且应该只更新UI,而不是做任何其他工作。
所以,我建议将AsyncTask更改为
AsyncTask<Integer, Integer, String>
移动线
reader.readLine().toString();
到onPostExecute,从doInBackground返回字符串,并将参数设为onPostExecute你读取的字符串。