java - RuntimeException : android. view.InflateException:二进制 XML 文件行 #8:膨胀类 fragment 时出错

标签 java android facebook android-fragments

我想将我的 Google map 与 Facebook SDK 集成,以通过 Facebook 检查位置并在同一布局中共享它,但是当我将此代码添加到方法 onCreate() 时,它会强制关闭并报告错误

if (savedInstanceState == null) {
    // Add the fragment on initial activity setup
    mainFragment = new MainFragment();

    getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
    myFragmentManager = getSupportFragmentManager();
    mainFragment = (MainFragment) myFragmentManager.findFragmentById(R.id.checkIn);
} else {
    // Or set the fragment from restored state info
    mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}

这是我的 onCreate() 方法

protected void onCreate(final Bundle savedInstanceState) {
    try {

        // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_in);



        checkInButton = (Button) findViewById(R.id.shareButton);
        checkInButton.setVisibility(View.VISIBLE);

        authButton = (Button)findViewById(R.id.authButton);
        authButton.setVisibility(View.VISIBLE);


        endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
        endLocationEditText.setVisibility(View.INVISIBLE);
        startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
        startLocationEdittext.setVisibility(View.INVISIBLE);

        toggle = (ToggleButton) findViewById(R.id.togglebutton);
        toggle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasConnection(getApplicationContext()) == true) {
                    if (toggle.isChecked()) {
                        endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
                        endLocationEditText.setVisibility(View.VISIBLE);
                        startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
                        startLocationEdittext.setVisibility(View.INVISIBLE);
                        goButton.setVisibility(View.VISIBLE);
                    } else {
                        endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
                        endLocationEditText.setVisibility(View.INVISIBLE);
                        startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
                        startLocationEdittext.setVisibility(View.VISIBLE);
                        goButton.setVisibility(View.VISIBLE);
                    }

                    checkInButton.setVisibility(View.VISIBLE);
                    checkInButton.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            endLocationEditText
                                    .setVisibility(View.INVISIBLE);
                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    CheckIn.this);
                            builder.setTitle("Attach photo?");
                            builder.setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {

                                        }

                                    });
                            builder.setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            Intent captureIntent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            startActivityForResult(
                                                    captureIntent,
                                                    CAMERA_CAPTURE);
                                        }
                                    });
                            builder.show();

                        }
                    });
                } else {
                    System.out.println("ยังไม่ได้ต่อเน็ต");
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            CheckIn.this);
                    builder.setTitle("Please connect to the Internet.");
                    builder.show();
                }

            }
        });

        goButton = (Button) findViewById(R.id.goButton);
        goButton.setVisibility(View.INVISIBLE);
        goButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (toggle.isChecked() == true) {
                    String location = endLocationEditText.getText()
                            .toString();
                    if (location != null && !location.equals("")) {
                        new GeocoderTask().execute(location);
                    }
                } else {
                    String location = startLocationEdittext.getText()
                            .toString();
                    if (location != null && !location.equals("")) {
                        new GeocoderTask().execute(location);
                    }
                }

            }
        });

        myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = myLocationManager.getBestProvider(criteria, true);
        Location location = myLocationManager
                .getLastKnownLocation(provider);
        if (location != null) {
            onLocationChanged(location);
        }

        myLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 20000, 0, this);

        // สำหรับแสดง Google maps v2
        FragmentManager myFragmentManager = getSupportFragmentManager();
        SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager
                .findFragmentById(R.id.checkIn);
        myMap = mySupportMapFragment.getMap();
        myMap.setMyLocationEnabled(true);
        fromMarkerPosition = new LatLng(location.getLatitude(),
                location.getLongitude());
        toMarkerPosition = fromMarkerPosition;
        myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                fromMarkerPosition, 13));
        myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        myMap.addMarker(new MarkerOptions()
                .position(fromMarkerPosition)
                .title("Yor are here!")
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        myMap.getUiSettings().setCompassEnabled(true);
        myMap.getUiSettings().setZoomControlsEnabled(true);
        /* จบการแสดง maps */

        // สร้าง click event สำหรับระบุพิกัดจุด
        myMap.setOnMapClickListener(new OnMapClickListener() {
            public void onMapClick(LatLng arg0) {

                if (hasConnection(getApplicationContext()) == true) {
                    final LatLng coordinate = arg0;
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            CheckIn.this);

                    endLocationEditText.setVisibility(View.INVISIBLE);
                    startLocationEdittext.setVisibility(View.INVISIBLE);
                    goButton.setVisibility(View.INVISIBLE);
                    System.out
                            .println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                    builder.setTitle("Select Marker").setItems(
                            new String[] { "From", "To" },
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int position) {

                                    try {
                                        if (position == 0) {
                                            fromMarkerPosition = coordinate;
                                            System.out
                                                    .println(fromMarkerPosition
                                                            + " yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
                                            refreshMarker();
                                        } else if (position == 1) {
                                            toMarkerPosition = coordinate;
                                            System.out
                                                    .println(toMarkerPosition
                                                            + " ttttttttttttttttttttttttttttttttttttttt");
                                            refreshMarker();
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        System.out
                                                .println("Please connect to the internet first");
                                    }
                                }
                            });
                    builder.show();
                    myMap.animateCamera(CameraUpdateFactory
                            .newLatLng(coordinate));

                    checkInButton.setVisibility(View.VISIBLE);
                    checkInButton.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            endLocationEditText
                                    .setVisibility(View.INVISIBLE);
                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    CheckIn.this);
                            builder.setTitle("Attach photo?");
                            builder.setNegativeButton("No",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {

                                        }

                                    });
                            builder.setPositiveButton("Yes",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            Intent captureIntent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            startActivityForResult(
                                                    captureIntent,
                                                    CAMERA_CAPTURE);
                                        }
                                    });
                            builder.show();

                        }
                    });
                } else {
                    System.out.println("ยังไม่ได้ต่อเน็ต");
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            CheckIn.this);
                    builder.setTitle("Please connect to the Internet.");
                    builder.show();
                }

            }
        });

        if (savedInstanceState == null) {
            // Add the fragment on initial activity setup

            mainFragment = new MainFragment();
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
            myFragmentManager = getSupportFragmentManager();
             mainFragment = (MainFragment) myFragmentManager
                    .findFragmentById(R.id.checkIn);
        } else {

            // Or set the fragment from restored state info
            mainFragment = (MainFragment) getSupportFragmentManager()
            .findFragmentById(android.R.id.content);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}// end onCreate

这是我的 MainFragment 类........

public class MainFragment extends Fragment{

private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private Button shareButton;
private UiLifecycleHelper uiHelper;
private static final String TAG = "MainFragment";

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(getActivity(), callback);
    uiHelper.onCreate(savedInstanceState);

}

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

    LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
    authButton.setFragment(this);
    authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));

    shareButton = (Button) view.findViewById(R.id.shareButton);
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            publishStory();        
        }
    });

    if (savedInstanceState != null) {
        pendingPublishReauthorization = 
            savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
    }
    return view;
}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (state.isOpened()) {
        Log.i(TAG, "Logged in...");
    } else if (state.isClosed()) {
        Log.i(TAG, "Logged out...");
    }

    if (state.isOpened()) {
        shareButton.setVisibility(View.VISIBLE);
        if (pendingPublishReauthorization && 
                state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
            pendingPublishReauthorization = false;
            publishStory();
        }
    } else if (state.isClosed()) {
        shareButton.setVisibility(View.INVISIBLE);
    }
}


private void publishStory() {
    Session session = Session.getActiveSession();

    if (session != null){

        // Check for publish permissions    
        List<String> permissions = session.getPermissions();
        if (!isSubsetOf(PERMISSIONS, permissions)) {
            pendingPublishReauthorization = true;
            Session.NewPermissionsRequest newPermissionsRequest = new Session
                    .NewPermissionsRequest(this, PERMISSIONS);
        session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }

        Bundle postParams = new Bundle();
        postParams.putString("name", "Facebook SDK for Android");
        postParams.putString("caption", "Build great social apps and get more installs.");
        postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
        postParams.putString("link", "https://developers.facebook.com/android");
        postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

        Request.Callback callback= new Request.Callback() {
            public void onCompleted(Response response) {
                JSONObject graphResponse = response
                                           .getGraphObject()
                                           .getInnerJSONObject();
                String postId = null;
                try {
                    postId = graphResponse.getString("id");
                } catch (JSONException e) {
                    Log.i(TAG,
                        "JSON error "+ e.getMessage());
                }
                FacebookRequestError error = response.getError();
                if (error != null) {
                    Toast.makeText(getActivity()
                         .getApplicationContext(),
                         error.getErrorMessage(),
                         Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity()
                             .getApplicationContext(), 
                             postId,
                             Toast.LENGTH_LONG).show();
                }
            }
        };

        Request request = new Request(session, "me/feed", postParams, 
                              HttpMethod.POST, callback);

        RequestAsyncTask task = new RequestAsyncTask(request);
        task.execute();
    }

}

private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
    for (String string : subset) {
        if (!superset.contains(string)) {
            return false;
        }
    }
    return true;
}

@Override
public void onResume() {
    super.onResume();
    Session session = Session.getActiveSession();
    if (session != null &&
           (session.isOpened() || session.isClosed()) ) {
        onSessionStateChange(session, session.getState(), null);
    }

    uiHelper.onResume();
}

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

@Override
public void onPause() {
    super.onPause();
    uiHelper.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
    uiHelper.onSaveInstanceState(outState);
}

}

xml 第 8 行在这里

<fragment
    android:id="@+id/checkIn"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/authButton"
    class="com.google.android.gms.maps.SupportMapFragment" />

这里有一个错误

03-09 20:17:15.433: E/AndroidRuntime(12547): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
03-09 20:17:15.433: E/AndroidRuntime(12547): Caused by: java.lang.IllegalArgumentException: Binary XML file line #8: Duplicate id 0x7f04000a, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment

最佳答案

看看http://code.google.com/p/gmaps-api-issues/issues/detail?id=5064#c1了解如何将 SupportMapFragment 正确放入 fragment 内。

关于java - RuntimeException : android. view.InflateException:二进制 XML 文件行 #8:膨胀类 fragment 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15310942/

相关文章:

java - 如果您正在使用缓冲读取器读取整行,那么在套接字上设置超时是否有效?

java - 用java在数据库服务器中创建文件

java - 我获得了 listView 中每个项目的 key 并将其保存到 Firebase 我想将该 key 发送到另一个 Activity ,但每次我获得相同的 key

android - 无法使 Android ImageSwitcher 背景透明

java - 获取没有 toString() 的枚举字符串

android - React Native 构建在 android 中失败,@react-native-community/cli-platform-android/native_modules.gradle' 行 : 130

android - 在 android 中使用谷歌 token 执行 HttpPost 不获取 JSON 数据

Facebook Pixel 查看 AMP 页面中的内容

javascript - 使用 javascript 获取 facebook 分享数

javascript - 加载跨域内容时触发事件?