我无法在AsyncTask(MainActivity内部类)的onPostExecute中设置TextView中的文本。
public class MainActivity extends Activity {
...
private TextView txt_msg;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_msg = (TextView) findViewById(R.id.txt_msg);
txt_msg.setText("ON create"); // <-- OK this works
...
...
btn = (Button) findViewById(R.id.btn_associa);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "http://myurl.php?a=1&b=2&c=3";
MainActivity.SQLAsync dlTask = new MainActivity().new SQLAsync(url);
dlTask.execute();
}
}
});
...
...
...
class SQLAsync extends AsyncTask<URL, Integer, String> {
private String myurl = "";
public SQLAsync(String _url) {
super();
myurl = _url;
}
@Override
protected void onPreExecute() {
//empty
}
@Override
protected String doInBackground(URL... urls) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int resp_code = conn.getResponseCode();
is = new BufferedInputStream(conn.getInputStream());
} catch (Exception e) {
Log.e("tag", "Error in http connection " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while (reader.readLine() != null) {
line = reader.readLine();
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("tag", "Error converting result " + e.toString());
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
//empty
}
@Override
protected void onPostExecute(String s) {
String result = s;
Log.i("davide", "String post execute " + s.toString());
if (txt_msg!=null) // <-- THIS IS NULL
txt_msg.setText("MESSAGGIO DI SISTEMA");
...
...
...
}
}
}
我查看了其他类似问题的帖子,但它们在AsyncTask中定义了TextView,而在我的情况下,我不明白哪里出错了。