这是我的应用程序的 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 解决问题,但这并没有真正帮助我。