Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Self-Destructing Message Android App Using Fragments for Tabs Modifying Fragments from the Template

Andre Colares
Andre Colares
5,437 Points

DROID YOU ARE LOOKING FOR - CODE FOR THIS VIDEO

After a lot of googling and reading other questions here in the forum, I solved all my errors and now is working. Here is the code for all files:

SECTIONSPAGEADAPTER:

package com.andrecolares.ribbit;

/**

  • Created by Andre on 14/10/2015. */ import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter;

import java.util.Locale;

/**

  • A {@link FragmentPagerAdapter} that returns a fragment corresponding to
  • one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter {

    // In the lesson, we factor this code out of MainActivity.class, and thus must add the context // as a member variable that gets passed in through the constructor. Nothing about this // will change from the video, no deprecation involved, no Android Studio conflicts.

    protected Context mContext;

    public SectionsPagerAdapter(Context context, FragmentManager fm) { super(fm); mContext = context; }

    @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). switch (position){ case 0: return new InboxFragment(); case 1: return new FriendsFragment(); }

    return new InboxFragment();
    

    }

    @Override public int getCount() { // In the video we reduce this boilerplate value from 3 // to 2 tabs, one for Inbox and one for Friends. Again, no // change needed from the video, follow along. // Show 2 total pages. return 2; }

    @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); // this is where we'll pass the context to variables that are now // outside the scope of MainActivity.class after the refactor. // again, nothing different than the video, follow the video. // Remember to delete the third case in the boilerplate code // and change the strings resources entries to Inbox and // Friends, respectively, just like in the video. switch (position) { case 0: return mContext.getString(R.string.title_section1).toUpperCase(l); case 1: return mContext.getString(R.string.title_section2).toUpperCase(l); } return null; } }

MAIN ACTIVITY:

package com.andrecolares.ribbit;

import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup;

import com.parse.ParseUser;

// The TabListener has been deprecated, will look for update later // **The MainActivity class is implementing TabListener, so the ** // *** activity itself is listening for tab changes. We'll have to *** // *** replace this later. Remember that TabListener is an interface,*** // *** so we'll be looking for a replacement interface later. *** public class MainActivity extends ActionBarActivity {

public static final String TAG = MainActivity.class.getSimpleName();

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;


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

    // Get the user cached on disk if present
    ParseUser currentUser = ParseUser.getCurrentUser();

    if (currentUser == null) {
        // If no one is logged in, go to the login screen
        navigateToLogin();
    } else {
        Log.i(TAG, currentUser.getUsername());
    }


    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();

    // ***This is where setNavigationMode has been deprecated***


    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@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
    switch (id) {

        case R.id.action_logout:
            ParseUser.logOut();
            navigateToLogin();
            break;
    }
    return super.onOptionsItemSelected(item);
}


private void navigateToLogin() {
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}






/**
 * A placeholder fragment containing a simple view.
 * This is referred to as "DummySectionFragment" in the
 * lesson.
 */
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";

    public PlaceholderFragment() {
    }

    /**
     * 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;
    }

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

INBOX FRAGMENT:

package com.andrecolares.ribbit;

import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;

// Inbox will be a list of messages public class InboxFragment extends ListFragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_inbox, container,
            false);

    return rootView;
}

}

INBOX LAYOUT: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" >

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/empty"
    android:text="@string/empty_inbox_label"/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"/>

</LinearLayout>

FRIENDS FRAGMENT:

package com.andrecolares.ribbit;

import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;

// Inbox will be a list of messages public class FriendsFragment extends ListFragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_friends, container,
            false);

    return rootView;
}

}

FRIENDS LAYOUT:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" >

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/empty"
    android:text="@string/empty_friends_label"/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"/>

</LinearLayout>

STRINGS VALUES:

<resources> <string name="app_name">Ribbit</string>

<string name="title_section1">Inbox</string>
<string name="title_section2">Friends</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>
<string name="title_activity_login">LoginActivity</string>
<string name="username_hint">Username</string>
<string name="password_hint">Password</string>
<string name="login_button_label">Login</string>
<string name="sign_up_text">Sign Up!</string>
<string name="title_activity_sign_up">SignUpActivity</string>
<string name="email_hint">Email</string>
<string name="sign_up_button_label">Sign Up</string>
<string name="signup_error_message">Please make sure you enter a username, password and email address!</string>
<string name="signup_error_title">Oops!</string>
<string name="login_error_message">Please make sure you enter a username and password!</string>
<string name="login_error_title">Oops!</string>
<string name="menu_logout_label">Logout</string>
<string name="empty_inbox_label">No new messages!</string>
<string name="empty_friends_label">Add friends to begin!</string>

</resources>

1 Answer

Andre Colares
Andre Colares
5,437 Points

If someone else wants some help at this point of the code , I can help... Thumbs up if it saved you time!