6216
以下の様な`fragment`を2つ並べたようなViewを作ったのですが､Activityの`setContentView`で以下のエラーが出てしまいます｡

**activity_video_player.xml:**

```

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.wotageishika.zousan.wotageishika.VideoPlayerActivity"
    android:orientation="vertical">
    
    <fragment
        android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
        android:id="@+id/youtube_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </fragment>
    
    <fragment
        android:name="com.wotageishika.zousan.wotageishika.VideoInfoFragment"
        android:id="@+id/video_info_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </fragment>
    </LinearLayout>
    
```

**エラー:**

```

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wotageishika.zousan.wotageishika/com.wotageishika.zousan.wotageishika.VideoPlayerActivity}: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
            at android.app.Activity.setContentView(Activity.java:2144)
            at com.wotageishika.zousan.wotageishika.VideoPlayerActivity.onCreate(VideoPlayerActivity.java:26)
            at android.app.Activity.performCreate(Activity.java:5933)
    ......
    
```

続けて､問題の起こった`fragment`と`activity`を示します｡

**VideoPlayerActivity:**

```

    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    
    import com.google.android.youtube.player.YouTubeInitializationResult;
    import com.google.android.youtube.player.YouTubePlayer;
    import com.google.android.youtube.player.YouTubePlayerSupportFragment;
    
    
    public class VideoPlayerActivity extends FragmentActivity implements YouTubePlayer.OnInitializedListener,
        VideoInfoFragment.OnFragmentInteractionListener{
    private static final String VIDEO_ID = "videoId";
    private String apiKey;
    private YouTubePlayerSupportFragment player;
    private String videoId;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);
    
        //videoIdを取得
        Intent data = getIntent();
        Bundle extras = data.getExtras();
        videoId = extras !=null ? extras.getString(VIDEO_ID) : "";
    
        //プレイヤを読み込む
        player = (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_fragment);
        apiKey=DeveloperKey.API_KEY;
        //プレイヤーを初期化
        player.initialize(apiKey, this);
    
        VideoInfoFragment viFragment = (VideoInfoFragment)getSupportFragmentManager().findFragmentById(R.id.video_info_fragment);
        viFragment.getVideoId(videoId);
    }
    
    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        if(!b){
            youTubePlayer.cueVideo(videoId);
        }
    }
    
    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
    
    }
    
    @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_video_player, 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
        if (id == R.id.action_settings) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onFragmentInteraction(Uri uri){
    
    }
    }
    
```

**VideoInfoFragment:**

```

    import android.app.Activity;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ListView;
    
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.JsonRequest;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    import org.json.JSONObject;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class VideoInfoFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    
    // TODO: Rename and change types of parameters
    private RequestQueue mQueue;
    private String videoId;
    private VideoDetail videoDetail;
    private VideoItems videoItem;
    private ChannelSearchResult chSearch;
    private ChannelSearchItems chItem;
    private VideoDetail suggestVideoDetail;
    private List<VideoItems> suggestVideoList1;
    private List<VideoItems> suggestVideoList2;
    private VideoSearchResult suggestVideoSearchResult;
    private String apiKey;
    private ListView mListView;
    
    private OnFragmentInteractionListener mListener;
    
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment VideoInfoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static VideoInfoFragment newInstance() {
        VideoInfoFragment fragment = new VideoInfoFragment();
        return fragment;
    }
    
    public VideoInfoFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        mQueue = RequestSingleton.getInstance(getActivity().getApplicationContext()).getRequestQueue();
        apiKey = DeveloperKey.API_KEY;
        suggestVideoList1 = new ArrayList<>();
        suggestVideoList2 = new ArrayList<>();
    
        //再生動画の動画情報をリクエスト
        String videoRequestUrl = "https://www.googleapis.com/youtube/v3/videos?part=id,snippet,contentDetails,statistics&id="
                + videoId + "&key=" + apiKey;
        videoRequest(videoRequestUrl);
    
        //再生動画のチャンネル情報をリクエスト
        String channelRequestUrl = "https://www.googleapis.com/youtube/v3/channels?part=id,snippet,statistics&id="
                + videoItem.snippet.channelId + "&key=" + apiKey;
        channelRequest(channelRequestUrl);
    
        //おすすめ動画の検索ワード(Tagを追加する)
        String searchWord = videoItem.snippet.tags.get(0);
        for(int i=1; i<videoItem.snippet.tags.size(); i++){
            searchWord += " | " + videoItem.snippet.tags.get(i);
        }
    
        //おすすめ動画を検索
        String suggestVideosListRequestUrl = "https://www.googleapis.com/youtube/v3/search?part=id" +
                "&q=" + searchWord + "&maxResults=20" + "&type=video&videoDefinition=high&key=" + apiKey;
        suggestVideosListRequest(suggestVideosListRequestUrl);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle saveInstanceState){
        final View view = inflater.inflate(R.layout.fragment_video_info, container, false);
        this.mListView = (ListView)view.findViewById(R.id.video_info_list);
        InfoListAdapter adapter = new InfoListAdapter(getActivity().getApplicationContext(),
                videoItem, chItem, suggestVideoList1);
        this.mListView.setAdapter(adapter);
    
        return view;
    }
    
    //動画情報をリクエスト
    private void videoRequest(String url){
        RequestSingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(new JsonObjectRequest(JsonRequest.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    
                videoDetail = gson.fromJson(response.toString(), VideoDetail.class);
                videoItem = videoDetail.items.get(0);
    
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }));
    }
    
    //チャンネル情報をリクエスト
    private void channelRequest(String url){
        RequestSingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(new JsonObjectRequest(JsonRequest.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    
                chSearch = gson.fromJson(response.toString(), ChannelSearchResult.class);
                chItem = chSearch.items.get(0);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }));
    }
    
    //おすすめ動画を20個検索
    private void suggestVideosListRequest(String url){
        RequestSingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(new JsonObjectRequest(JsonRequest.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    
                suggestVideoSearchResult = gson.fromJson(response.toString(), VideoSearchResult.class);
    
                String suggestVideoIds = suggestVideoSearchResult.items.get(0).id.videoId;
                for(int i=1; i<suggestVideoSearchResult.items.size(); i++){
                    suggestVideoIds += "," + suggestVideoSearchResult.items.get(i).id.videoId;
                }
    
                String suggestVideosSearchUrl = "https://www.googleapis.com/youtube/v3/videos?" +
                        "part=id,snippet,contentDetails,statistics&id=" + suggestVideoIds +
                        "&key=" + apiKey;
                suggestVideosRequest(suggestVideosSearchUrl);
    
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }));
    }
    
    //おすすめ動画の動画情報をリクエスト
    private void suggestVideosRequest(String url){
        RequestSingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(new JsonObjectRequest(JsonRequest.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    
                suggestVideoDetail = gson.fromJson(response.toString(), VideoDetail.class);
                for(int i=0; i<9; i++){
                    if(!suggestVideoDetail.items.isEmpty()) {
                        suggestVideoList1.add(suggestVideoDetail.items.get(i));
                    }else{
                        break;
                    }
                }
                for(int i=9; i<20; i++){
                    if(!suggestVideoDetail.items.isEmpty()) {
                        suggestVideoList2.add(suggestVideoDetail.items.get(i));
                    }else{
                        break;
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }));
    }
    
    @Override
    public void onPause(){
        if(mQueue!=null){
            mQueue.stop();
        }
    }
    
    @Override
    public void onResume(){
        if(mQueue!=null){
            mQueue.start();
        }
    }
    
    
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }
    
    /*ここからオリジナルのコードです｡*/
    public void getVideoId(String videoId){
        this.videoId=videoId;
    }
    
```

}

ちなみに､この`VideoInfoFragment`を追加する以前はエラーは出ませんでした｡  
あと関係があるのかわからないのですが､`AndroidManifest`で`NoActionBar`を指定しています｡  
このエラーについて､検索し､様々な方法を試しましたが結局､直りませんでした｡  
どなたか解決方法がわかる方､教えて頂ければ幸いです｡  
よろしくお願いします｡
CC BY-SA 3.0
2015-02-09T12:38:36.993
6192
2015-02-10T03:10:30.760
2015-02-09T13:17:25.260
7232
7232
question
android android-fragments
inflating class fragment が出てしまう｡
解決しました｡

`Fragment`を静的に設置した場合､`onCreate`､`onCreateView`内では､まだ親のActivityが生成されていないので､`getActivity()`を呼ぶことができませんでした｡
なので､`onCreateView`で呼ぶ必要がある場合は､`Fragment`を動的に生成する必要があるようでした｡
CC BY-SA 3.0
2015-02-10T03:10:30.760
6216
2015-02-10T03:10:30.760
7232
6192
answer