在ListFragment中显示进度对话框

时间:2014-02-05 05:46:56

标签: android progressdialog android-listfragment

我有一个从 ListFragment 扩展的课程。我需要显示一个进度对话框,因为从服务器加载数据需要一些时间。我正在使用一个名为MenuItemData的私有类,并从 AsyncTask 扩展该类。在 onPreExecute 方法中,我有这一行,

pDialog  = ProgressDialog.show(getActivity(), "Loading...", "Please wait...", false); //line 1

onPostExecute 方法,

pDialog.dismiss(); //line 2

现在,当我运行该程序时,它会停止并提供 NullPointerException

但是当我评论这两行时,程序运行正常我认为问题是getActivity()返回null。

MenuItemData类的代码

private class MenuItemData extends AsyncTask<String, String, String> {
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try {
            if ((json_.getString(KEY_SUCCESS) != null)) {

                int success = Integer.parseInt(json_.getString(KEY_SUCCESS));

                if (success == 1) {

                    jsonArray = json_.getJSONObject("data").getJSONArray("items");
                    itemCount = jsonArray.length();
                    for (int i = 0; i < itemCount; i++) {
                        jsonObject = jsonArray.getJSONObject(i);
                        menuItems = new Menu_Items();
                        menuItems.setName(jsonObject.getString("name"));
                        menuItems.setDescription(jsonObject.getString("description"));
                        menuItems.setPrice("$"+jsonObject.getString("price"));
                        menu_itemsArrayList.add(menuItems);
                    }
                }
            }
        } catch (JSONException e) {
            Log.e("Menu Items2", e.toString());
        }


        pDialog.dismiss();



    }

    @Override
    protected void onPreExecute() {

        pDialog  = ProgressDialog.show(getActivity(), "Loading...", "Please wait...", false);

        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... params) {
        json_ = userFunctions.getMenuItems("Appetizers");
        return null;
    }
}

logcat的

02-05 11:25:24.245  28619-28619/com.burgerhot.main E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
        at android.app.AlertDialog.<init>(AlertDialog.java:98)
        at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
        at android.app.ProgressDialog.show(ProgressDialog.java:110)
        at android.app.ProgressDialog.show(ProgressDialog.java:99)
        at com.burgerhot.main.MenuCategory1$MenuItemData.onPreExecute(MenuCategory1.java:105)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
        at android.os.AsyncTask.execute(AsyncTask.java:511)
        at com.burgerhot.main.MenuCategory1.setDataToMenu(MenuCategory1.java:61)
        at com.burgerhot.main.MenuCategory1.<init>(MenuCategory1.java:46)
        at com.burgerhot.main.MyAdapter.getItem(Menu.java:47)
        at com.burgerhot.main.MyAdapter.getItem(Menu.java:36)
        at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:97)
        at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:832)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:982)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
        at android.view.View.measure(View.java:12911)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4805)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:297)
        at android.view.View.measure(View.java:12911)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:828)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:557)
        at android.view.View.measure(View.java:12911)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4805)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:297)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2097)
        at android.view.View.measure(View.java:12911)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1064)
        at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2446)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4448)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
        at dalvik.system.NativeStart.main(Native Method)

MenuCategory1类

public class MenuCategory1 extends ListFragment {

private UserFunctions userFunctions;
private static String KEY_SUCCESS = "success";
private JSONObject json_, jsonObject;
private JSONArray jsonArray;
int itemCount = 0;
private ProgressDialog pDialog;
private Menu_Items menuItems;
final private Context context=getActivity();
private ArrayList<Menu_Items> menu_itemsArrayList;
CustomAdapterForMenu myCustomAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}


public MenuCategory1() {
    userFunctions = new UserFunctions();
    setDataToMenu();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    myCustomAdapter = new CustomAdapterForMenu(getActivity(), R.layout.menu_category1, menu_itemsArrayList);
    /** Setting the list adapter for the ListFragment */
    this.setListAdapter(myCustomAdapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}


private void setDataToMenu() {
    menu_itemsArrayList = new ArrayList<Menu_Items>();
    new MenuItemData().execute();
}

//private class goes here (mentioned above)

} 那么无论如何要解决这个问题? (显示进度对话框)

感谢。

5 个答案:

答案 0 :(得分:2)

试试这个..

调用如下代码

new MenuItemData(getActivity()).execute();

并在AsyncTask内使用构造函数

    Context context;

    public MenuItemData(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog  = ProgressDialog.show(context, "Loading...", "Please wait...", false);

    }

答案 1 :(得分:1)

问题在于你的构造函数

public MenuCategory1() {
userFunctions = new UserFunctions();
setDataToMenu();
}

在构造函数中,getActivity()返回null,因为Android没有“初始化”片段所需的后端内容。

尝试在onViewCreated()上移动setDataToMenu(),这应该可以解决您的问题,因为getActivity()应该立即返回活动。

答案 2 :(得分:0)

定义一个变量来存储上下文并使其成为最终。使用AsyncTask中的final变量。

final Context activity = getActivity();

答案 3 :(得分:0)

首先调用你的super.onPreExecute()并使用构造函数来获取活动参考

Activity act;
MenuItemData(Activity a){
    act = a;
}

@Override
protected void onPreExecute() {
     super.onPreExecute();

    pDialog  = ProgressDialog.show(act, "Loading...", "Please wait...", false);

}

从列表片段

中调用它
Activity act = this;
new MenuItemData(act).execute();

答案 4 :(得分:0)

将对异步方法的调用移至onactivitycreated。因为在从构造函数中调用它时,getactivity将返回null。