在FB上加载视频时出现空指针异常

时间:2012-08-25 17:05:26

标签: android facebook video nullpointerexception

我正在制作一个应用程序,我想在facebook上发布视频。但在给出视频的引用时,我得到空指针异常。请告诉我如何解决这个问题。

这是代码:

public class Example extends Activity {

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

    private LoginButton mLoginButton;
    private TextView mText;
    private Button mRequestButton;
    private Button mPostButton;
    private Button mDeleteButton;
    private Button mUploadButton;

    private Facebook mFacebook;
    private AsyncFacebookRunner mAsyncRunner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

        setContentView(R.layout.main);
        mLoginButton = (LoginButton) findViewById(R.id.login);
        mText = (TextView) Example.this.findViewById(R.id.txt);
        mRequestButton = (Button) findViewById(R.id.requestButton);
        mPostButton = (Button) findViewById(R.id.postButton);
        mDeleteButton = (Button) findViewById(R.id.deletePostButton);
        mUploadButton = (Button) findViewById(R.id.uploadButton);

        mFacebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(mFacebook);

        SessionStore.restore(mFacebook, this);
        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        mLoginButton.init(this, mFacebook);

        mRequestButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mAsyncRunner.request("me", new SampleRequestListener());
            }
        });
        mRequestButton.setVisibility(mFacebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);


        mUploadButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                byte[] data = null;
                AssetFileDescriptor fileDesc = getResources().openRawResourceFd(
                R.raw.movie);
                String dataPath =  fileDesc.toString();
                String dataMsg = "Your video description here.";
                String dataName = "movie.mp4";
                Bundle param;
                AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
                InputStream is ;
                try 
                {
                    is = new FileInputStream(dataPath);
                    if(is != null)
                    data = readBytes(is);
                    param = new Bundle();
                    param.putString("message", dataMsg);
                    param.putString("filename", dataName);
                    param.putByteArray("video", data);
                    mAsyncRunner.request(null, param, "POST", new SampleUploadListener(), null);
                }
                catch (FileNotFoundException e) {
                   e.printStackTrace();
                }
                catch (IOException e) {
                   e.printStackTrace();
                }       
            }
        });
        mUploadButton.setVisibility(mFacebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);

        mPostButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mFacebook.dialog(Example.this, "feed",
                        new SampleDialogListener());
            }
        });
        mPostButton.setVisibility(mFacebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);

        mPostButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mFacebook.dialog(Example.this, "feed",
                        new SampleDialogListener());
            }
        });
        mPostButton.setVisibility(mFacebook.isSessionValid() ?
                View.VISIBLE :
                View.INVISIBLE);
    }

    public byte[] readBytes(InputStream inputStream) throws IOException {
        // This dynamically extends to take the bytes you read.
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        // This is storage overwritten on each iteration with bytes.
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // We need to know how may bytes were read to write them to the byteBuffer.
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }

        // And then we can return your byte array.
        return byteBuffer.toByteArray();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        mFacebook.authorizeCallback(requestCode, resultCode, data);
    }

    public class SampleAuthListener implements AuthListener {

        public void onAuthSucceed() {
            mText.setText("You have logged in! ");
            mRequestButton.setVisibility(View.VISIBLE);
            mUploadButton.setVisibility(View.VISIBLE);
            mPostButton.setVisibility(View.VISIBLE);
        }

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

    public class SampleLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
            mText.setText("Logging out...");
        }

        public void onLogoutFinish() {
            mText.setText("You have logged out! ");
            mRequestButton.setVisibility(View.INVISIBLE);
            mUploadButton.setVisibility(View.INVISIBLE);
            mPostButton.setVisibility(View.INVISIBLE);
        }
    }

    public class SampleRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: executed in background thread
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String name = json.getString("name");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                Example.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mText.setText("Hello there, " + name + "!");
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }

    public class SampleUploadListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: (executed in background thread)
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String src = json.getString("src");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."
                Example.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mText.setText("Hello there, photo has been uploaded at \n" + src);
                    }
                });
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }
    }
    public class WallPostRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            Log.d("Facebook-Example", "Got response: " + response);
            String message = "<empty>";
            try {
                JSONObject json = Util.parseJson(response);
                message = json.getString("message");
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
            final String text = "Your Wall Post: " + message;
            Example.this.runOnUiThread(new Runnable() {
                public void run() {
                    mText.setText(text);
                }
            });
        }
    }

    public class WallPostDeleteListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            if (response.equals("true")) {
                Log.d("Facebook-Example", "Successfully deleted wall post");
                Example.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mDeleteButton.setVisibility(View.INVISIBLE);
                        mText.setText("Deleted Wall Post");
                    }
                });
            } else {
                Log.d("Facebook-Example", "Could not delete wall post");
            }
        }
    }

    public class SampleDialogListener extends BaseDialogListener {

        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");
            if (postId != null) {
                Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
                mAsyncRunner.request(postId, new WallPostRequestListener());
                mDeleteButton.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        mAsyncRunner.request(postId, new Bundle(), "DELETE",
                                new WallPostDeleteListener(), null);
                    }
                });
                mDeleteButton.setVisibility(View.VISIBLE);
            } else {
                Log.d("Facebook-Example", "No wall post made");
            }
        }
    }

}

这是一个例外:

08-25 22:22:12.521: W/System.err(385): java.io.FileNotFoundException: /{AssetFileDescriptor: {ParcelFileDescriptor: java.io.FileDescriptor@44ea68c8} start=12468 len=466888}
08-25 22:22:12.630: W/System.err(385):  at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:244)
08-25 22:22:12.662: W/System.err(385):  at java.io.FileInputStream.<init>(FileInputStream.java:77)
08-25 22:22:12.671: W/System.err(385):  at java.io.FileInputStream.<init>(FileInputStream.java:130)
08-25 22:22:12.691: W/System.err(385):  at com.facebook.android.Example$2.onClick(Example.java:107)
08-25 22:22:12.691: W/System.err(385):  at android.view.View.performClick(View.java:2364)
08-25 22:22:12.702: W/System.err(385):  at android.view.View.onTouchEvent(View.java:4179)
08-25 22:22:12.710: W/System.err(385):  at android.widget.TextView.onTouchEvent(TextView.java:6541)
08-25 22:22:12.730: W/System.err(385):  at android.view.View.dispatchTouchEvent(View.java:3709)
08-25 22:22:12.741: W/System.err(385):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-25 22:22:12.750: W/System.err(385):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-25 22:22:12.750: W/System.err(385):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-25 22:22:12.762: W/System.err(385):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
08-25 22:22:12.780: W/System.err(385):  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
08-25 22:22:12.780: W/System.err(385):  at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
08-25 22:22:12.791: W/System.err(385):  at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
08-25 22:22:12.801: W/System.err(385):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
08-25 22:22:12.810: W/System.err(385):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
08-25 22:22:12.834: W/System.err(385):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 22:22:12.841: W/System.err(385):  at android.os.Looper.loop(Looper.java:123)
08-25 22:22:12.852: W/System.err(385):  at android.app.ActivityThread.main(ActivityThread.java:4363)
08-25 22:22:12.860: W/System.err(385):  at java.lang.reflect.Method.invokeNative(Native Method)
08-25 22:22:12.871: W/System.err(385):  at java.lang.reflect.Method.invoke(Method.java:521)
08-25 22:22:12.881: W/System.err(385):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
08-25 22:22:12.890: W/System.err(385):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
08-25 22:22:12.900: W/System.err(385):  at dalvik.system.NativeStart.main(Native Method)

我在这一行得到例外。

is = new FileInputStream(dataPath);

1 个答案:

答案 0 :(得分:2)

首先,您将AssetFileDescriptor的引用作为路径传递。

替换

is = new FileInputStream(dataPath);

is = fileDesc.createInputStream()