Well to be more specific I have made a create account fragment and a login fragment. When switching to landscape in the create account fragment it actually goes back to the login fragment. And then if you try to switch back into portrait then the app crashes. I've looked at similar questions but I couldnt make anything out from them. I really appreciate the help guys!
CreateAccountFragment
package com.keyconsultant.parse.logintutorial;
/**
* Create an Account. Username is the primary method of login. Email is used for forgotten password recovery.
*
* #author Trey Robinson
*
*/
public class CreateAccountFragment extends BaseFragment implements OnClickListener {
protected static final String EXTRA_EMAIL = "com.keyconsultant.parse.logintutorial.fragment.extra.EMAIL";
protected static final String EXTRA_USERNAME = "com.keyconsultant.parse.logintutorial.fragment.extra.USERNAME";
protected static final String EXTRA_PASSWORD = "com.keyconsultant.parse.logintutorial.fragment.extra.PASSWORD";
protected static final String EXTRA_CONFIRM = "com.keyconsultant.parse.logintutorial.fragment.extra.CONFIRMPASSWORD";
private EditText mUserNameEditText;
private EditText mEmailEditText;
private EditText mPasswordEditText;
private EditText mConfirmPasswordEditText;
private Button mCreateAccountButton;
private String mEmail;
private String mUsername;
private String mPassword;
private String mConfirmPassword;
/**
* Factory method for creating fragment instances.
* #return
*/
public static CreateAccountFragment newInstance(){
return new CreateAccountFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create_account, container, false);
mUserNameEditText = (EditText)view.findViewById(R.id.etUsername);
mEmailEditText = (EditText)view.findViewById(R.id.etEmail);
mPasswordEditText = (EditText)view.findViewById(R.id.etPassword);
mConfirmPasswordEditText = (EditText)view.findViewById(R.id.etPasswordConfirm);
mCreateAccountButton = (Button)view.findViewById(R.id.btnCreateAccount);
mCreateAccountButton.setOnClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null){
mEmailEditText.setText(savedInstanceState.getString(EXTRA_EMAIL));
mUserNameEditText.setText(savedInstanceState.getString(EXTRA_USERNAME));
mPasswordEditText.setText(savedInstanceState.getString(EXTRA_PASSWORD));
mConfirmPasswordEditText.setText(savedInstanceState.getString(EXTRA_CONFIRM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_EMAIL, mEmailEditText.getText().toString());
outState.putString(EXTRA_USERNAME, mUserNameEditText.getText().toString());
outState.putString(EXTRA_PASSWORD, mPasswordEditText.getText().toString());
outState.putString(EXTRA_CONFIRM, mConfirmPasswordEditText.getText().toString());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCreateAccount:
createAccount();
break;
default:
break;
}
}
/**
* Some front end validation is done that is not monitored by the service.
* If the form is complete then the information is passed to the service.
*/
private void createAccount(){
clearErrors();
boolean cancel = false;
View focusView = null;
// Store values at the time of the login attempt.
mEmail = mEmailEditText.getText().toString();
mUsername = mUserNameEditText.getText().toString();
mPassword = mPasswordEditText.getText().toString();
mConfirmPassword = mConfirmPasswordEditText.getText().toString();
// Check for a valid confirm password.
if (TextUtils.isEmpty(mConfirmPassword)) {
mConfirmPasswordEditText.setError(getString(R.string.error_field_required));
focusView = mConfirmPasswordEditText;
cancel = true;
} else if (mPassword != null && !mConfirmPassword.equals(mPassword)) {
mPasswordEditText.setError(getString(R.string.error_invalid_confirm_password));
focusView = mPasswordEditText;
cancel = true;
}
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordEditText.setError(getString(R.string.error_field_required));
focusView = mPasswordEditText;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordEditText.setError(getString(R.string.error_invalid_password));
focusView = mPasswordEditText;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailEditText.setError(getString(R.string.error_field_required));
focusView = mEmailEditText;
cancel = true;
} else if (!mEmail.contains("#")) {
mEmailEditText.setError(getString(R.string.error_invalid_email));
focusView = mEmailEditText;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
UserManager.getInstance().signUp(mUsername.toLowerCase(Locale.getDefault()), mEmail, mPassword);
}
}
/**
* Remove error messages from all fields.
*/
private void clearErrors(){ mEmailEditText.setError(null);
mUserNameEditText.setError(null);
mPasswordEditText.setError(null);
mConfirmPasswordEditText.setError(null);
}
#Subscribe
public void onSignInError(AuthenticateUserErrorEvent event){
clearErrors();
switch (event.getErrorCode()) {
case ParseException.INVALID_EMAIL_ADDRESS:
mEmailEditText.setError(getString(R.string.error_invalid_email));
mEmailEditText.requestFocus();
break;
case ParseException.EMAIL_TAKEN:
mEmailEditText.setError(getString(R.string.error_duplicate_email));
mEmailEditText.requestFocus();
break;
case ParseException.USERNAME_TAKEN:
mUserNameEditText.setError(getString(R.string.error_duplicate_username));
mUserNameEditText.requestFocus();
break;
default:
UnknownErrorDialogFactory.createUnknownErrorDialog(this.getActivity()).show();
break;
}
}
}
LoginFragment
package com.keyconsultant.parse.logintutorial;
/**
* Fragment for logging in. Includes button for loading the Create account view.
*
* #author Trey Robinson
*
*/
public class LoginFragment extends BaseFragment {
public static final String EXTRA_USERNAME = "com.keyconsultant.parse.logintutorial.activity.extra.USERNAME";
public static final String EXTRA_PASSWORD = "com.keyconsultant.parse.logintutorial.activity.extra.PASSWORD";
// UI references.
private EditText mUserNameEditText;
private EditText mPasswordEditText;
/**
* Factory method for creating new fragments
*
* #return
*/
public static LoginFragment newInstance() {
return new LoginFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
mUserNameEditText = (EditText) view.findViewById(R.id.username);
mPasswordEditText = (EditText) view.findViewById(R.id.password);
mPasswordEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
view.findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
view.findViewById(R.id.register_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
createAccount();
}
});
view.findViewById(R.id.forgot_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
forgotPassword();
}
});
return view;
}
/**
* Open the forgotPassword dialog
*/
private void forgotPassword() {
FragmentManager fm = getActivity().getSupportFragmentManager();
ForgotPasswordDialogFragment forgotPasswordDialog = new ForgotPasswordDialogFragment();
forgotPasswordDialog.show(fm, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mUserNameEditText.setText(savedInstanceState
.getString(EXTRA_USERNAME));
mPasswordEditText.setText(savedInstanceState
.getString(EXTRA_PASSWORD));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(EXTRA_USERNAME, mUserNameEditText.getText()
.toString());
outState.putString(EXTRA_PASSWORD, mPasswordEditText.getText()
.toString());
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
clearErrors();
// Store values at the time of the login attempt.
String username = mUserNameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(password)) {
mPasswordEditText
.setError(getString(R.string.error_field_required));
focusView = mPasswordEditText;
cancel = true;
} else if (password.length() < 4) {
mPasswordEditText
.setError(getString(R.string.error_invalid_password));
focusView = mPasswordEditText;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(username)) {
mUserNameEditText
.setError(getString(R.string.error_field_required));
focusView = mUserNameEditText;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// perform the user login attempt.
UserManager.getInstance().authenticate(
username.toLowerCase(Locale.getDefault()), password);
}
}
/**
* Load the create account view.
*/
private void createAccount() {
FragmentManager fragmentManager = getActivity()
.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(
((ViewGroup) getView().getParent()).getId(),
CreateAccountFragment.newInstance());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* Remove all edit text errors
*/
private void clearErrors() {
mUserNameEditText.setError(null);
mPasswordEditText.setError(null);
}
#Subscribe
public void onSignInError(AuthenticateUserErrorEvent event) {
clearErrors();
switch (event.getErrorCode()) {
case ParseException.OBJECT_NOT_FOUND:
mPasswordEditText
.setError(getString(R.string.error_incorrect_password));
mPasswordEditText.requestFocus();
break;
default:
UnknownErrorDialogFactory.createUnknownErrorDialog(
this.getActivity()).show();
break;
}
}
}
Just in case you need it here is my LoginActivity
package com.keyconsultant.parse.logintutorial;
/**
* Activity which displays a login screen to the user, offering registration as
* well. Based loosley on the default Login template.
*
* #author Trey Robinson
*/
public class LoginActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Parse.initialize(this, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction
.replace(R.id.main_view, LoginFragment.newInstance());
fragmentTransaction.commit();
parseCache();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_forgot_password:
forgotPassword();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Open the forgotPassword dialog
*/
private void forgotPassword() {
FragmentManager fm = getSupportFragmentManager();
ForgotPasswordDialogFragment forgotPasswordDialog = new ForgotPasswordDialogFragment();
forgotPasswordDialog.show(fm, null);
}
#Subscribe
public void onSignInStart(AuthenticateUserStartEvent event) {
showProgress(true, getString(R.string.login_progress_signing_in));
}
#Subscribe
public void onSignInSuccess(AuthenticateUserSuccessEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
Intent loginSuccess = new Intent(this, MainActivity.class);
startActivity(loginSuccess);
finish();
}
#Subscribe
public void onSignInError(AuthenticateUserErrorEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
}
#Subscribe
public void onForgotPasswordStart(UserForgotPasswordStartEvent event) {
showProgress(true, getString(R.string.login_progress_signing_in));
}
#Subscribe
public void onForgotPasswordSuccess(UserForgotPasswordSuccessEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
Toast toast = Toast.makeText(this,
"A password reset email has been sent.", Toast.LENGTH_LONG);
toast.show();
}
#Subscribe
public void onForgotPasswordError(UserForgotPasswordErrorEvent event) {
showProgress(false, getString(R.string.login_progress_signing_in));
Toast toast = Toast.makeText(this,
"An error has occured. Please try again.", Toast.LENGTH_LONG);
toast.show();
}
private void parseCache() {
Intent intent;
if (ParseUser.getCurrentUser() != null) {
intent = new Intent(this, MainActivity.class);
startActivity(intent);
this.finish();
}
}
}
Here is the logcat
01-10 16:09:05.796: I/Process(1923): Sending signal. PID: 1923 SIG: 9
01-10 17:00:57.513: I/Choreographer(1975): Skipped 111 frames! The application may be doing too much work on its main thread.
01-10 17:00:57.513: D/gralloc_goldfish(1975): Emulator without GPU emulation detected.
01-10 17:00:58.363: I/Choreographer(1975): Skipped 36 frames! The application may be doing too much work on its main thread.
01-10 17:00:58.833: I/Choreographer(1975): Skipped 37 frames! The application may be doing too much work on its main thread.
01-10 17:00:59.163: I/Choreographer(1975): Skipped 32 frames! The application may be doing too much work on its main thread.
01-10 17:01:11.253: D/dalvikvm(1975): GC_FOR_ALLOC freed 74K, 5% free 5533K/5820K, paused 2ms, total 3ms
01-10 17:01:11.253: I/dalvikvm-heap(1975): Grow heap (frag case) to 7.992MB for 2500620-byte allocation
01-10 17:01:11.263: D/dalvikvm(1975): GC_FOR_ALLOC freed 2K, 4% free 7972K/8264K, paused 2ms, total 3ms
01-10 17:01:11.273: D/dalvikvm(1975): GC_FOR_ALLOC freed <1K, 4% free 7972K/8264K, paused 3ms, total 4ms
01-10 17:01:11.273: I/dalvikvm-heap(1975): Grow heap (frag case) to 10.696MB for 2838540-byte allocation
01-10 17:01:11.283: D/dalvikvm(1975): GC_FOR_ALLOC freed 0K, 3% free 10744K/11040K, paused 4ms, total 4ms
01-10 17:01:15.953: D/dalvikvm(1975): GC_FOR_ALLOC freed 5268K, 45% free 6880K/12360K, paused 0ms, total 3ms
01-10 17:01:15.953: I/dalvikvm-heap(1975): Grow heap (frag case) to 8.489MB for 1642512-byte allocation
01-10 17:01:15.973: D/dalvikvm(1975): GC_FOR_ALLOC freed <1K, 32% free 8483K/12360K, paused 13ms, total 13ms
01-10 17:01:16.053: I/Choreographer(1975): Skipped 42 frames! The application may be doing too much work on its main thread.
01-10 17:01:17.473: I/Choreographer(1975): Skipped 58 frames! The application may be doing too much work on its main thread.
01-10 17:01:18.043: I/Choreographer(1975): Skipped 57 frames! The application may be doing too much work on its main thread.
01-10 17:01:23.363: D/AndroidRuntime(1975): Shutting down VM
01-10 17:01:23.363: W/dalvikvm(1975): threadid=1: thread exiting with uncaught exception (group=0xb0f2e648)
01-10 17:01:23.363: E/AndroidRuntime(1975): FATAL EXCEPTION: main
01-10 17:01:23.363: E/AndroidRuntime(1975): java.lang.NullPointerException
01-10 17:01:23.363: E/AndroidRuntime(1975): at com.keyconsultant.parse.logintutorial.LoginFragment.onSaveInstanceState(LoginFragment.java:119)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1607)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1587)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1655)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:527)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.Activity.performSaveInstanceState(Activity.java:1147)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3714)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread.access$700(ActivityThread.java:141)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.os.Looper.loop(Looper.java:137)
01-10 17:01:23.363: E/AndroidRuntime(1975): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-10 17:01:23.363: E/AndroidRuntime(1975): at java.lang.reflect.Method.invokeNative(Native Method)
01-10 17:01:23.363: E/AndroidRuntime(1975): at java.lang.reflect.Method.invoke(Method.java:525)
01-10 17:01:23.363: E/AndroidRuntime(1975): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-10 17:01:23.363: E/AndroidRuntime(1975): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-10 17:01:23.363: E/AndroidRuntime(1975): at dalvik.system.NativeStart.main(Native Method)
Your logcat shows you have problems in LoginFragment.onSaveInstanceState()
First, make super.onSaveInstanceState() the last line instead of the first line as it is now.
Then make sure you don't have mUserName and mPassword and their texts as nulls
Initialize mUserName and password texts to "" somewhere and the error should be gone, I think.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application has a Progress Dialog for login process and when the orientation is changed while dialog box is open, app crashes.This all works fine, except when screen orientation changes while the dialog is up. At this point the app crashes. I am figuring out this issue from the last 3 nights but not able to get it, please help.
My fragment:
public class Example extends Fragment {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
Unbinder unbinder;
#BindView(R.id.input_email) EditText _emailText;
#BindView(R.id.input_password) EditText _passwordText;
#BindView(R.id.btn_login) Button _loginButton;
#BindView(R.id.link_signup) TextView _signupLink;
#Override
public void onDestroyView() {
super.onDestroyView();
// unbind the view to free some memory
unbinder.unbind();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.Example, container, false);
unbinder=ButterKnife.bind(this,rootView);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent create= new Intent(getActivity(),NewAccount.class);
startActivity(create);
}
});
return rootView;
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
//new YourAsynTask(getActivity()).execute();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of loginFragment1");
super.onPause();
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
Intent i=new Intent(getActivity(),SuccessLogin.class);
startActivity(i);
}
public void onLoginFailed() {
Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
Logcat output:
11-16 19:20:10.955 4022-4022/com.example.a1332931.login_application E/WindowManager: android.view.WindowLeaked: Activity com.example.a1332931.login_application.TabActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{42b6135 V.E...... R......D 0,0-683,232} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.example.a1332931.login_application.Example.login(Example.java:156)
at com.example.a1332931.login_application.Example$1.onClick(Example.java:67)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-16 19:20:10.957 4022-4095/com.example.a1332931.login_application E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8aa6c60
11-16 19:20:12.512 4022-4022/com.example.a1332931.login_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1332931.login_application, PID: 4022
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at com.example.a1332931.login_application.Example.onLoginSuccess(Example.java:200)
at com.example.a1332931.login_application.Example$3.run(Example.java:168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Add this configuration change in your Android manifest activity:
<activity
android:name="YourActivity"
android:configChanges="orientation|keyboardHidden|screenSize"/>
I have developed simple android imageview that uses viewpager, and it plays music in background. It also stops music when last image is reached and it will resume the music when user slides back to the images. However, my main problem is that when device goes to sleep music stops and when device starts again instead of resuming music again and displaying image..It force closes... Any suggestion on how to fix this issue...Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1)
{
oursong.pause();
} else if (!oursong.isPlaying())
{
oursong.start();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause() {
super.onPause();
oursong.release();
}
}
ImageAdapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Logcat errors.... (Following Logcat was taken when app was running on actual device)
08-29 02:48:21.051: I/dalvikvm(2880): Could not find method android.widget.ShareActionProvider.setShareIntent, referenced from method com.manishkpr.viewpagerimagegallery.MainActivity.setShareIntent
08-29 02:48:21.051: W/dalvikvm(2880): VFY: unable to resolve virtual method 3259: Landroid/widget/ShareActionProvider;.setShareIntent (Landroid/content/Intent;)V
08-29 02:48:21.051: D/dalvikvm(2880): VFY: replacing opcode 0x6e at 0x0006
08-29 02:48:21.066: I/dalvikvm(2880): Could not find method android.view.MenuItem.getActionProvider, referenced from method com.manishkpr.viewpagerimagegallery.MainActivity.onCreateOptionsMenu
08-29 02:48:21.066: W/dalvikvm(2880): VFY: unable to resolve interface method 2912: Landroid/view/MenuItem;.getActionProvider ()Landroid/view/ActionProvider;
08-29 02:48:21.066: D/dalvikvm(2880): VFY: replacing opcode 0x72 at 0x0010
08-29 02:48:21.066: D/dalvikvm(2880): VFY: dead code 0x0013-0019 in Lcom/manishkpr/viewpagerimagegallery/MainActivity;.onCreateOptionsMenu (Landroid/view/Menu;)Z
08-29 02:48:21.230: W/MediaPlayer-cpp(2880): info/warning (802, 0)
08-29 02:48:21.348: I/MediaPlayer(2880): Info (802,0)
08-29 02:48:21.434: D/dalvikvm(2880): GC_EXTERNAL_ALLOC freed 1117 objects / 212256 bytes in 71ms
08-29 02:48:36.644: D/dalvikvm(2880): GC_EXTERNAL_ALLOC freed 553 objects / 29584 bytes in 32ms
08-29 02:50:00.566: D/AndroidRuntime(2880): Shutting down VM
08-29 02:50:00.566: W/dalvikvm(2880): threadid=1: thread exiting with uncaught exception (group=0x4001d8a8)
08-29 02:50:00.605: E/AndroidRuntime(2880): FATAL EXCEPTION: main
08-29 02:50:00.605: E/AndroidRuntime(2880): java.lang.RuntimeException: Unable to resume activity {com.manishkpr.viewpagerimagegallery/com.manishkpr.viewpagerimagegallery.MainActivity}: java.lang.IllegalStateException
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2059)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.os.Handler.dispatchMessage(Handler.java:99)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.os.Looper.loop(Looper.java:123)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-29 02:50:00.605: E/AndroidRuntime(2880): at java.lang.reflect.Method.invokeNative(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): at java.lang.reflect.Method.invoke(Method.java:521)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-29 02:50:00.605: E/AndroidRuntime(2880): at dalvik.system.NativeStart.main(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): Caused by: java.lang.IllegalStateException
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.media.MediaPlayer.seekTo(Native Method)
08-29 02:50:00.605: E/AndroidRuntime(2880): at com.manishkpr.viewpagerimagegallery.MainActivity.onResume(MainActivity.java:86)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.Activity.performResume(Activity.java:3823)
08-29 02:50:00.605: E/AndroidRuntime(2880): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3118)
08-29 02:50:00.605: E/AndroidRuntime(2880): ... 10 more
08-29 02:50:10.371: I/Process(2880): Sending signal. PID: 2880 SIG: 9
Have you tried moving your music playback to onResume() Activity lifecycle with fragments won't call onCreate() again until you activity is 're created. So the playback won't be resumed without closing your app.
Something like this
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
ImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(MyViewPagerListener);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause() {
super.onPause();
if(oursong != null){
oursong.release();
}
}
#Override
protected void onResume(){
super.onResume();
/*
* This is the important part, basically since your releasing the song
* in onPause() you are getting rid of its reference, in this case check
* if your song is null then if it is re-create it, else you can reuse the
* the original, but i suspect that calling release() in onPause() allows the
* song to get cleaned up by Java's Garbage Collector.
*/
if(oursong == null){
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0); // You will probably want to save an int to restore here
oursong.start();
}else{
oursong.seekTo();
oursong.start();
}
}
/*
* May want to add two methods here: onSaveInstanceState(Bundle outstate) &
* onRestoreInstanceState(Bundle savedInstanceState) to maintain playback position
* in onResume instead of just restarting the song.
*/
private final OnPageChangeListener MyViewPagerListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1){
// adding null checks for safety
if(oursong != null){
oursong.pause();
}
} else if (!oursong.isPlaying()){
// adding null check for safety
if(oursong != null){
oursong.start();
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
}
Hope this helps you resolve your problem.
Info: I am a decent java developer, I know my way around it pretty well I think, so I decided to give android a chance, and it hasn't been the smoothest road for me. I mess up very often. Anyway to my question if anyone would be so kind to help me out with this error I would very much appreciate it! Thank you.
Main Class
package dev.shaw.MyShoppingPlanner;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private String m_Text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(firstTime()){
GenerateNeededFiles();
}
else{
//do nothing
}
ActionBar.TabListener tablistener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch(tab.getText().toString()){
case "Lists":
openLists();
break;
case "Store":
openStore();
case "Home":
openTab();
}
}
private void openTab() {
}
private void openStore() {
View v = new View(MainActivity.this);
v.setVisibility(1);
v.clearFocus();
v.bringToFront();
}
private void openLists() {
Intent intent = new Intent(MainActivity.this,List_Activity.class);
startActivity(intent);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
};
actionbar.addTab(actionbar.newTab().setText("Home").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Store").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Lists").setTabListener(tablistener));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
private boolean firstTime() {
File storelist = new File(this.getFilesDir() + "\\StoreList.txt");
File listnames = new File(this.getFilesDir() + "\\ListNames.txt");
if(storelist.exists() && listnames.exists()){
return false;
}
else{
return true;
}
}
private void GenerateNeededFiles() {
Intent intent = new Intent(MainActivity.this,Install_Activity.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
}
private void openSearch() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Search");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The Class that gets an error when called
package dev.shaw.MyShoppingPlanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List_Activity extends ListActivity {
String ListNames[] = getListNames();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem , ListNames));
}
protected void onListItemClick(ListView lv, View v, int pos,long id){
this.onListItemClick(lv, v, pos, id);
ShoppingList list = new ShoppingList(ListNames[pos]);
try {
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list.toArray(list.getFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String[] getListNames() {
File file = new File(this.getFilesDir() + "\\listnames.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader is = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(is);
String line;
String names[] = new String[100];
int i = 0;
try {
while(true){
line = br.readLine();
if(line == null){
break;
}
else{
try{
names[i] = line;
}
catch(NullPointerException e){
e.printStackTrace();
}
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return names;
}
}
and here is the printStack
03-23 04:58:16.523: D/dalvikvm(3710): GC_FOR_ALLOC freed 151K, 18% free 2770K/3356K, paused 2ms, total 7ms
03-23 04:58:16.531: D/dalvikvm(3710): GC_FOR_ALLOC freed 100K, 19% free 2988K/3680K, paused 1ms, total 4ms
03-23 04:58:16.535: I/dalvikvm-heap(3710): Grow heap (frag case) to 4.414MB for 1127532-byte allocation
03-23 04:58:16.539: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 3ms, total 3ms
03-23 04:58:16.555: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 1ms, total 1ms
03-23 04:58:16.587: I/dalvikvm-heap(3710): Grow heap (frag case) to 6.833MB for 2536932-byte allocation
03-23 04:58:16.599: D/dalvikvm(3710): GC_FOR_ALLOC freed 0K, 10% free 6567K/7264K, paused 2ms, total 2ms
03-23 04:58:16.615: D/HardwareRenderer(3710): Profiling hardware renderer
03-23 04:58:16.647: D/libEGL(3710): loaded /system/lib/egl/libEGL_genymotion.so
03-23 04:58:16.651: D/(3710): HostConnection::get() New Host Connection established 0xb85b3b40, tid 3710
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv2_genymotion.so
03-23 04:58:16.711: W/EGL_genymotion(3710): eglSurfaceAttrib not implemented
03-23 04:58:16.711: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from GradienCache
03-23 04:58:16.723: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
03-23 04:58:16.723: D/OpenGLRenderer(3710): Enabling debug mode 0
03-23 04:58:18.015: D/AndroidRuntime(3710): Shutting down VM
03-23 04:58:18.015: W/dalvikvm(3710): threadid=1: thread exiting with uncaught exception (group=0xa4bae648)
03-23 04:58:18.015: E/AndroidRuntime(3710): FATAL EXCEPTION: main
03-23 04:58:18.015: E/AndroidRuntime(3710): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{dev.shaw.MyShoppingPlanner/dev.shaw.MyShoppingPlanner.List_Activity}: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Looper.loop(Looper.java:137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invoke(Method.java:525)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dalvik.system.NativeStart.main(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): Caused by: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:199)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:38)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.<init>(List_Activity.java:16)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstanceImpl(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstance(Class.java:1130)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
03-23 04:58:18.015: E/AndroidRuntime(3710): ... 11 more
I m learning android please help me. It gives me following errors in logcat.
02-27 14:14:42.455: D/dalvikvm(1655): GC_FOR_ALLOC freed 46K, 5% free 2891K/3020K, paused 152ms, total 156ms
02-27 14:14:42.465: I/dalvikvm-heap(1655): Grow heap (frag case) to 3.668MB for 810016-byte allocation
02-27 14:14:42.545: D/dalvikvm(1655): GC_FOR_ALLOC freed 2K, 4% free 3680K/3812K, paused 76ms, total 77ms
02-27 14:14:43.425: I/Choreographer(1655): Skipped 35 frames! The application may be doing too much work on its main thread.
02-27 14:14:43.645: D/gralloc_goldfish(1655): Emulator without GPU emulation detected.
02-27 14:14:48.395: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:49.725: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:52.355: I/Choreographer(1655): Skipped 61 frames! The application may be doing too much work on its main thread.
02-27 14:14:55.195: D/AndroidRuntime(1655): Shutting down VM
02-27 14:14:55.195: W/dalvikvm(1655): threadid=1: thread exiting with uncaught exception (group=0xb3aaaba8)
02-27 14:14:55.275: E/AndroidRuntime(1655): FATAL EXCEPTION: main
02-27 14:14:55.275: E/AndroidRuntime(1655): Process: com.example.dreamhome, PID: 1655
02-27 14:14:55.275: E/AndroidRuntime(1655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dreamhome/com.example.dreamhome.LoginFormActivity}: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Looper.loop(Looper.java:136)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-27 14:14:55.275: E/AndroidRuntime(1655): at dalvik.system.NativeStart.main(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): Caused by: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.example.dreamhome.LoginFormActivity.onCreate(LoginFormActivity.java:45)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Activity.performCreate(Activity.java:5231)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-27 14:14:55.275: E/AndroidRuntime(1655): ... 11 more
02-27 14:15:03.295: I/Process(1655): Sending signal. PID: 1655 SIG: 9
HomeActivity.java
public class HomeActivity extends Activity
{
Button search_property, log_in, exit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
search_property=(Button)findViewById(R.id.homebutton1);
log_in=(Button)findViewById(R.id.homebutton2);
exit=(Button)findViewById(R.id.homebutton3);
search_property.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main1=new Intent(HomeActivity.this,EndUserSearchPropertyActivity.class);
startActivity(main1);
}
});
log_in.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2 = new Intent(HomeActivity.this,LoginFormActivity.class);
startActivity(main2);
}
});
exit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
System.exit(0);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
this is LoginFormActivity.java
public class LoginFormActivity extends Activity
{
private Button sign_up = null;
private Button btnSignIn = null;
LoginDataBaseAdapter loginDataBaseAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
final Dialog dialog = new Dialog(LoginFormActivity.this);
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.login_editText1);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.login_editText2);
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(LoginFormActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(LoginFormActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
sign_up = (Button)findViewById(R.id.login_form_button2);
sign_up.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2=new Intent(LoginFormActivity.this,SignupFormActivity.class);
startActivity(main2);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
final Dialog dialog = new Dialog(LoginFormActivity.this);
Merely instantiating a dialog doesn't inflate/create its layout. All the subsequent dialog.findViewById() calls return null and you'll get the NPE here attempting to call a method on null reference:
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
You probably need to set a content view to your dialog with all the views you want to reference. The views are available with findViewById() after the dialog is showing.
I am trying to use putextra() and getextra() but my program is crashing after implementing it
Go through my code and let me know my mistake
If I am not using getextra() and putextra() the code is working flawlessly
This is 1st class from where I am getting the value
public class Assess extends ListActivity {
String itm;
ArrayAdapter<String> Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setBackgroundResource(R.drawable.background);
Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getResources()
.getStringArray(R.array.English));
setListAdapter(Adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
selectItem(pos);
itm = getListView().getItemAtPosition(pos).toString();
// Toast.makeText(getApplicationContext(), "CLicked",
// Toast.LENGTH_SHORT).show();
}
});
}
public void selectItem(int pos) {
switch (pos) {
case 0: {
Intent i;
List<Question> questions = getQuestionSetFromDb();
// Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((ChuckApplication) getApplication()).setCurrentGame(c);
// Start Game Now.. //
i = new Intent(this, QuestionActivity.class);
**i.putExtra("itemname", itm);**
//startActivityForResult(i, Constants.PLAYBUTTON);
startActivity(i);
//this.finish();
break;
}
}
}
Now the Second class where I am trying to Pass the item name
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
topic1 = i.getStringExtra("itemname");
Log.i("sanket", topic1);
/**
* Configure current game and get question
*/
currentGame = ((ChuckApplication) getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
RadioGroup rdgb = (RadioGroup) findViewById(R.id.group1);
rdgb.setOnCheckedChangeListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current
* games current question
*/
private void setQuestions() {
// set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "?";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
// set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
/*
* #Override public void onClick(View arg0) { //Log.d("Questions",
* "Moving to next question");
*//**
* validate a checkbox has been selected
*/
/*
* if (!checkAnswer()) return;
*//**
* check if end of game
*/
/*
* if (currentGame.isGameOver()){ //Log.d("Questions",
* "End of game! lets add up the scores.."); //Log.d("Questions",
* "Questions Correct: " + currentGame.getRight()); //Log.d("Questions",
* "Questions Wrong: " + currentGame.getWrong()); Intent i = new
* Intent(this, EndgameActivity.class); startActivity(i); finish(); } else{
* Intent i = new Intent(this, QuestionActivity.class); startActivity(i);
* finish(); } }
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (a > 0) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
return true;
}
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it has then check if its
* correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer == null) {
// Log.d("Questions", "No Checkbox selection made - returning");
return false;
} else {
// Log.d("Questions",
// "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer)) {
// Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
} else {
// Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
}
return true;
}
}
/**
*
*/
public String getSelectedAnswer() {
RadioButton c1 = (RadioButton) findViewById(R.id.answer1);
RadioButton c2 = (RadioButton) findViewById(R.id.answer2);
RadioButton c3 = (RadioButton) findViewById(R.id.answer3);
RadioButton c4 = (RadioButton) findViewById(R.id.answer4);
if (c1.isChecked()) {
return c1.getText().toString();
}
if (c2.isChecked()) {
return c2.getText().toString();
}
if (c3.isChecked()) {
return c3.getText().toString();
}
if (c4.isChecked()) {
return c4.getText().toString();
}
return null;
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
// Log.d("Questions", "Moving to next question");
a++;
/**
* validate a checkbox has been selected
*/
if (!checkAnswer())
return;
/**
* check if end of game
*/
if (currentGame.isGameOver()) {
// db.open();
// db.insertOptions(topic1, currentGame.getRight(), month);
// Log.d("Questions", "End of game! lets add up the scores..");
// Log.d("Questions", "Questions Correct: " +
// currentGame.getRight());
// Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
// db.close();
} else {
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
}
Or is there any other way to carry data from one page to other page other than putextra() and getextra().
Here is my LOGCAT
02-04 10:33:35.697: E/AndroidRuntime(1776): FATAL EXCEPTION: main
02-04 10:33:35.697: E/AndroidRuntime(1776): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tmm.android.chuck/com.tmm.android.chuck.QuestionActivity}: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.os.Looper.loop(Looper.java:130)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-04 10:33:35.697: E/AndroidRuntime(1776): at java.lang.reflect.Method.invokeNative(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): at java.lang.reflect.Method.invoke(Method.java:507)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-04 10:33:35.697: E/AndroidRuntime(1776): at dalvik.system.NativeStart.main(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): Caused by: java.lang.NullPointerException: println needs a message
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.util.Log.println_native(Native Method)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.util.Log.i(Log.java:158)
02-04 10:33:35.697: E/AndroidRuntime(1776): at com.tmm.android.chuck.QuestionActivity.onCreate(QuestionActivity.java:48)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-04 10:33:35.697: E/AndroidRuntime(1776): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-04 10:33:35.697: E/AndroidRuntime(1776): ... 11 more
Try out to get the string as below :
First change your onItemClickListener as below: You need to assign value to your itm variable and then call the selectItem() method so that your itm variable is not null.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
itm = getListView().getItemAtPosition(pos).toString();
selectItem(pos);
}
});
Get the String in your another activity as below:
String topic1 =getIntent().getStringExtra("itemname");
first initialize the itm String in OnItemClickListener implementation of ListView, then call selectItem() method.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
itm = getListView().getItemAtPosition(pos).toString(); // initialize it first.
selectItem(pos);
// Toast.makeText(getApplicationContext(), "CLicked",
// Toast.LENGTH_SHORT).show();
}
});
and in reeiving Activity, get this String as
topic1 = getIntent().getStringExtra("itemname");
You should read string from getIntent(). Read like below
topic1 = getIntent().getStringExtra("itemname");
It must be a NullPointerException because "itm" will always be null in that scope
Why don't you make it like this:
itm = getListView().getItemAtPosition(pos).toString();
selectItem(pos,itm);
And then pass it as extra in this method
Hope that helps :)