我是Android新手,我試圖編寫一個小應用程序,它允許我抓取外部JSON文件並解析它。我得到了這個工作,但它不會工作,如果我試圖在後臺執行它作爲AsyncTask
。蝕給我的錯誤findViewById(int)方法未定義
在這一行方法findViewById(INT)是未定義的類型LongOperation
:
的TextView txtView1 =(TextView的)findViewById(R.id .TextView01);
這裏是我的代碼:
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private final Context LongOperation = null;
@Override
protected String doInBackground(String... params) {
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
txtView1.setText(jo.getString("text") + " - " + jo.getString("secondtest"));
}
} catch (MalformedURLException e) {
Toast.makeText(this.LongOperation, "Malformed URL Exception: " + e, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this.LongOperation, "IO Exception: " + e, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(this.LongOperation, "JSON Exception: " + e, Toast.LENGTH_LONG).show();
}
return null;
}
@Override
protected void onPostExecute(String result) {
}
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(LongOperation);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
關於如何解決此問題的任何想法?
地方通過你的`Activity`類的實例是非常危險的,如果你不知道你在做什麼,你最終可能會泄露整個活動! – 2011-02-12 17:40:34