我无法通过AsyncTask(MainActivity innerclass)中的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定义,在我的情况下,我无法理解错误。
答案 0 :(得分:1)
您正在从SQLAsync
课程的新实例创建新的MainActivity
,而不是现有的实例。
变化:
MainActivity.SQLAsync dlTask = new MainActivity().new SQLAsync(url);
要:
SQLAsync dlTask = new SQLAsync(url);
答案 1 :(得分:1)
而不是
MainActivity.SQLAsync dlTask = new MainActivity().new SQLAsync(url);
初始化如下:
SQLAsync dlTask = new SQLAsync(url);