Getting an error when adding a new fragment to an action in an Android application

I follow the training course on the Android developer site ( tutorial ) and I get this error:

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

I have done a lot of research and it seems that the problem of most people is that they imported the wrong thing, but I imported android.app.Fragment, which is the majority of people resolving this error, and DisplayMessageActivity.PlaceholderFragmentis an extension (I also tried replacing new PlaceholderFragment()with new Fragment()and got the same error. I I think the error comes from this file.

Below is the code for the new action that 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;
    }
}
}
+4
source share
1 answer

You must use getSupportFragmentManager()when working with android.support.v4.app.Fragmentand getFragmentManager()when working with android.app.Fragment.
In your example, you should use the latter.

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

All Articles