Q:

Fragments are not loaded from Navigation Drawer Click Listener

Android OnItemClickListener is not working. I have already researched some of the previous similar questions I could not find any solution to my problem.
I find  Log.d("TAG", "Item Click Working"); in the Logcat but I am not able to open a new fragment.
I am attaching the code below.
**MainActivity**

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.sri.vaavefeed.adapter.FeedListAdapter;
import com.sri.vaavefeed.app.AppController;
import com.sri.vaavefeed.data.FeedItem;

public class MainActivity extends Activity implements OnItemClickListener
{
    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://coherendz.net/vaavefeed1.json";
    int node_type;
    FeedItem item;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private ArrayList<NavDrawerItem> navDrawerItems;
    private TypedArray navMenuIcons;
    private NavDrawerListAdapter adapter;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private myAdapter myadapter;
    private int node_id;
    private String comments_count;
    private String like_count;
    private String readable_date;
    private String name;
    private String description;

    @SuppressLint("NewApi") 
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();
        navMenuTitles = getResources().getStringArray(R.array.Options);

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

        listView = (ListView) findViewById(R.id.list);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mDrawerList = (ListView) findViewById(R.id.drawerList);
        mDrawerList.setItemsCanFocus(true);
        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

       getActionBar().setHomeButtonEnabled(true);
       getActionBar().setDisplayHomeAsUpEnabled(true);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // These two lines not needed, 
        // just to get the look of facebook (changing background color & hiding the icon)

        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998"))); 
        getActionBar().setIcon( 
                   new ColorDrawable(getResources().getColor(android.R.color.transparent))); 

        // We first check for cached request 
        Cache cache = AppController.getInstance().getRequestQueue().getCache(); 
        Entry entry = cache.get(URL_FEED); 
        if (entry != null) { 
            // fetch the data from cache 
            try { 
                String data = new String(entry.data, "UTF-8"); 
                try { 
                    parseJsonFeed(new JSONObject(data)); 
                } catch (JSONException e) { 
                    e.printStackTrace(); 
                } 
            } catch (UnsupportedEncodingException e) { 
                e.printStackTrace(); 
            } 

        } else { 
            // making fresh volley request and getting json 
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET, 
                    URL_FEED, null, new Response.Listener<JSONObject>() { 

                        @Override 
                        public void onResponse(JSONObject response) { 
                            VolleyLog.d(TAG, "Response: " + response.toString()); 
                            if (response != null) { 
                                parseJsonFeed(response); 
                            } 
                        } 
                    }, new Response.ErrorListener() { 

                        @Override 
                        public void onErrorResponse(VolleyError error) { 
                            VolleyLog.d(TAG, "Error: " + error.getMessage()); 
                        } 
                    }); 

            // Adding request to volley request queue 
            AppController.getInstance().addToRequestQueue(jsonReq); 
        }

        mTitle = mDrawerTitle = getTitle();

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));

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

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);

         /*  myadapter = new myAdapter(this);*/
           mDrawerList.setAdapter(adapter);

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

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

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

    /** 
     * Parsing json reponse and passing the data to feed view list adapter 
     * */ 
    private void parseJsonFeed(JSONObject response) {

        @SuppressWarnings("rawtypes")
        Iterator itr = response.keys();
        int i = 0;

      try 
      {     
        while(itr.hasNext())

        {
                String key = itr.next().toString();
                JSONObject entry = response.getJSONObject(key);

                JSONObject phone = entry.getJSONObject("basic");
                name = phone.getString("title");
                description = phone.getString("description");
                node_type = phone.getInt("node_type");
                node_id = phone.getInt("node_id");
                JSONObject comments = entry.getJSONObject("comments");
                comments_count = comments.getString("count");
                JSONObject like = entry.getJSONObject("likes");
                like_count = like.getString("count");
                readable_date = phone.getString("readable_date");

                item = new FeedItem();
                item.setId(node_id); 
                item.setName(name);               
                item.setStatus(description); 
                item.setReadable_date(readable_date);
                item.setComments_count(comments_count);
                item.setLike_count(like_count);

                i++;

                // Image might be null sometimes 
                String image = response.isNull("image") ? null : response 
                        .getString("image"); 

                // url might be null sometimes 
                String feedUrl = response.isNull("url") ? null : response 
                        .getString("url");

                /*item.setUrl(feedUrl);*/ 
                item.setUrl(feedUrl);
                feedItems.add(item); 
            } 

            // notify data changes to list adapater 
            listAdapter.notifyDataSetChanged();

        } 
      catch (JSONException e) 
      {
            e.printStackTrace(); 
      } 
  }
        /**
         * Slide menu item click listener
         * */
        private class SlideMenuClickListener implements
                ListView.OnItemClickListener {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) 
            {   // display view for selected nav drawer item

                //Log.d("Kanth", "Item Click Working");
                Toast.makeText(MainActivity.this,navMenuTitles[position]+"was selected", Toast.LENGTH_LONG).show();
                displayView(position);
            }
        }

        /**
         * Diplaying fragment view for selected nav drawer list item
         * */
        private void displayView(int position) {
            // update the main content by replacing fragments
            Fragment fragment = null;
            switch (position) 
            { 
            case 0:
                fragment = new HomeFragment();
                Bundle data = new Bundle();
                data.putInt("id", node_id);
                data.putString("name", name);
                data.putString("description", description);
                data.putString("readable_date", readable_date);
                data.putString("Comments_count", comments_count);
                data.putString("Like_count", like_count);
                fragment.setArguments(data);
                Log.d("Kanth", "Item Click Working");
                break;
            case 1:
                fragment = new FindPeopleFragment();
                break;
            case 2:
                fragment = new PhotosFragment();
                break;
            case 3:
                fragment = new CommunityFragment();
                break;
            case 4:
                fragment = new PagesFragment();
                break;
            case 5:
                fragment = new WhatsHotFragment();
                break;
            default:
                break;
            }

            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.mainContent, fragment).commit();

                // update selected item and title, then close the drawer
                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                setTitle(navMenuTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            }

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

            @Override
            public boolean onCreateOptionsMenu(Menu menu) 
            {
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) 
            {
                // 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_settings:
                    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(mDrawerList);
                menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
                return super.onPrepareOptionsMenu(menu);
            }

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

            /**
             * When using the ActionBarDrawerToggle, you must call it during
             * onPostCreate() and onConfigurationChanged()...
             */

            @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);
            } 

drawer_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:clickable="false"
    android:descendantFocusability="blocksDescendants"
    android:focusable="false"
    android:focusableInTouchMode="false"
    >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="25dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:contentDescription="@string/desc_list_item_icon"
        android:src="@drawable/ic_launcher"
        android:layout_centerVertical="true" 
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"/>

    <TextView android:id="@+id/counter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/counter_bg"
        android:layout_alignParentRight="true"
        android:layout_marginRight="8dp"
        android:textColor="#000000"
        android:layout_centerHorizontal="true"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="57dp"
        android:layout_toRightOf="@+id/icon"
        android:paddingRight="20dp"
        android:paddingTop="5dp"
        android:text="Hello"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF" 
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"/>

</RelativeLayout>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/drawerLayout"
 android:layout_height="match_parent"
 android:layout_width="match_parent">

   <FrameLayout 
    android:id="@+id/mainContent"
    android:layout_height="match_parent"
    android:layout_width="match_parent">    
   </FrameLayout>

   <!-- navigation drawer -->
   <ListView
        android:id="@+id/drawerList"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:divider="@null"
        android:descendantFocusability="beforeDescendants"
        android:listSelector="#FFFFFF"
        android:background="#3b5998"
        android:layout_gravity="left" />"

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:listSelector="#000000"
        android:divider="@null" />

</LinearLayout>
</android.support.v4.widget.DrawerLayout>

Images

http://s24.postimg.org/pqjmfcx5x/vaave_feed.jpg

A:

The other LinearLayout is hiding the Fragment content. The Fragment is being loaded. You need to either load the content in that Linear layout if you don't need the listview and remove the extra Frame layout.

