Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook Sharing with android studio

Dear people of the stackoverflow,

I'm afraid im in dire need of help. There is one problem that I keep encountering with my app. I'm making an app that has three buttons: One to see a link, one for intent and one for sharing stuff on facebook (the reason is due to that you cant send stuff with intent anymore, or so i've been told) However, according to the Facebook Developer website, i should get a share button. With my code , everything crashes and the only thing i can see, is the share dialog. My question is, what is the main mistake i've made?

My main activity code:

package things;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.view.View.OnClickListener;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareButton;
import com.facebook.share.widget.ShareDialog;

import java.util.Random;


public class MainActivity extends ActionBarActivity {

private Button btnScore;
private Button btnShare;

private static String APP_ID = "things";

CallbackManager callbackManager;
ShareDialog shareDialog;

//ms = mobile Scores
WebView msWebView;
WebView mfWebView;


ShareLinkContent content = new ShareLinkContent.Builder()
        .setContentTitle("Test")
        .setContentUrl(Uri.parse("http://developers.facebook.com/android"))
        .setContentDescription("Play Something with your facebook friends and many more people!")
        .build();


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

    //Facebook for  sharing
    callbackManager = CallbackManager.Factory.create();
    shareDialog = new ShareDialog(this);
    final ShareButton shareButton = (ShareButton) findViewById(R.id.fb_share_button);


    int score = 64;

    //Searches the phone for apps that can share simple data
    final Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "My score of the last game  was: " + score + " \n Can you beat my score?");

    //This is for the share dialog to show





    //an iff statement if it shows
    if (ShareDialog.canShow(ShareLinkContent.class)) {
        ShareLinkContent linkContent = new ShareLinkContent.Builder()
                .setContentTitle("Hello Facebook")
                .setContentDescription(
                        "The 'Hello Facebook' sample  showcases simple Facebook integration")
                .setContentUrl(Uri.parse("http://developers.facebook.com/android"))
                .build();

        shareDialog.show(linkContent);
    }
    shareButton.setShareContent(content);

    //The buttons
    btnScore=(Button)findViewById(R.id.btnScores);
    btnShare =(Button)findViewById(R.id.btnShare);



    //the score Webview link
    msWebView = new WebView(this);
    msWebView.loadUrl("Thing");
    msWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String     url){
            view.loadUrl(url);
            return true;
        }
    });

   ShareDialog.show(this, content);
   btnScore.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View vw) {
            setContentView(msWebView);
        }
    });

    //the share button
    btnShare.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View vw)     {startActivity(Intent.createChooser(sendIntent, "share..."));

        }
    });
    shareButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            shareButton.setShareContent(content);
        }
    }     );
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu.
    // Adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    // Access the Share Item defined in menu XML


    return true;
}

//special method to handle the callbackmanager
@Override
protected void onActivityResult(final int requestCode, final int  resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
    ShareDialog.show(this, content);
}

@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.menu_item_share) {
       return true;
    }

    return super.onOptionsItemSelected(item);
}


}

My Activity_Main.XML:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"     tools:context=".MainActivity"
android:background="#ffd2e489">

<TextView android:text="Results"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="View"
    android:id="@+id/btnScores"
    android:background="#ffff7878"
    android:layout_marginTop="40dp"
    android:layout_below="@+id/text"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@+id/text"
    android:layout_toStartOf="@+id/text" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Share"
    android:id="@+id/btnShare"
    android:background="#ff20f6ff"
    android:layout_alignTop="@+id/btnScores"
    android:layout_toRightOf="@+id/text"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<com.facebook.share.widget.ShareButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fb_share_button"
android:text="SHARE"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="175dp" />


</RelativeLayout>

And just in case my Android: Manifest:

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data android:name="com.facebook.sdk.ApplicationId"    android:value="@string/app_id"/>
    <activity

        android:name=".MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <provider   android:authorities="com.facebook.app.FacebookContentProviderthings"
                android:name="com.facebook.FacebookContentProvider"
                android:exported="true"/>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:mimeType="text/plain"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
            "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"
        android:label="@string/app_name" />
    android:debuggable="true"
</application>

</manifest>

Sorry for the long post, I know the answer is there but can't find the greemly error and this has been bothering me for a week.

Thanks for reading!

Frederick

Edit: I'm using facebookSDK 4.0.

Edit 2.0: the error:

 Caused by: java.lang.NullPointerException
        at things.MainActivity.onCreate(MainActivity.java:93)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)

Edit 3.0 The Logcat:

 Process: nl.test.test, PID: 12287
java.lang.ExceptionInInitializerError
        at java.lang.reflect.Constructor.constructNative(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at android.view.LayoutInflater.createView(LayoutInflater.java:594)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
        at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:240)
        at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
        at nl.test.test.MainActivity.onCreate(MainActivity.java:60)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5135)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: null
        at com.facebook.internal.Validate.sdkInitialized(Validate.java:99)
        at com.facebook.FacebookSdk.getCallbackRequestCodeOffset(FacebookSdk.java:735)
        at com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.toRequestCode(CallbackManagerImpl.java:109)
        at com.facebook.share.widget.ShareButton.<clinit>   (ShareButton.java:36)
    at java.lang.reflect.Constructor.constructNative(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at android.view.LayoutInflater.createView(LayoutInflater.java:594)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)

android.view.LayoutInflater.rInflate(LayoutInflater.java:755)

android.view.LayoutInflater.inflate(LayoutInflater.java:492)



android.view.LayoutInflater.inflate(LayoutInflater.java:397)

   android.view.LayoutInflater.inflate(LayoutInflater.java:353)
android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:240)
                android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            test.MainActivity.onCreate(MainActivity.java:60)
            at android.app.Activity.performCreate(Activity.java:5231)
             android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
            android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            android.app.ActivityThread.access$800(ActivityThread.java:144)                   android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            android.os.Handler.dispatchMessage(Handler.java:102)
            android.os.Looper.loop(Looper.java:212)
        android.app.ActivityThread.main(ActivityThread.java:5135)
        java.lang.reflect.Method.invokeNative(Native Method)
        java.lang.reflect.Method.invoke(Method.java:515)
        com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
        com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
dalvik.system.NativeStart.main(Native Method)
like image 236
frederick van der meulen Avatar asked Mar 16 '23 07:03

frederick van der meulen


1 Answers

Alright, after some work, I found the answer. The answer is very simple: instead of this:

super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());

But what you need to do is this:

FacebookSdk.sdkInitialize(getApplicationContext()); 
super.onCreate(savedInstanceState);

The reason to do this, is because you want to initialize the Facebook SDK before you create the app instance, otherwise, the Facebook SDK can never be used by the app.

I hope that if someone has the same problem as I had, can use this!

like image 79
frederick van der meulen Avatar answered Mar 30 '23 12:03

frederick van der meulen