我正在尝试在ImageView上设置点击监听器,这将在特定页面上打开Facebook应用程序。 变量“ facebook”保存我要打开的Facebook页面的URL 我的点击监听器代码如下:
imgFb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (facebook != null) {
Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(context);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);
}
}
});
和方法getFacebookUrl()如下:
//Open club's Facebook page
public String getFacebookPageURL(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
if (versionCode >= 3002850) { //newer versions of fb app
return "fb://facewebmodal/f?href=" + facebook;
} else { //older versions of fb app
return "fb://page/" + facebook;
}
} catch (PackageManager.NameNotFoundException e) {
return facebook; //normal web url
}
}
此代码不适用于我。我在以下两行中有空指针异常:
PackageManager packageManager = context.getPackageManager();
String facebookUrl = getFacebookPageURL(context);
我认为这与上下文变量有关。我不太了解,我不确定确切要放置什么,因此我使用了Open Facebook Page in Facebook App (if installed) on Android中的代码。有人可以帮我吗?
答案 0 :(得分:3)
我认为您不需要在主体中声明上下文,而是必须添加
context=getApplicationContext();
或
context=YourActivity.this;
对你的身体。
这对我有用。
Button btn;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.btn);
context=getApplicationContext();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isAppInstalled()) {
Toast.makeText(getApplicationContext(), "facebook app already installed", Toast.LENGTH_SHORT).show();
Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(context);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);
} else {
Toast.makeText(getApplicationContext(), "facebook app not installing", Toast.LENGTH_SHORT).show();
}
}
});
}
public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";
//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
int versionCode = packageManager.getPackageInfo("com.facebook.orca", 0).versionCode;
if (versionCode >= 3002850) { //newer versions of fb app
return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
} else { //older versions of fb app
return "fb://page/" + FACEBOOK_PAGE_ID;
}
} catch (PackageManager.NameNotFoundException e) {
return FACEBOOK_URL; //normal web url
}
}
public boolean isAppInstalled() {
try {
getApplicationContext().getPackageManager().getApplicationInfo("com.facebook.katana", 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}