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 Sending Messages Selecting Recipients

James N
James N
17,864 Points

the sections pager activity has problems that I don't understand!!!

SectionsPagerActivity.java
package james.ribbit;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v13.app.FragmentPagerAdapter;

import java.util.Locale;


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

        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(); // the errors are here
                case 1:
                    return new FriendsFragment(); // the errors are here
            }
            return null;
        }

        @Override
        public int getCount() {
            // Show 2 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            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;
        }
    }

can I please have some help with this code!?!?!?! thanks! if you need to see my other code, just ask.

Henrik Hansen
Henrik Hansen
23,176 Points

Does your Friends- and InboxFragment extend ListFragment?

What is the error?

James N
James N
17,864 Points

my friends & inbox fragments are both extending list fragment. my errors are:

Error:(30, 28) error: incompatible types: InboxFragment cannot be converted to Fragment

and

Error:(32, 28) error: incompatible types: FriendsFragment cannot be converted to Fragment
Henrik Hansen
Henrik Hansen
23,176 Points

Are you using the correct library?

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

// ....

new SectionsPagerAdapter( getSupportFragmentManager() );
James N
James N
17,864 Points

thanks! that did the trick!

I did have similar imports: import android.support.v13.app.FragmentPagerAdapter; import android.app.FragmentManager; and import android.app.Fragment; but your versions work! thanks!!!

UPDATE: there is one problem with your new import statements: in main activity (I called it my activity because it was android studio's default): there was an error.

myActivity.java
package james.ribbit;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
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 android.view.Window;
import android.widget.Toast;

import com.parse.ParseUser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class MyActivity extends Activity implements ActionBar.TabListener {
    public static final String TAG = MyActivity.class.getSimpleName();
    public static final int TakePhotoRequest = 0;
    public static final int TakeVideoRequest = 1;
    public static final int GetPhotoRequest = 2;
    public static final int GetVideoRequest = 3;
    public static final int MediaTypeImage= 4;
    public static final int MediaTypeVideo= 5;
    public static final int FILE_SIZE_LIMIT = 1024*1024*10 ; // 10 mb

    protected Uri mMediaUri;
    /**
     * The {@link /android.support.v4.view.(without /)"PagerAdapter(without the ")} that will provide
     * fragments for each of the sections. We use a
     * {@link "FragmentPagerAdapter(without the ")} 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.v13.app.(without /)"FragmentStatePagerAdapter(without the ")}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link "ViewPager(without the ")} that will host the section contents.
     */
    ViewPager mViewPager;
    protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int which) {
            switch (which) {
                case 0: // Take pic
                    Intent TakePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    mMediaUri = getOutputMediaFileUri(MediaTypeImage);
                    if (mMediaUri==null) {
                        //display some sort of error
                        Toast.makeText(MyActivity.this,R.string.error_storage_external,Toast.LENGTH_LONG).show();
                    }
                    else {
                        TakePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                        startActivityForResult(TakePhotoIntent, TakePhotoRequest);
                    }

                    break;
                case 1: // Take vid
                    Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    mMediaUri = getOutputMediaFileUri(MediaTypeVideo);
                    if (mMediaUri==null) {
                        //display some sort of error
                        Toast.makeText(MyActivity.this,R.string.error_storage_external,Toast.LENGTH_LONG).show();
                    }
                    else {
                        videoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mMediaUri);
                        videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,10);
                        videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,0); // 0 = low res, 1 = high res
                        startActivityForResult(videoIntent,TakeVideoRequest);
                    }
                    break;
                case 2: // Choose pic
                    Intent ChoosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    ChoosePhotoIntent.setType("image/*");
                    startActivityForResult(ChoosePhotoIntent,GetPhotoRequest);
                    break;
                case 3: // Choose vid
                    Intent ChooseVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    ChooseVideoIntent.setType("video/*");
                    Toast.makeText(MyActivity.this,getString(R.string.video_warning) ,Toast.LENGTH_LONG).show();
                    startActivityForResult(ChooseVideoIntent, GetPhotoRequest);


                    break;
            }
        }


    };

    private Uri getOutputMediaFileUri(int mediaType) {

        if (isExternalStorageAvailible()) {
            //get uri
            //1  DIR
            String appName = MyActivity.this.getString(R.string.app_name);
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),appName);
            //2 create subDIR
            if (! mediaStorageDir.exists()) {
                if (mediaStorageDir.mkdirs()) {
                    Log.e(TAG,"FAILED IN CREATING DIR");
                    return null;
                }
            }

            //3 create filename

            //4 create file
            File mediaFile;
            Date now = new Date();
            String time = new SimpleDateFormat("MMddyyyy_HHmmss", Locale.getDefault()).format(now);
            String path = mediaStorageDir.getPath() + File.separator;
            if (mediaType == MediaTypeImage ) {
                mediaFile = new File(path+"IMAGE_"+time+".jpg");
            }
            else if (mediaType == MediaTypeVideo) {
                mediaFile = new File(path+"VIDEO_"+time +".mp4");
            }
            else {
                return null;
            }
            Log.d(TAG,"File " + Uri.fromFile(mediaFile));
            //5 return file

            return Uri.fromFile(mediaFile);
        }
        else {
            return null;
        }

    }
    private boolean isExternalStorageAvailible() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        else { return false;}
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my);
        ParseUser currentUser = ParseUser.getCurrentUser();
        if (currentUser == null) {

            navigateToLogin();
        } else {
            Log.i(TAG,currentUser.getUsername());
        }
        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

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

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

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //Add to gallery

            if (requestCode == GetPhotoRequest || requestCode == GetVideoRequest) {
                if (data == null) {
                    Toast.makeText(this, getString(R.string.general_error),Toast.LENGTH_LONG);
                } else {
                    mMediaUri = data.getData();
                    Log.i(TAG,"Media URI:" + mMediaUri);
                }
                if (requestCode == GetVideoRequest) {
                    // make sure vid is less than 10 mb
                    int filesize = 0;
                    InputStream inputStream = null;
                    try {
                        inputStream = getContentResolver().openInputStream(mMediaUri);
                        filesize = inputStream.available();
                    }
                    catch (FileNotFoundException e) {
                        Toast.makeText(this,getString(R.string.error_file),Toast.LENGTH_LONG).show();
                        return;
                    }
                    catch (IOException e) {
                        Toast.makeText(this,getString(R.string.error_file),Toast.LENGTH_LONG).show();
                        return;
                    }
                    finally {
                        try {
                            inputStream.close();
                        }
                        catch (IOException e){/* BLANK/!!!! */}
                    }
                    if (filesize >= FILE_SIZE_LIMIT) {
                        Toast.makeText(this,"this file is too large. Please select a different file.",Toast.LENGTH_LONG).show();
                        return;
                    }

                }
            } else {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                mediaScanIntent.setData(mMediaUri);
                sendBroadcast(mediaScanIntent);
            }

            Intent recipientsIntent = new Intent(this,RecipientsActivity.class);
            recipientsIntent.setData(mMediaUri);
            String fileType;
            if (requestCode == TakePhotoRequest || requestCode == GetPhotoRequest) {
                fileType = ParseConstants.TYPE_IMAGE;

            } else {
                fileType = ParseConstants.TYPE_VIDEO;
            }

            recipientsIntent.putExtra(ParseConstants.KEY_FILE_TYPE,fileType);
            startActivity(recipientsIntent);

        }
        else if (resultCode != RESULT_CANCELED) {
            Toast.makeText(this,getString(R.string.general_error),Toast.LENGTH_LONG).show();
        }

    }

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        switch(id){
            case R.id.action_logout:
                ParseUser.logOut();
                navigateToLogin();
            case R.id.action_edit_friends:
                Intent intent = new Intent(this,EditFriendsActivity.class);
                startActivity(intent);
            case R.id.action_camera:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setItems(R.array.camera_choices,mDialogListener);
                builder.show();
        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }



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




        public PlaceholderFragment() {
        }

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

}

my error is: Error:(179, 81) error: incompatible types: android.app.FragmentManager cannot be converted to android.support.v4.app.FragmentManager

James N
James N
17,864 Points

also, I would like to inform you, there is someone who made this forum post who I am trying to help out, but I don't understand what is causing his problem, so I was thinking you could help him. I will link you to this forum post: https://teamtreehouse.com/forum/hi-my-edit-friendspage-is-taking-the-full-page-of-the-phone-did-i-forget-something

1 Answer

Henrik Hansen
Henrik Hansen
23,176 Points

The issue, I belive, is that you use the Android.app.ActionBar and others when you are supposed to use the support libraries. You can compare your imports to mine. If you have the "wrong" import statement, you will have to specifi the library you want to use when instantiating the variable.

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;                                 // Epecially check the support libraries
import android.support.v4.app.FragmentManager;                  // and replace the standard ones like
import android.support.v4.app.FragmentPagerAdapter;         // android.app.ActionBar
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.Menu;
import android.view.MenuItem;
import android.widget.Toast;

// Defining the variable when using "wrong" import
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
James N
James N
17,864 Points

I don't understand... so what am I supposed to do with my imports?

myactivity.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import android.support.v4.view.ViewPager;
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 android.view.Window;

import android.widget.Toast;


import com.parse.ParseUser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.Locale;
Henrik Hansen
Henrik Hansen
23,176 Points

Instead of android.app.Actionbar, you have to use the v7 support library imports. And instead of the android.app.Fragment, you must use the v4 support libraries. You can fin the correct names in the list i submitted. Just replace them.

James N
James N
17,864 Points

can you give me code to copy and paste my imports into?