0

我正在尝试使用 facebook 的“Hackbook”应用程序作为对我的编码的参考,这是一个片段而不是活动......但是我在第 64 行遇到错误,即:

            mText = (TextView) getView().findViewById(R.id.txt);

日志猫:

    05-20 17:47:34.741: W/dalvikvm(1766): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    05-20 17:47:34.761: E/AndroidRuntime(1766): FATAL EXCEPTION: main
    05-20 17:47:34.761: E/AndroidRuntime(1766): java.lang.NullPointerException
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at com.projectcaruso.naturalfamilyplaning.LoginFragment.init(LoginFragment.java:78)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at com.projectcaruso.naturalfamilyplaning.LoginFragment.onCreateView(LoginFragment.java:61)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.os.Handler.handleCallback(Handler.java:725)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.os.Handler.dispatchMessage(Handler.java:92)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.os.Looper.loop(Looper.java:137)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at android.app.ActivityThread.main(ActivityThread.java:5041)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at java.lang.reflect.Method.invokeNative(Native Method)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at java.lang.reflect.Method.invoke(Method.java:511)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    05-20 17:47:34.761: E/AndroidRuntime(1766):     at dalvik.system.NativeStart.main(Native Method)

片段:包com.projectcaruso.naturalfamilyplaning;

import org.json.JSONException;
import org.json.JSONObject;
import com.projectcaruso.naturalfamilyplaning.R;
import com.projectcaruso.naturalfamilyplaning.SessionEvents.AuthListener;
import com.projectcaruso.naturalfamilyplaning.SessionEvents.LogoutListener;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.Util;



@SuppressWarnings("deprecation")
public class LoginFragment extends Fragment implements OnClickListener{

    /*
     * Your Facebook Application ID must be set before running this example See
     * http://www.facebook.com/developers/createapp.php
     */
    public static String APP_ID;

    private LoginButton mLoginButton;
    private TextView mText;
    private ImageView mUserPic;
    private Handler mHandler;
    ProgressDialog dialog;

    final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
    final static int PICK_EXISTING_PHOTO_RESULT_CODE = 1;

    String[] permissions = { "offline_access", "publish_stream", "user_photos", "publish_checkins",
    "photo_upload" };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (APP_ID == null) {
            Util.showAlert(getActivity(), "Warning", "Facebook Applicaton ID must be "
                    + "specified before running this example: see FbAPIs.java");
            return;
        }
    }         


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, null);
         init();
        mHandler = new Handler();

        /*
         * Source Tag: login_tag
         */
        mLoginButton.init(getActivity(), AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

        if (Utility.mFacebook.isSessionValid()) {
            requestUserData();
        }

        return view;
    }


    private void init() {
        mText = (TextView) getView().findViewById(R.id.txt);
        mUserPic = (ImageView) getView().findViewById(R.id.user_pic);

        APP_ID = getResources().getString(R.string.app_id);

        // Create the Facebook Object using the app id.
        Utility.mFacebook = new Facebook(APP_ID);
        // Instantiate the asynrunner object for asynchronous api calls.
        Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

        mLoginButton = (LoginButton) getView().findViewById(R.id.login);

        // restore session if one exists
        SessionStore.restore(Utility.mFacebook, getActivity());
        SessionEvents.addAuthListener(new FbAPIsAuthListener());
        SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
    }

    /*
     * Request user name, and picture to show on the main screen.
     */
    public void requestUserData() {
        mText.setText("Fetching user name, profile pic...");
        Bundle params = new Bundle();
        params.putString("fields", "name, picture");
        Utility.mAsyncRunner.request("me", params, new UserRequestListener());
    }

    /*
     * Callback for fetching current user's name, picture, uid.
     */
    public class UserRequestListener extends BaseRequestListener {

        @Override
        public void onComplete(final String response, final Object state) {
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(response);

                final String picURL = jsonObject.getJSONObject("picture")
                        .getJSONObject("data").getString("url");
                final String name = jsonObject.getString("name");
                Utility.userUID = jsonObject.getString("id");

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mText.setText("Welcome " + name + "!");
                        mUserPic.setImageBitmap(Utility.getBitmap(picURL));
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    public class FbAPIsAuthListener implements AuthListener {

        @Override
        public void onAuthSucceed() {
            requestUserData();
        }

        @Override
        public void onAuthFail(String error) {
            mText.setText("Login Failed: " + error);
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    /*
     * The Callback for notifying the application when log out starts and
     * finishes.
     */
    public class FbAPIsLogoutListener implements LogoutListener {
        @Override
        public void onLogoutBegin() {
            mText.setText("Logging out...");
        }

        @Override
        public void onLogoutFinish() {
            mText.setText("You have logged out! ");
            mUserPic.setImageBitmap(null);
        }
    }

}

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Facebook login -->
        <ImageView
            android:id="@+id/user_pic"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="6dip" />
        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/user_pic" />

        <com.projectcaruso.naturalfamilyplaning.LoginButton
            android:id="@+id/login"
            android:src="@drawable/login_button"
            android:layout_toRightOf="@id/user_pic"
            android:layout_below="@id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
</RelativeLayout>
4

1 回答 1

1

片段生命周期中,视图在阶段不可用onCreate(),因此getView()返回 null。将您的视图代码移至onCreateView()或稍后。

于 2013-05-20T17:41:28.763 回答