Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook login button causes a crash

I have trouble trying to solve Facebook login button as a part of Android application.

Application starts well, but it crashes when I press Facebook Login button.

This is what it says in log:

12-06 17:17:01.079 25678-25678/com.example.icen.tij01 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: com.example.icen.tij01, PID: 25678
                                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.Fragment com.facebook.internal.FragmentWrapper.getSupportFragment()' on a null object reference
                                                                                     at com.facebook.FacebookButtonBase.getFragment(FacebookButtonBase.java:105)
                                                                                     at com.facebook.login.widget.LoginButton$LoginClickListener.onClick(LoginButton.java:736)
                                                                                     at com.facebook.FacebookButtonBase$1.onClick(FacebookButtonBase.java:383)
                                                                                     at android.view.View.performClick(View.java:5198)
                                                                                     at android.view.View$PerformClick.run(View.java:21147)
                                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:148)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-06 17:17:03.055 25678-25678/com.example.icen.tij01 I/Process: Sending signal. PID: 25678 SIG: 9

UPDATE:

And this is part of Activity that have to handle Facebook login:

package com.example.icen.tij01;

import android.app.Activity;
/* import... */

public class StartActivity extends ActionBarActivity {

    static String hostDomain = "http://192.168.48.1/myPhpApp/";

    private TextView info;
    private LoginButton loginButton;
    private CallbackManager callbackManager;

    static String checkUrl = hostDomain + "connect.php";

    String responseServer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();

        setContentView(R.layout.activity_start);


        info = (TextView)findViewById(R.id.info);
        loginButton = (LoginButton)findViewById(R.id.login_button);

        // redirekicija na formu za logovanje
        Button btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent loginForm = new Intent(StartActivity.this, LoginFormActivity.class);
                startActivity(loginForm);
            }
        });

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                info.setText(
                        "User ID: "
                                + loginResult.getAccessToken().getUserId()
                                + "\n" +
                                "Auth Token: "
                                + loginResult.getAccessToken().getToken()
                );
            }

            @Override
            public void onCancel() {
                info.setText("Login attempt canceled.");
            }

            @Override
            public void onError(FacebookException e) {

            }

        });

    }

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

    @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_start, 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);
    }




    /* Inner class to get response */
    class AsyncT extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(checkUrl);

            try {
                JSONObject jsonobj = new JSONObject();
                jsonobj.put("name", "Aneh");
                jsonobj.put("age", "22");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));

                Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());

                // Use UrlEncodedFormEntity to send in proper format which we need
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                InputStream inputStream = response.getEntity().getContent();
                InputStreamToStringExample str = new InputStreamToStringExample();
                responseServer = str.getStringFromInputStream(inputStream);

                //Log.e("response", "response -----" + responseServer);


            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast;

            if(responseServer.trim().equals("1")) {

                toast = Toast.makeText(context, "Connection ok, redirecting to adverts...", duration);
                toast.show();
                Intent show = new Intent(StartActivity.this, MainActivity.class);
                startActivity(show);

            } else {
                toast = Toast.makeText(context, "Connection error", duration);
                toast.show();

                AlertDialog alertDialog = new AlertDialog.Builder(StartActivity.this).create();
                alertDialog.setTitle("Connection error");
                alertDialog.setMessage("Error. Please check your connection");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();

            }


        }
    }



    public static class InputStreamToStringExample {

        public static void main(String[] args) throws IOException {

            // intilize an InputStream
            InputStream is =
                    new ByteArrayInputStream("file content..blah blah".getBytes());

            String result = getStringFromInputStream(is);

            System.out.println(result);
            System.out.println("Done");

        }

        // convert InputStream to String
        private static String getStringFromInputStream(InputStream is) {

            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();

            String line;
            try {

                br = new BufferedReader(new InputStreamReader(is));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return sb.toString();
        }

    }



}

I followed several tutorials, like:

http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837

Can you help me how to solve this, please.

like image 997
user198003 Avatar asked Mar 14 '23 23:03

user198003


1 Answers

The problem is with facebook login button. For some reason it is not initialized. I tried a lot of different ways to resolve this issue. And ended up with two solutions.

1) Change your class to extend fragment.And setFragment to your fb_login_button as per https://developers.facebook.com/docs/facebook-login/android

  {
     loginButton = (LoginButton) view.findViewById(R.id.login_button);
     loginButton.setReadPermissions("user_friends");
     loginButton.setFragment(this); 
  }

2) Instead of facebook_login_button create a custom button. And on the onClickListener call a method which has callBackManager and LoginManager.

{

Custom button in login_activity

    <Button
        android:id="@+id/fb_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background = "@drawable/btn_facebook"
        />

Login_Activity

        fb_btn = (Button) findViewById(R.id.fb_btn);

        fb_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                onfbClick();
            }

        });

Method to call LoginManager

    private void onfbClick() {
    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email","public_profile"));
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();

            Bundle parameters = new Bundle();
            parameters.putString("fields", "first_name,last_name");
            //request.setParameters(parameters);
            //request.executeAsync();
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "onCancel triggered");
        }

        @Override
        public void onError(FacebookException exception) {
            Log.i(TAG, "onError triggered");

        }
    });
}
}
like image 86
Rupesh Avatar answered Mar 27 '23 22:03

Rupesh