title: Android: how to convert activities to fragments in order to use the navigation drawer correctly?
body: <p>I'm developing an android application that currently displays a list of articles in the MainActivity and is working correctly, i want to make the application a little more sophisticated by adding a navigation drawer that contains the articles' categories and a "Home" button above them.</p>
  
  <p>So i started a new project on Android Studio and i selected blank app with Navigation Drawer then i imported my previous app manually into this new project and i renamed my previous MainActivity to HomePage.java, because the MainActivity here is for the Navigation Drawer.</p>
  
  <p>I made many researches and i think that i have to convert my activities into fragments in order to work with Navigation Drawer, but i don't know how.</p>
  
  <p>This is the MainActivity.java:</p>
  
  <pre><code>import android.app.Activity;
  import android.content.Intent;
  import android.support.v7.app.ActionBarActivity;
  import android.support.v7.app.ActionBar;
  import android.support.v4.app.Fragment;
  import android.support.v4.app.FragmentManager;
  import android.os.Bundle;
  import android.view.LayoutInflater;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.view.View;
  import android.view.ViewGroup;
  import android.support.v4.widget.DrawerLayout;
  
  
  
  public class MainActivity extends ActionBarActivity
          implements NavigationDrawerFragment.NavigationDrawerCallbacks {
  
      /**
       * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
       */
      private NavigationDrawerFragment mNavigationDrawerFragment;
  
      /**
       * Used to store the last screen title. For use in {@link #restoreActionBar()}.
       */
      private CharSequence mTitle;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          mNavigationDrawerFragment = (NavigationDrawerFragment)
                  getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
          mTitle = getTitle();
  
          // Set up the drawer.
          mNavigationDrawerFragment.setUp(
                  R.id.navigation_drawer,
                  (DrawerLayout) findViewById(R.id.drawer_layout));
      }
  
      @Override
      public void onNavigationDrawerItemSelected(int position) {
          // update the main content by replacing fragments
  
          FragmentManager fragmentManager = getSupportFragmentManager();
          fragmentManager.beginTransaction()
                  .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                  .commit();
  
  
      }
  
      public void onSectionAttached(int number) {
          switch (number) {
              case 1:
                  mTitle = getString(R.string.title_section1); //The Home Button
                  break;
              case 2:
                  mTitle = getString(R.string.title_section2);
                  break;
              case 3:
                  mTitle = getString(R.string.title_section3);
                  break;
          }
      }
  
      public void restoreActionBar() {
          ActionBar actionBar = getSupportActionBar();
          actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
          actionBar.setDisplayShowTitleEnabled(true);
          actionBar.setTitle(mTitle);
      }
  
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          if (!mNavigationDrawerFragment.isDrawerOpen()) {
              // Only show items in the action bar relevant to this screen
              // if the drawer is not showing. Otherwise, let the drawer
              // decide what to show in the action bar.
              getMenuInflater().inflate(R.menu.main, menu);
              restoreActionBar();
              return true;
          }
          return super.onCreateOptionsMenu(menu);
      }
  
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          int id = item.getItemId();
  
          //noinspection SimplifiableIfStatement
          if (id == R.id.action_settings) {
              return true;
          }
  
          return super.onOptionsItemSelected(item);
      }
  
      /**
       * A placeholder fragment containing a simple view.
       */
      public static class PlaceholderFragment extends Fragment {
          /**
           * The fragment argument representing the section number for this
           * fragment.
           */
          private static final String ARG_SECTION_NUMBER = "section_number";
  
          /**
           * Returns a new instance of this fragment for the given section
           * number.
           */
          public static PlaceholderFragment newInstance(int sectionNumber) {
              PlaceholderFragment fragment = new PlaceholderFragment();
              Bundle args = new Bundle();
              args.putInt(ARG_SECTION_NUMBER, sectionNumber);
              fragment.setArguments(args);
              return fragment;
          }
  
          public PlaceholderFragment() {
          }
  
          @Override
          public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                   Bundle savedInstanceState) {
              View rootView = inflater.inflate(R.layout.fragment_main, container, false);
              return rootView;
          }
  
          @Override
          public void onAttach(Activity activity) {
              super.onAttach(activity);
              ((MainActivity) activity).onSectionAttached(
                      getArguments().getInt(ARG_SECTION_NUMBER));
          }
      }
  
  }
  </code></pre>
  
  <p>And this is HomePage.java : </p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.List;
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
  import android.app.ListActivity;
  import android.app.ProgressDialog;
  import android.content.Context;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.text.Html;
  import android.util.Log;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.AdapterView.OnItemClickListener;
  import android.widget.Button;
  import android.widget.ListView;
  import android.widget.TextView;
  
  
  
  public class HomePage extends ListActivity  {
  
      //Create a progress dialog instance
      private ProgressDialog pDialog;
  
      // JSON Node names
      private static final String TAG_ARTICLES = "articles";
      private static final String TAG_ID = "id";
      private static final String TAG_TITLE = "title";
      private static final String TAG_TEASER = "teaser";
      private static final String TAG_COVER_PHOTO = "cover_photo";
      String call_url = "http://www.ana.fm/api/main/?start=0&amp;count=20";
      int start_get = 0;
      int count_get = 20;
      int lastItemIndex = 0;
      ListView lv;
  
      //Articles JSONArray
      JSONArray articles = null;
  
      //Defining the articles list with type Article
      List&lt;Article&gt; articleList;
  
      Button loadMoreButton;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.home_page);
  
          articleList = new ArrayList&lt;&gt;();
  
          //Getting the ListView
          lv = getListView();
  
          //add the footer before adding the adapter, else the footer will not load!
          View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_footer, null, false);
          lv.addFooterView(footerView);
  
          //Add click listener to the load more button
          loadMoreButton = (Button) findViewById(R.id.loadMoreBtn);
  
  
          loadMoreButton.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  lastItemIndex = lv.getLastVisiblePosition();
                  start_get = start_get + 20;
                  call_url = "http://www.ana.fm/api/main/?start=".concat(String.valueOf(start_get)).concat("&amp;count=20");
                  // Calling async task to get json
                  new GetArticles().execute();
              }
          });
  
          // Listview on item click listener
          lv.setOnItemClickListener(new OnItemClickListener() {
  
              @Override
              public void onItemClick(AdapterView&lt;?&gt; parent, View view,
                                      int position, long id) {
                  String article_id = ((TextView) view.findViewById(R.id.article_id))
                          .getText().toString();
                  // Starting single article activity
                  Intent in = new Intent(getApplicationContext(),
                          SingleArticleActivity.class);
                  in.putExtra(TAG_ID, article_id);
                  startActivity(in);
  
              }
          });
          // Calling async task to get json
          new GetArticles().execute();
      }
  
      /**
       * Async task class to get json by making HTTP call
       */
      private class GetArticles extends AsyncTask&lt;Void, Void, Void&gt; {
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              // Showing progress dialog
              pDialog = new ProgressDialog(HomePage.this);
              pDialog.setMessage("Please wait...");
              pDialog.setCancelable(false);
              pDialog.show();
          }
  
          @Override
          protected Void doInBackground(Void... arg0) {
              // Creating service handler class instance
              ServiceHandler sh = new ServiceHandler();
  
              // Making a request to url and getting response
              //call_url is defined previously
  
              String jsonStr = sh.makeServiceCall(call_url, ServiceHandler.GET);
              if (jsonStr != null) {
                  try {
                      JSONObject jsonObj = new JSONObject(jsonStr);
  
                      // Getting JSON Array node
                      articles = jsonObj.getJSONArray(TAG_ARTICLES);
  
                      // looping through All Articles
                      for (int i = 0; i &lt; articles.length(); i++) {
                          JSONObject c = articles.getJSONObject(i);
  
                          String id = c.getString(TAG_ID);
                          String title = c.getString(TAG_TITLE);
                          title = Html.fromHtml(title).toString();
                          String teaser = c.getString(TAG_TEASER);
                          teaser = Html.fromHtml(teaser).toString();
                          String cover_photo = "http://www.ana.fm/med_photos/articles/";
                          cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));
  
  
                          //Getting an object from the Article class
                          Article article = new Article();
  
                          //Setting the values to the object's variables
                          article.setId(id);
                          article.setTitle(title);
                          article.setTeaser(teaser);
                          article.setImageUrl(cover_photo);
  
  
                          // adding article to the article list
                          articleList.add(article);
                      }
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              } else {
                  Log.e("ServiceHandler", "Couldn't get any data from the url");
                  //new GetContacts().execute();
              }
              return null;
          }
  
          @Override
          protected void onPostExecute(Void result) {
              super.onPostExecute(result);
              // Dismiss the progress dialog
              if (pDialog.isShowing())
                  pDialog.dismiss();
  
              /**
               * Calling my custom adapter to view the images as well
               * */
              MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, articleList);
              setListAdapter(adapter);
              lv.setSelection(lastItemIndex);
          }
      }
  }
  </code></pre>
  
  <p>Now what i want is to be navigated to the HomePage.java after clicking on the "Home" button on the Navigation Drawer (Side Menu).</p>
  
  <p>Anyone can help ?</p>