简体   繁体   English

在ListFragment中显示进度对话框

[英]Showing Progress Dialog in ListFragment

I have a class that extends from ListFragment . 我有一个从ListFragment扩展的类。 I need to show a progress dialog since it takes some time to load the data from the server. 我需要显示一个进度对话框,因为从服务器加载数据需要花费一些时间。 I am using a private class called MenuItemData and extends that class from AsyncTask . 我正在使用一个名为MenuItemData的私有类,并从AsyncTask扩展了该类。 In the onPreExecute method I have this line, onPreExecute方法中,我有这一行,

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

and in onPostExecute method, onPostExecute方法中

pDialog.dismiss(); //line 2

Now when I run the program it stops and gives NullPointerException . 现在,当我运行程序时,它将停止并提供NullPointerException

But when I commented those two lines, program works fine . 但是当我评论这两行时,程序运行正常 I think the problem is that getActivity() returns null. 我认为问题在于getActivity()返回null。

Code for MenuItemData class 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 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 class 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)

} So is there anyway to solve this problem? 因此,有解决这个问题的方法吗? (To show the progress dialog) (显示进度对话框)

Thanks. 谢谢。

Try this.. 尝试这个..

Call like below code 像下面的代码一样调用

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

and inside your AsyncTask use constructor 并在您的AsyncTask使用构造函数

    Context context;

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

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

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

    }

The problem lies in your constructor 问题出在你的构造函数上

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

In the constructor, getActivity() returns null as Android has not "inititalized" back-end stuff needed for the fragment. 在构造函数中,由于Android尚未“初始化”该片段所需的后端内容,因此getActivity()返回null。

Try moving setDataToMenu() at onViewCreated(), this should fix your problem as getActivity() should return the activity now. 尝试在onViewCreated()处移动setDataToMenu(),这将解决您的问题,因为getActivity()应该立即返回活动。

Define a variable to store the context and make it final. 定义一个变量来存储上下文并使其最终。 Use the final variable inside the AsyncTask. 在AsyncTask中使用最终变量。

final Context activity = getActivity();

Call your super.onPreExecute() first and use constructor to get the activity reference 首先调用您的super.onPreExecute()并使用构造函数获取活动参考

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

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

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

}

call it as from your list fragment 从列表片段中调用它

Activity act = this;
new MenuItemData(act).execute();

Move the call to the async method to onactivitycreated. 将对异步方法的调用移至onactivitycreated。 Because at the point when you call it from the constructor the getactivity will return null. 因为从构造函数调用它时,getactivity将返回null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM