[英]Facebook login button causes a crash
I have trouble trying to solve Facebook login button as a part of Android application. 我无法尝试解决Facebook登录按钮作为Android应用程序的一部分。
Application starts well, but it crashes when I press Facebook Login button. 应用程序启动良好,但是当我按下Facebook登录按钮时它崩溃了。
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: 这是必须处理Facebook登录的Activity的一部分:
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 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. 请帮我解决一下这个问题。
The problem is with facebook login button. 问题出在facebook登录按钮上。 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 1)根据https://developers.facebook.com/docs/facebook-login/android更改您的类以将fragment.And和setFragment扩展到您的fb_login_button
{
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. 2)而不是facebook_login_button创建自定义按钮。 And on the onClickListener call a method which has callBackManager and LoginManager. 并在onClickListener上调用一个具有callBackManager和LoginManager的方法。
{ {
Custom button in login_activity 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 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 调用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");
}
});
}
}
It's hard to see where or why you have a Null Pointer Exception when the Fragment is being invoked, also because it's a custom example. 在调用Fragment时,很难看到你在哪里或为什么有Null Pointer Exception,这也是因为它是一个自定义的例子。
I suggest that you give Simple Facebook a try, it will make your life with Facebook a lot easier. 我建议你试试Simple Facebook吧,它会让你的Facebook生活变得更轻松。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.