[英]My application works fine on Android version 2.3.3 but does not work on android 4.2.2
Here is the JAVA code of my app: 这是我的应用程序的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;
}
}
Whenever i try to work with the reader, it stops working for 4.2.2 but works fine for 2.3.3. 每当我尝试与阅读器一起使用时,它在4.2.2中停止工作,但在2.3.3中工作正常。 I posted a similar question before and i was asked to solve the problem using asyncTask, but that didn't really help me out. 我之前曾发布过类似的问题,并被要求使用asyncTask解决问题,但这并没有真正帮助我。
You should only be accessing the reader in the doInBackground method, which executes on a background thread. 您应该只在doInBackground方法中访问阅读器,该方法在后台线程上执行。
The onPostExecute method runs on the UI thread, and should only update the UI, not do any other work. onPostExecute方法在UI线程上运行,并且应该仅更新UI,而不做任何其他工作。
So, I'd suggest changing your AsyncTask to 因此,我建议将您的AsyncTask更改为
AsyncTask<Integer, Integer, String>
move the line 移动线
reader.readLine().toString();
to onPostExecute, return the string from doInBackground, and make the parameter to onPostExecute the string that you read. 到onPostExecute,从doInBackground返回字符串,然后将参数设置为onPostExecute您读取的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.