当没有数据网络android时,导航抽屉不会打开

时间:2014-12-16 07:00:04

标签: android expandablelistview drawer

我正在使用导航抽屉显示ExpandableListview。除了一个之外,每件事情都很完美...当抽屉没有数据网络打开时(点击抽屉图标时没有任何反应)

当网络可用时,OPEN抽屉没有明确的代码。

MainActivity.java

public class MainActivity extends Activity implements OnQueryTextListener {

    public int CURRENT_THEME;

    /* Google Analytics*/
    Button btn_trackEvent, btn_trackCrash;
    EasyTracker easyTracker = null;
    GoogleAnalytics googleAnalytics;
    StandardExceptionParser exceptionParser;
    /* END GOOGLE ANALYTICS */




    /* shared preference */

     SharedPreferences sharedExpListView;
     SharedPreferences.Editor editorExpList;

    /* end of shared preference */

    private DrawerLayout mDrawerLayout;

    //private ListView expListView;
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild,emptyChildren;
    List<String> list_cat_name,list_cat_id,list_setting;
    private HashMap<String, ArrayList<String>> emptyChild;



    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private TextView mStatusView;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    JSONArray cat = null;
    // Hashmap for ListView
    // ArrayList<HashMap<String, String>> catList;
    int error_flag = 0; // 0 normal, 1 internet connvettion 2Server Error
    private TextView main_error;
    private TextView textView;

    String FavCount = "0";

    /* for push */
    // Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;
    public static String name = "All";
    public static String email = "newsfirst@gmail.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Let's get rid of the app icon here
        ActionBar actionBar = getActionBar();
        actionBar.setIcon(null);
        actionBar.setTitle("");

        super.onCreate(savedInstanceState);
        //overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
        //LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //View view = inflator.inflate(R.layout.action_bar_custom, null);

        setContentView(R.layout.activity_main);

        // Google Analytics
        googleAnalytics = GoogleAnalytics.getInstance(this);
        googleAnalytics.setDryRun(true);
        googleAnalytics.getLogger().setLogLevel(LogLevel.VERBOSE);
        easyTracker = EasyTracker.getInstance(MainActivity.this);
        easyTracker.set(Fields.SCREEN_NAME, "MainActivity");
        easyTracker.send(MapBuilder.createAppView().build());
        exceptionParser = new StandardExceptionParser(MainActivity.this, null);
        // End Google Analytics



        /* get polling webservice*/

        StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy1); 

        /* shared preference */


        sharedExpListView=this.getSharedPreferences("sharedExpListView", MODE_PRIVATE);

        editorExpList=sharedExpListView.edit();


        // mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);






        navDrawerItems = new ArrayList<NavDrawerItem>();

        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], "", navMenuIcons
                .getResourceId(0, -1), "0"));

        FavCount = String.valueOf(All_link.getFavRowCount(MainActivity.this));




        // initialize Expandable listview
                expListView = (ExpandableListView) findViewById(R.id.list_slidermenu);
                expListView.setGroupIndicator(null);
                list_cat_name = new ArrayList<String>();
                list_cat_id = new ArrayList<String>();
                list_setting = new ArrayList<String>();
                listDataHeader = new ArrayList<String>();
                listDataChild = new HashMap<String, List<String>>();
                emptyChild = new HashMap<String, ArrayList<String>>();


                new GetCatList().execute();




        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, // nav menu toggle icon
                0, // nav drawer open - description for
                    // accessibility
                0 // nav drawer close - description for
                    // accessibility
        ) {
            @Override
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                //Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0, "0");
        }







    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            Log.e("position", "karpo "+position);
            TextView txt_id = (TextView) view.findViewById(R.id.txt_id);
            String catid = txt_id.getText().toString();
            TextView txt_title = (TextView) view.findViewById(R.id.title);
            All_link.GLOBAL_TITLE = "";
            All_link.GLOBAL_TITLE = txt_title.getText().toString();

            // display view for selected nav drawer item
            if (!catid.isEmpty())
                displayView(position, catid);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Toast.makeText(this, "Selected Item: " + item.getTitle(),
        // Toast.LENGTH_SHORT).show();
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // Handle action bar actions click
        switch (item.getItemId()) {
        /*
         * case R.id.action_search:
         * 
         * return true;
         */
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        // boolean drawerOpen = mDrawerLayout.isDrawerOpen(expListView);
        // menu.findItem(R.id.action_search).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position, String id) {
        // update the main content by replacing fragments
        Fragment fragment = null;

        Log.e("POSITION", String.valueOf(id));
        int position_id = Integer.parseInt(id);
        switch (position_id) {
        case 0:
            // update selected item and title, then close the drawer
            try{
                fragment = new HomeFragment();

                easyTracker.send(MapBuilder.createEvent("Menu Click", "Fragment", "HomeFragment", null).build());
            }
            catch(Exception e){
                easyTracker.send(MapBuilder.createException(exceptionParser.getDescription(Thread.currentThread().getName(), e), false).build());
            }
            break;

        default:

            fragment = new CategoryFragment(id);
            Log.e("category id","karcat "+id);
            break;
        }

        // update selected item and title, then close the drawer
        // expListView.setItemChecked(position, true);
        // expListView.setSelection(position);
        // //setTitle(navMenuTitles[position]);
        // mDrawerLayout.closeDrawer(expListView);
                if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();
            expListView.setItemChecked(position, true);
            expListView.setSelection(position);
            // setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(expListView);

        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);

    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetCatList extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {

            //expListView.setVisibility(8);
            super.onPreExecute();

            // Adding group data
            listDataHeader.add("Home");                                                         
            listDataHeader.add("News Category");                                                
            listDataHeader.add("My Favourites");  
            listDataHeader.add("Manage Notifications");  
            listDataHeader.add("Send Your Story");  
            listDataHeader.add("News on WhatsApp");  
            listDataHeader.add("About NewsFirst");  
            listDataHeader.add("Contact NewsFirst");  
            listDataHeader.add("Share this App");  
            listDataHeader.add("Rate this App");                                                    
            listDataHeader.add("Settings");


            listDataChild.put(listDataHeader.get(0), new ArrayList<String>()); // No child                                                              
            listDataChild.put(listDataHeader.get(2), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(3), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(4), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(5), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(6), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(7), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(8), new ArrayList<String>()); // No child
            listDataChild.put(listDataHeader.get(9), new ArrayList<String>()); // No child

            list_setting.add("FAQs");
            list_setting.add("Privacy Policy");
            list_setting.add("Terms & Conditions");         
            listDataChild.put(listDataHeader.get(10), list_setting); // With child
        }

        @Override
        protected Void doInBackground(String... params) {

            if (NetworkCheck.isNetworkAvailable(getApplicationContext()) == true) {
                 //navDrawerItems = new ArrayList<NavDrawerItem>();

                // Creating service handler class instance
                ServiceHandler sh = new ServiceHandler();

                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(All_link.CATEGORY_URL,
                        ServiceHandler.GET);

                Log.d("Response: ", "> " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node
                        cat = jsonObj.getJSONArray(All_link.TAG_NEWS);

                        String err = jsonObj.getString(All_link.TAG_ERROR);
                        Log.e("------>Error", String.valueOf(err));

                        if (err.equals("1")) {

                        } else {                                                                                                            
                            // looping through All Contacts
                            for (int i = 0; i < cat.length(); i++) {
                                JSONObject c = cat.getJSONObject(i);

                                String cat_id = c.getString(All_link.TAG_CAT_ID);
                                String cat_name = c
                                        .getString(All_link.TAG_CAT_NAME);
                                String image_icon = c.getString("image_icon");

                                list_cat_name.add(cat_name);
                                list_cat_id.add(cat_id);                                                               
                            }



                            // saving cat_name with cat id in shared preference
                            for (int i = 0; i <list_cat_name.size(); i++) {
                                editorExpList.putString(list_cat_name.get(i), list_cat_id.get(i));
                                editorExpList.commit();     
                            }
                            // End saving cat_name with cat id in shared preference

                            listDataChild.put(listDataHeader.get(1), list_cat_name); // With child      

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler",
                            "Couldn't get any data from the url");
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } else {
                Log.e("Network Error", "Internet Connection Error");
                error_flag = 1;
                // error = "Internet Connection Error";

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (error_flag == 1) {

                expListView.setVisibility(8);
                // main_error.setText("Internet Connection Error! Please check your network settings and try again");
                // main_error.setVisibility(0);

            } else {

                /*
                 * navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],
                 * navMenuIcons .getResourceId(0, -1),"1"));
                 */

                expListView.setVisibility(0);
                // main_error.setText("");
                // main_error.setVisibility(8);

                // Recycle the typed array
                navMenuIcons.recycle();

                expListView
                        .setOnItemClickListener(new SlideMenuClickListener());

                // setting the nav drawer list adapter
                /*adapter = new NavDrawerListAdapter(getApplicationContext(),
                        navDrawerItems);*/
                listAdapter=new ExpandableListAdapter(MainActivity.this, listDataHeader, listDataChild);
                expListView.setAdapter(listAdapter);

                expListView.setItemChecked(0, true);
                expListView.setSelection(0);

            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

据推测,您的抽屉只包含ExpandableListView expListView。如果您检查AsyncTask的doInBackground()方法,如果没有可用的网络,您会看到error_flag设置为1。然后,在onPostExecute()方法中:

if (error_flag == 1) {
    expListView.setVisibility(8);

8的值对应View.GONE,因此,基本上,如果没有网络,则没有抽屉。