將上下文傳遞給我的課程的一個大問題。我嘗試了幾乎所有的東西:getApplicationContext()/ getBaseContext()/ getContext()- >不適用於自動完成/ this。 此時,this
幾乎工作(我的意思不是null)。應將哪個上下文傳遞給超類?
public class PersonActivity extends Activity implements OnTaskCompletedInterface {
public PersonAdapter listAdapter ;
public PersonActivity() {
try {
PersonGetAsync asyncGet = new PersonGetAsync(this, this, this);
asyncGet.execute().get; // supposed to block the UI I know
// With this, I catch the exception
}catch (Exception e) {e.printStackTrace();}
}
public PersonAdapter getListAdapter() {
return listAdapter;
}
有關詳細信息,這裏是孩子:
public class PersonBlueActivity extends PersonActivity {
private ListView lv_Person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person_chooser_blue);
lv_Person = (ListView) findViewById(R.id.activity_person_chooser_blue_lv);
lv_Person.setAdapter(getListAdapter());
lv_Person.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
lv_Person.setClickable(true);
}
@Override
public PersonAdapter getListAdapter() {
return super.getListAdapter();
}
這裏是異步
public class PersonGetAsync extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
Activity mActivity;
Context mContext;
String response;
private OnTaskCompletedInterface listener;
public PersonGetAsync(Activity activity, Context context, OnTaskCompletedInterface listener) {
this.listener = listener;
mActivity = activity;
mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(mContext);
String str = "Connexion en cours";
dialog.setTitle(str + "...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
@Override
protected String doInBackground(String... params) {
System.setProperty("http.keepAlive", "false");
response = "";
try {
//Appel du webservice
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(Globale.webURL+Globale.PERSON);
// Envoi de la requête GET
HttpResponse httpResponse = httpClient.execute(request);
response = EntityUtils.toString(httpResponse.getEntity());
Log.v("Get : ", response);
} catch (Exception e) {
e.printStackTrace();
return "";
}
return response;
}
@Override
protected void onPostExecute(String result) {
listener.onTaskCompleted(result);
dialog.dismiss();
}
它引起了我一個「空指針異常「爲什麼?
您不應該在Activity構造函數中初始化它。您可能會獲得NPE,因爲該活動尚未建立。在onCreate()中執行此操作,然後立即執行此操作。 – DeeV
謝謝DeeV,它的工作! – Nawako