AsyncTask和Fragment Exception android.view.WindowManager $ BadTokenException

时间:2013-06-18 15:01:52

标签: android android-fragments android-asynctask actionbarsherlock android-gridview

片段应该在asynctask中下载带有名称和图像的json,并在gridview中显示它们 这是我得到的例外

06-17 16:34:30.207: W/dalvikvm(689): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
06-17 16:34:30.297: E/AndroidRuntime(689): FATAL EXCEPTION: main
06-17 16:34:30.297: E/AndroidRuntime(689): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewRootImpl.setView(ViewRootImpl.java:589)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:326)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.app.Dialog.show(Dialog.java:277)
06-17 16:34:30.297: E/AndroidRuntime(689):  at project.almashy.TopRatedFragment$DownloadJSON.onPreExecute(TopRatedFragment.java:107)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.os.AsyncTask.execute(AsyncTask.java:534)
06-17 16:34:30.297: E/AndroidRuntime(689):  at project.almashy.TopRatedFragment.methodThatStartsTheAsyncTask(TopRatedFragment.java:50)
06-17 16:34:30.297: E/AndroidRuntime(689):  at project.almashy.TopRatedFragment.onCreate(TopRatedFragment.java:40)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:807)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:801)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.view.ViewPager.populate(ViewPager.java:1062)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.View.measure(View.java:15172)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:617)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.View.measure(View.java:15172)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.View.measure(View.java:15172)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.View.measure(View.java:15172)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-17 16:34:30.297: E/AndroidRuntime(689):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.View.measure(View.java:15172)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.Choreographer.doCallbacks(Choreographer.java:555)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.Choreographer.doFrame(Choreographer.java:525)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.os.Handler.handleCallback(Handler.java:615)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.os.Looper.loop(Looper.java:137)
06-17 16:34:30.297: E/AndroidRuntime(689):  at android.app.ActivityThread.main(ActivityThread.java:4745)
06-17 16:34:30.297: E/AndroidRuntime(689):  at java.lang.reflect.Method.invokeNative(Native Method)
06-17 16:34:30.297: E/AndroidRuntime(689):  at java.lang.reflect.Method.invoke(Method.java:511)
06-17 16:34:30.297: E/AndroidRuntime(689):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-17 16:34:30.297: E/AndroidRuntime(689):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-17 16:34:30.297: E/AndroidRuntime(689):  at dalvik.system.NativeStart.main(Native Method)

这是我的片段代码

public class TopRatedFragment extends SherlockFragment{
    GridView gridView;
    JSONObject jsonobject;
    JSONArray jsonarray;
    ImageAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    public static String PROD_NAME = "prod_name";
    public static String PROD_SMALL_IMG = "prod_small_img";
    View v;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        methodThatStartsTheAsyncTask();
    }
    private void methodThatStartsTheAsyncTask() {
        AsyncTask<Void, Void, Void> testAsyncTask = new DownloadJSON(new FragmentCallback() {

            @Override
            public void onTaskDone() {
                methodThatDoesSomethingWhenTaskIsDone();
            }
        });
        testAsyncTask.execute();
    }

    private void methodThatDoesSomethingWhenTaskIsDone() {
        gridView = (GridView) v.findViewById(R.id.gridview);
        gridView.setAdapter(new adapter.ImageAdapter(getActivity().getBaseContext(), arraylist));

    }

    public interface FragmentCallback {
        public void onTaskDone();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
         v = inflater.inflate(R.layout.top_rated, container, false);
        return v;           
    }

    @Override
    public void onStart() {
        super.onStart();

        //getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

 // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        private FragmentCallback mFragmentCallback;

        public DownloadJSON(FragmentCallback fragmentCallback) {
            mFragmentCallback = fragmentCallback;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(getActivity().getBaseContext());
            // Set progressdialog title
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create the array 
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrive JSON Objects from the given website URL in JSONfunctions.class
            //jsonobject = JSONfunctions.getJSONfromURL("http://fcis.zzl.org/android_login_api_hegazy/products.php");
            jsonobject = JSONParser
                    .getJSONfromURL("http://10.0.2.2/android_login_api/products.php");

            try {
                // Locate the array name
                jsonarray = jsonobject.getJSONArray("products");
                //jsonarray = jsonobject.getJSONArray(name);

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("rank", jsonobject.getString("prod_name"));
                    map.put("flag", jsonobject.getString("prod_small_img"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            mFragmentCallback.onTaskDone();
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

这是我的适配器

public class ImageAdapter extends BaseAdapter {
    // Declare Variables
        Context context;
        LayoutInflater inflater;
        ArrayList<HashMap<String, String>> data;
        ImageLoader imageLoader;


    public ImageAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        this.data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        // Declare Variables
        TextView prod_name;
        ImageView prod_small_img;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.mobile, parent, false);
        // Get the position from the results
        HashMap<String, String> resultp = new HashMap<String, String>();
        resultp = data.get(position);


        // Locate the ImageView in listview_item.xml
        prod_small_img = (ImageView) itemView.findViewById(R.id.grid_item_image); 
        // Locate the TextViews in listview_item.xml
        prod_name = (TextView) itemView.findViewById(R.id.grid_item_label);

        // Capture position and set results to the TextViews
        prod_name.setText(resultp.get(TopRatedFragment.PROD_NAME));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class to download and cache
        // images
        imageLoader.DisplayImage(resultp.get(TopRatedFragment.PROD_SMALL_IMG), prod_small_img);


        return itemView;

    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

}

我不知道出了什么问题!

1 个答案:

答案 0 :(得分:2)

更改mProgressDialog = new ProgressDialog(getActivity().getBaseContext());

mProgressDialog = new ProgressDialog(getActivity());

您应该始终只使用getActivity()作为片段中的上下文,因为活动是从上下文

派生的