我正在尝试将facebook与我的应用集成。 我的登录按钮位于活动内的片段内。
当我回到主要活动并回到我的facebook活动时。 我得到空指针异常。 我使用共享首选项来保留用户的数据并将其设置在特定的textViews上。
Facebook登录片段(为了提问我删除了导入)
public class Profilee extends Fragment {
static String email1, birthday1, gender1;
ImageView imageView;
static int itis = 1;
TextView texty;
LoginButton button;
LinearLayout userinput;
private CallbackManager callbackManager;
private TextView textView;
SharedPreferences pref;
private TextView email, birthday, gende;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
static String mail,gender,name;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest graphrequest = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
if (jsonObject != null) {
try {
email1 = jsonObject.getString("email");
gender1 = jsonObject.getString("gender");
birthday1 = jsonObject.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email, gender, birthday");
graphrequest.setParameters(parameters);
graphrequest.executeAsync();
AppEventsLogger.activateApp(getContext());
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
}
};
public Profilee() {
// Required empty public constructor
}
public boolean m;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Toast.makeText(getContext(), "Create", Toast.LENGTH_SHORT).show();
pref = getContext().getSharedPreferences("hello", getContext().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
onResume();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profilee, container, false);
button = (LoginButton) v.findViewById(R.id.login_button);
TextView button12 = (TextView) v.findViewById(R.id.edit);
button12.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PrifileEdit.class);
i.putExtra("st", email1);
startActivity(i);
}
});
texty = (TextView) v.findViewById(R.id.emo);
imageView = (ImageView) v.findViewById(R.id.asd);
userinput = (LinearLayout) v.findViewById(R.id.userdetail);
int unicode = 0x1F60E;
String emoji = getEmijoByUnicode(unicode);
String text = "We will never post on your wall without permission ";
texty.setText(text + emoji);
Toast.makeText(getContext(), "CreateView", Toast.LENGTH_SHORT).show();
return v;
}
public String getEmijoByUnicode(int unicode) {
return new String(Character.toChars(unicode));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
email = (TextView) view.findViewById(R.id.emailid);
gende = (TextView) view.findViewById(R.id.gender);
birthday = (TextView) view.findViewById(R.id.birth);
loginButton.setReadPermissions("email");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
Toast.makeText(getContext(), "ViewCreate", Toast.LENGTH_SHORT).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
onResume();
}
}, 2000);
}
public void displayMessage(final Profile profile) {
pref = getContext().getSharedPreferences("hello", getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
m=pref.getBoolean("key",true);
if(m==true) {
if (profile != null) {
textView.setText(profile.getName());
email.setText(email1);
gende.setText(gender1);
birthday.setText(birthday1);
button.setVisibility(View.GONE);
texty.setVisibility(View.GONE);
userinput.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences("hello", getContext().MODE_PRIVATE);
editor.putString("email",email1);
editor.putString("name",profile.getName());
editor.putString("gender",gender1);
editor.putBoolean("key",false);
editor.commit();
}
} else if(m==false){
mail=pref.getString("email","lol1");
gender=pref.getString("gender","lol2");
name=pref.getString("name","lol3");
textView.setText(name);
email.setText(mail);
gende.setText(gender);
}
}
@Override
public void onStart() {
super.onStart();
Toast.makeText(getContext(), "Start", Toast.LENGTH_SHORT).show();
}
@Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
@Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
AppEventsLogger.activateApp(getContext());
}
}
对上述片段的反应
public class Profile extends AppCompatActivity {
private ViewPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
TextView textView, textView2;
SharedPreferences sp;
private static String totalurl = "random.com/l.php";
public static final String MyPREFERENCES = "User" ;
public static final String UserID = "UserIDKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
mSectionsPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
textView = (TextView) findViewById(R.id.redeem);
SharedPreferences sp = getSharedPreferences("User", Context.MODE_PRIVATE);
totalearn();
textView.setText("₹ " + sp.getString("A_EARN", ""));
textView2.setText("₹ "+sp.getString("T_EARN",""));
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Profilee(), "PROFILE");
adapter.addFragment(new Redeem(), "REDEEM");
//adapter.addFragment(new History(), "HISTORY");
viewPager.setAdapter(adapter);
}
@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();
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public int getCount() {
return mFragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void redeem(View v){
Intent internet = new Intent();
internet.setAction(Intent.ACTION_VIEW);
internet.addCategory(Intent.CATEGORY_BROWSABLE);
internet.setData("my"));
startActivity(internet);
}
}
logcat的
FATAL EXCEPTION: mainProcess: earn.free.cashback.snapcash, PID: 3959
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at earn.free.cashback.snapcash.fragments.Profilee.displayMessage(Profilee.java:241)
at earn.free.cashback.snapcash.fragments.Profilee.onResume(Profilee.java:268)
at earn.free.cashback.snapcash.fragments.Profilee.onCreate(Profilee.java:149)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:926)
at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:876)
at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1175)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:17430)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
at android.view.View.measure(View.java:17430)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17430)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17430)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17430)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17430)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
at android.view.View.measure(View.java:17430)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
答案 0 :(得分:0)
在设置setText之前,请确保您没有传递NULL值。我认为问题在于此处,传递的值必须为null,因此为NullPointerException。
email.setText(email1);
gende.setText(gender1);
birthday.setText(birthday1);
答案 1 :(得分:0)
将您的onResume()
更改为:
public void onResume() {
super.onResume();
textView = (TextView) getView().findViewById(R.id.textView);
email = (TextView) getView().findViewById(R.id.emailid);
gende = (TextView) getView().findViewById(R.id.gender);
birthday = (TextView) getView().findViewById(R.id.birth);
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
AppEventsLogger.activateApp(getContext());
}