在我的应用程序中,我有两个活动登录和注册以及主要活动。我已经使用片段来获取带有滑动手势的标签。我得到了Nullpointerexception。请帮帮我。
我的代码在这里..
MainActivity:
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Login", "Login with Facebook", "Registration" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
LoginActivity:
public class LoginActivity extends Fragment {
// Your Facebook APP ID
private static String APP_ID = "270865596396516";
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
@SuppressWarnings("unused")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
public SharedPreferences mPrefs;
Button login, signup, login_facebook, forgot, button_getprofile;;
EditText uname, pwd;
String name, password;
ConnectivityManager mConnectivityMgr;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.login, container, false);
login = (Button) getActivity().findViewById(R.id.login_btn);
login_facebook = (Button) getActivity().findViewById(R.id.facebook_btn);
button_getprofile = (Button) getActivity().findViewById(
R.id.btn_get_profile);
forgot = (Button) getActivity().findViewById(R.id.text_forgot);
uname = (EditText) getActivity().findViewById(R.id.user_et);
pwd = (EditText) getActivity().findViewById(R.id.pwd_et);
login_facebook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
// by reference from andfroidhive...
/*
* button_getprofile.setOnClickListener(new OnClickListener() {
*
* @Override public void onClick(View v) { // TODO Auto-generated method
* stub getProfileInformation();
*
* } });
*/
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ((uname.length() >= 4) && (pwd.length() > 0)) {
name = uname.getText().toString().trim();
password = pwd.getText().toString().trim();
callWebService();
} else {
if ((uname.length() < 12)) {
uname.setError("enter valid username");
} else if ((pwd.length() <= 0)) {
pwd.setError("enter valid password");
}
}
}
});
return rootView;
}
public void loginToFacebook() {
mPrefs = getActivity().getPreferences(Context.MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
login_facebook.setVisibility(View.INVISIBLE);
button_getprofile.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(), new String[] { "email",
"publish_stream" }, new DialogListener() {
@Override
public void onCancel() {
// Function to handle cancel event
}
@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
login_facebook.setVisibility(View.INVISIBLE);
button_getprofile.setVisibility(View.VISIBLE);
}
@Override
public void onError(DialogError error) {
// Function to handle error
}
@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/*
* @SuppressWarnings("deprecation") public void getProfileInformation() {
* mAsyncRunner.request("me", new RequestListener() {
*
* @Override public void onComplete(String response, Object state) {
* Log.d("Profile", response); String json = response; try { // Facebook
* Profile JSON data JSONObject profile = new JSONObject(json);
*
* // getting name of the user final String name =
* profile.getString("name");
*
* // getting email of the user final String email =
* profile.getString("email");
*
* Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " +
* email, Toast.LENGTH_LONG).show();
*
* runOnUiThread(new Runnable() {
*
* @Override public void run() { Toast.makeText(getApplicationContext(),
* "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show(); }
*
* });
*
* } catch (JSONException e) { Toast.makeText(getApplicationContext(),
* "...." + e, Toast.LENGTH_LONG).show(); e.printStackTrace(); } }
*
* @Override public void onIOException(IOException e, Object state) { }
*
* @Override public void onFileNotFoundException(FileNotFoundException e,
* Object state) { }
*
* @Override public void onMalformedURLException(MalformedURLException e,
* Object state) { }
*
* @Override public void onFacebookError(FacebookError e, Object state) { }
* }); }
*/
// database authentication...from SQLite database....
public void callWebService() {
try {
SQLiteDatabase database = getActivity().openOrCreateDatabase(
"studentDB", 0, null);
Cursor c = database.query("login", null, null, null, null, null,
null);
while (c.moveToNext()) {
String c1 = c.getString(0);
String c2 = c.getString(1);
if (c1.equals(name)) {
if (c2.equals(password)) {
Toast.makeText(LoginActivity.this.getActivity(),
"" + c1 + " Welcome to Smarteach..",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(),
SignupActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this.getActivity(),
"Incorrect Password", Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(LoginActivity.this.getActivity(),
"Incorrect Username", Toast.LENGTH_SHORT).show();
}
}
database.close();
} catch (Exception e) {
Log.d("Login class", e.toString());
Toast.makeText(LoginActivity.this.getActivity(),
"No records found with these credentials",
Toast.LENGTH_SHORT).show();
}
}
}
注册活动:
public class SignupActivity extends Fragment {
EditText email, pswd, cnfrm, mobile;
Button register, cancel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.registration, container,
false);
email = (EditText) getActivity().findViewById(R.id.ed_email);
pswd = (EditText) getActivity().findViewById(R.id.ed_pswd);
cnfrm = (EditText) getActivity().findViewById(R.id.ed_cnfrm);
mobile = (EditText) getActivity().findViewById(R.id.ed_mobile);
register = (Button) getActivity().findViewById(R.id.btn_reg);
cancel = (Button) getActivity().findViewById(R.id.btn_can);
register.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String mail = email.getText().toString();
String password = pswd.getText().toString();
String confirmpswd = cnfrm.getText().toString();
String phonenumber = mobile.getText().toString();
if (mail.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")
&& mail.length() > 0) {
if (password.equals(confirmpswd)) {
if (phonenumber.length() > 0) {
// creating a database and storing the credentials
// into it...
try {
SQLiteDatabase database = getActivity()
.openOrCreateDatabase("studentDB", 0,
null);
// String create =
// "create table if not exists student(emai varchar(20),password varchar(20),mobile varchar(20));";
String create1 = "create table if not exists login(emailid varchar(28),pass varchar(20))";
database.execSQL(create1);
// database.execSQL(create);
// String insert =
// "insert into student values('"+mail+"','"+password+"','"+phonenumber+"');";
String insert1 = "insert into login values('"
+ mail + "','" + password + "')";
// database.execSQL(insert);
database.execSQL(insert1);
database.close();
/*
* startActivity(new
* Intent(SignupActivity.this.getActivity(),
* AnimatedSliding.class));
*/
// startActivity(new Intent(Registration.this,
// Login.class));
} catch (Exception e) {
Toast.makeText(
SignupActivity.this.getActivity(),
e.toString(), Toast.LENGTH_SHORT)
.show();
}
Toast.makeText(
getActivity().getApplicationContext(),
"your account successfully created...",
Toast.LENGTH_LONG).show();
} else {
mobile.setError("enter min 10 digits..");
}
} else if (pswd.length() < 4) {
pswd.setError("enter min 4 digits");
cnfrm.setError("enter correct password..");
}
} else {
email.setError("enter valid email ID..");
}
}
});
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getActivity().finish();
}
});
return rootView;
}
}
logcat的:
01-27 13:10:36.361: D/AndroidRuntime(1033): Shutting down VM
01-27 13:10:36.371: W/dalvikvm(1033): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
01-27 13:10:36.381: E/AndroidRuntime(1033): FATAL EXCEPTION: main
01-27 13:10:36.381: E/AndroidRuntime(1033): java.lang.NullPointerException
01-27 13:10:36.381: E/AndroidRuntime(1033): at info.androidhive.tabsswipe.LoginActivity.onCreateView(LoginActivity.java:61)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.View.measure(View.java:12603)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.View.measure(View.java:12603)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.widget.LinearLayout.measureVertical(LinearLayout.java:812)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.View.measure(View.java:12603)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-27 13:10:36.381: E/AndroidRuntime(1033): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2072)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.View.measure(View.java:12603)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1044)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.os.Handler.dispatchMessage(Handler.java:99)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.os.Looper.loop(Looper.java:137)
01-27 13:10:36.381: E/AndroidRuntime(1033): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-27 13:10:36.381: E/AndroidRuntime(1033): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 13:10:36.381: E/AndroidRuntime(1033): at java.lang.reflect.Method.invoke(Method.java:511)
01-27 13:10:36.381: E/AndroidRuntime(1033): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-27 13:10:36.381: E/AndroidRuntime(1033): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-27 13:10:36.381: E/AndroidRuntime(1033): at dalvik.system.NativeStart.main(Native Method)
01-27 13:13:52.910: D/AndroidRuntime(1080): Shutting down VM
01-27 13:13:52.910: W/dalvikvm(1080): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
01-27 13:13:52.920: E/AndroidRuntime(1080): FATAL EXCEPTION: main
01-27 13:13:52.920: E/AndroidRuntime(1080): java.lang.NullPointerException
01-27 13:13:52.920: E/AndroidRuntime(1080): at info.androidhive.tabsswipe.LoginActivity.onCreateView(LoginActivity.java:61)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.View.measure(View.java:12603)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.View.measure(View.java:12603)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.widget.LinearLayout.measureVertical(LinearLayout.java:812)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.View.measure(View.java:12603)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4677)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-27 13:13:52.920: E/AndroidRuntime(1080): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2072)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.View.measure(View.java:12603)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1044)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.os.Handler.dispatchMessage(Handler.java:99)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.os.Looper.loop(Looper.java:137)
01-27 13:13:52.920: E/AndroidRuntime(1080): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-27 13:13:52.920: E/AndroidRuntime(1080): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 13:13:52.920: E/AndroidRuntime(1080): at java.lang.reflect.Method.invoke(Method.java:511)
01-27 13:13:52.920: E/AndroidRuntime(1080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-27 13:13:52.920: E/AndroidRuntime(1080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-27 13:13:52.920: E/AndroidRuntime(1080): at dalvik.system.NativeStart.main(Native Method)
01-27 13:18:52.971: I/Process(1080): Sending signal. PID: 1080 SIG: 9
答案 0 :(得分:1)
变化:
login = (Button) getActivity().findViewById(R.id.login_btn);
login_facebook = (Button) getActivity().findViewById(R.id.facebook_btn);
button_getprofile = (Button) getActivity().findViewById(
R.id.btn_get_profile);
forgot = (Button) getActivity().findViewById(R.id.text_forgot);
uname = (EditText) getActivity().findViewById(R.id.user_et);
pwd = (EditText) getActivity().findViewById(R.id.pwd_et);
为:
login = (Button) rootView.findViewById(R.id.login_btn);
login_facebook = (Button) rootView.findViewById(R.id.facebook_btn);
button_getprofile = (Button) rootView.findViewById(
R.id.btn_get_profile);
forgot = (Button) rootView.findViewById(R.id.text_forgot);
uname = (EditText) rootView.findViewById(R.id.user_et);
pwd = (EditText) rootView.findViewById(R.id.pwd_et);
直到onCreateView返回一个视图,这个片段没有附加到活动。
所以getActivity()。findViewById将无法找到该视图。因此,您只需从rootView中查找视图即可。或者将此代码放在片段中的onAttach
事件中。
答案 1 :(得分:1)
在OnCreateView()
中将所有getActivity()
替换为rootView
,例如:
login = (Button) rootView.findViewById(R.id.login_btn);
答案 2 :(得分:1)
1。将LoginActivity getActivity()
中的所有onCreateView(...)
替换为rootView
2. 确保您定义的布局元素位于同一个xml
中