我想做一個Dialog Fragment來訪問外部類。在對話框片段中,我有這樣一行:「new JSONParse()。execute();」 在這一行中,Android Studio IDE說不能從靜態上下文中引用。訪問外部類的Android DialogFragment
我該如何更改代碼,例如我可以在Dialog Fragment中調用JSONParse類?
public class HorariosMedFragment extends Fragment {
...
Button butMarca = (Button) view.findViewById(R.id.but_horarios_view);
butMarca.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ConfirmDialogFragment().show(getFragmentManager(), "MyDialog");
}
});
public class JSONParse extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
....
}
@Override
protected JSONObject doInBackground(String... args) {
.....
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
....
}
}
public static class ConfirmDialogFragment extends DialogFragment {
Context mContext;
public ConfirmDialogFragment() {
mContext = getActivity();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Confirmação?");
alertDialogBuilder.setMessage("Voce confirma o agendamento?");
alertDialogBuilder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
new JSONParse().execute(); //Here is my problem
}
});
alertDialogBuilder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
}
您的ConfirmDialogFragment和JSONParse類都是HorariosMedFragment的內部類嗎? – fluffyBatman
@ fluffyBatman是的,他們這樣做。 –
我有一個解決方法:在HorariosMedFragment和DialogFragmet中使用JSONParse js = new JSONParse()我做了:((HorariosMedFragment)getFragmentManager()。findFragmentById(R.id.fragment_container)).js.execute();它有效,但我不知道這是否是一個好的解決方案。我已經不得不將原始文章更改爲公共ConfirmDialogFragment(){0} {0} {0} {0} mContext = getContext(); }和AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); –