squidwardtenticles
squidwardtenticles

Reputation: 57

Getting an error adding a new fragment to an activity in an android app

I'm following the tutorial on the Android developer site (tutorial) and I'm getting this error:

The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, DisplayMessageActivity.PlaceholderFragment)

I've done a lot of research and it seems like the problem for most people is that they have imported the wrong thing but I have imported android.app.Fragment which is most people's solution to this error and DisplayMessageActivity.PlaceholderFragment is an extension of Fragment so I think the types should match fine (I also tried replacing new PlaceholderFragment() with new Fragment() and got the same error. I think the error is coming from this file.

Below is the code for the new activity I created with the imported files; any help would be greatly appreciated.

package com.example.myfirstapp;

import android.support.v7.app.ActionBarActivity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class DisplayMessageActivity extends ActionBarActivity {

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

    if (savedInstanceState == null){
        //ERROR IS HERE
        getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public static class PlaceholderFragment extends Fragment{
    public PlaceholderFragment(){}

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

Upvotes: 4

Views: 2463

Answers (1)

Simon Marquis
Simon Marquis

Reputation: 7516

You should use getSupportFragmentManager() when dealing with android.support.v4.app.Fragment and getFragmentManager() when dealing with android.app.Fragment.
From your example, you should use the latter.

getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();

Upvotes: 5

Related Questions