This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
My app is getting some errors whenever I click the signout button. I suspect that this causes by the authentication.signout().
This is the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.demo.finalssuncrestbank, PID: 17982
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.firestore.DocumentSnapshot.getString(java.lang.String)' on a null object reference
at com.demo.finalssuncrestbank.UserProfile$1.onEvent(UserProfile.java:52)
at com.demo.finalssuncrestbank.UserProfile$1.onEvent(UserProfile.java:49)
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2(DocumentReference.java:483)
at com.google.firebase.firestore.DocumentReference$$Lambda$3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6521)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The code is this:
DocumentReference documentReference = fStore.collection("Users").document(UserID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
mName.setText("Name: " + value.getString("Name"));
mPhone.setText("Phone: " + value.getString("Phone"));
mEmail.setText("Email: \n \n" + value.getString("Email"));
mBalance.setText(String.valueOf(value.getDouble("Balance")));
}
});
LogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fAuth.signOut();
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
}
});
I wanted to know what are the possible reasons why this keeps happening and what should I do?
You are accessing UI in your listener. The listener will listen to any changes forever or in your user log out listener, you are navigating to another Activity which mean the current Activity/UI is null and the listener addSnapshotListener will be triggred as there is a change in authorisation state.
You must detach your snapshot listener before sending your intent: https://firebase.google.com/docs/firestore/query-data/listen#java_11
DocumentReference documentReference = fStore.collection("Users").document(UserID);
ListenerRegistration registration = documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
mName.setText("Name: " + value.getString("Name"));
mPhone.setText("Phone: " + value.getString("Phone"));
mEmail.setText("Email: \n \n" + value.getString("Email"));
mBalance.setText(String.valueOf(value.getDouble("Balance")));
}
});
LogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Stop listening to changes
registration.remove();
fAuth.signOut();
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
}
});
When it logout, again it notifies in addSnapshotListener. But this time FirebaseFirestoreException. So make sure before accesing value if there is no error.
DocumentReference documentReference = fStore.collection("Users").document(UserID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if( error == null){
mName.setText("Name: " + value.getString("Name"));
mPhone.setText("Phone: " + value.getString("Phone"));
mEmail.setText("Email: \n \n" + value.getString("Email"));
mBalance.setText(String.valueOf(value.getDouble("Balance")));
}
}
});
LogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fAuth.signOut();
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
}
});
Related
suggest collectionusers collectionI have a simple suggestion page where I can type title and contents, then store some other information to the Firestore, show it on ListView pages. It works fine itself, but after I send it, an error pops and it shows the bug is the timestamp toDate on the listview pages
The order of activities is listview>sending page>listview.
//the send activity
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getId();
String title = art1.getText().toString();
String content = art2.getText().toString();
Intent intent = new Intent(create_announce_main.this, SuggestionMain.class);
// DocumentReference documentReference = firebaseFirestore.collection("announce").document("ann");
Map<String, Object> suggest = new HashMap<>();
suggest.put("title", title);
suggest.put("content", content);
suggest.put("name", name);
suggest.put("recID", recID);
suggest.put("admin_name", "");
suggest.put("response_content", "");
suggest.put("response_status", "未回覆");
suggest.put("response_time",FieldValue.serverTimestamp());
suggest.put("createdAt", FieldValue.serverTimestamp());
firebaseFirestore.collection("Suggestion").document().set(suggest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(create_announce_main.this, "added succesfully", Toast.LENGTH_LONG).show();
}
}
});
startActivity(intent);
}
});
to listview page
//the view
DocumentReference docRef = firebaseFirestore.collection("users").document(userID);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d("TAG", "DocumentSnapshot data: " + document.getData());
recID = document.getString("recID");
firebaseFirestore.collection("Suggestion").whereEqualTo("recID",recID).orderBy("createdAt", Query.Direction.DESCENDING).addSnapshotListener((documentSnapshots, error) -> {
ar.clear();
for (DocumentSnapshot snapshot : documentSnapshots){
idlv = snapshot.getId();
Timestamp timestamp = (Timestamp) snapshot.getData().get("createdAt");
**Date date = timestamp.toDate();//the error is at here**
String date2 = date.toString();
ar.add(new itemAnnounce(R.drawable.notes, snapshot.getString("title"),"回饋於 "+date2,"回覆管理者:"+snapshot.getString("admin_name"),"回覆狀態:"+snapshot.getString("response_status"),idlv,url));
}
adapterAnnounce adapterAnnounce = new adapterAnnounce(getApplicationContext(), R.layout.list_row_announce, ar);
adapterAnnounce.notifyDataSetChanged();
lv1.setAdapter(adapterAnnounce);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object selectedObj =adapterAnnounce.getItem(position).getId();// this will get you selected obj of itemAnnounce
String obj = (String)selectedObj.toString();
Intent i = new Intent(SuggestionMain.this, announce_Page.class);
i.putExtra("annId",obj);
startActivity(i);
}
});
});
} else {
Log.d("TAG", "No such document");
}
} else {
Log.d("TAG", "get failed with ", task.getException());
}
}
});
the error pops
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.districtapp, PID: 12764
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date com.google.firebase.Timestamp.toDate()' on a null object reference
at com.example.districtapp.SuggestionMain$1.lambda$onComplete$0$SuggestionMain$1(SuggestionMain.java:65)
at com.example.districtapp.-$$Lambda$SuggestionMain$1$70rkZQjkWJS7wHwVoKS2O7TV5ls.onEvent(Unknown Source:4)
at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2(Query.java:1133)
at com.google.firebase.firestore.Query$$Lambda$3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
I have impression about this sort of thing when I touch firestore the first time,So i tried to start the send activity first not the view,it works out but just for once,second time it shows the same bug,I tried to finish the whole activity listview when onclick to sendpage,still dont work,
Firestore is getting the data perfectly, and after restarting the app, listview shows the data, so the function is working though.
suggest field
You are getting NullPointerException because of the following line of code:
Date date = timestamp.toDate();
And this is because the timestamp object in:
Timestamp timestamp = (Timestamp) snapshot.getData().get("createdAt");
Has the value of null. To solve this, please change the above line of code to:
if (snapshot.getDate("createdAt") != null) {
Date timestamp = snapshot.getDate("createdAt");
//Do what you need to do with this timestamp
}
Besides that, a query like this:
firebaseFirestore.collection("Suggestion").whereEqualTo("recID",recID).orderBy("createdAt", Query.Direction.DESCENDING)
Requires an index. To add such an index please check my answer from the following post:
Firestore whereEqualTo, orderBy and limit(1) not working
I'm trying to create an onClickListener for another class, but there's a NullPointerException. I already tried to pass the value of context, but still, it didn't work. I don't know what value is null.
This is the class for ExternalOnClickListener
public class ExternalOnClickListener implements View.OnClickListener{
private Context context;
public ExternalOnClickListener(Context c) {
context = c;
}
public void setRowCol(Intent hardLevelIntent) {
hardLevelIntent.putExtra("rowCount", 6);
hardLevelIntent.putExtra("colCount", 6);
hardLevelIntent.putExtra("difficulty", 3);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View v) {
//Hard levels intent
Intent hardLevelIntent = new Intent(context, GameActivity.class);
setRowCol(hardLevelIntent);
switch (v.getId()) {
case R.id.btnBack:
Intent intent = new Intent(context, Level_Selection.class);
context.startActivity(intent);
break;
case R.id.btnHard1:
hardLevelIntent.putExtra("hardStageCount", 1);
context.startActivity(hardLevelIntent);
break;
}
}
}
And the btnEndless.onClickListener() here is trying to create an object for the external onClick. But there's a null pointer exception
public class Level_Selection extends AppCompatActivity {
ImageButton btnBack, btnEasy, btnAverage, btnHard, btnEndless;
ImageButton btnHard1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level__selection);
this.btnBack = findViewById(R.id.btnBack);
this.btnEasy = findViewById(R.id.btnEasy);
this.btnAverage = findViewById(R.id.btnAverage);
this.btnHard = findViewById(R.id.btnHard);
this.btnEndless = findViewById(R.id.btnEndless);
this.btnHard1 = findViewById(R.id.btnHard1);
btnBack.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Menu.class);
startActivity(intent);
});
btnEasy.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Easy.class);
startActivity(intent);
});
btnAverage.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Average.class);
startActivity(intent);
});
btnHard.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), Level_Hard.class);
startActivity(intent);
});
btnEndless.setOnClickListener(v -> {
btnHard1.setOnClickListener(new ExternalOnClickListener(getApplicationContext()));
btnHard1.performClick();
});
}
This is the error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flip, PID: 10862
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.flip.Level_Selection.lambda$onCreate$4$Level_Selection(Level_Selection.java:59)
at com.flip.-$$Lambda$Level_Selection$EhORL8AmJ4WhZjndwpPfbUXg1uA.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:6312)
at android.view.View$PerformClick.run(View.java:24811)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
I hope someone answers my question. Thanks in advance!
Try check btnHard1 value, is it null?
Make sure there is ImageButton with id 'btnHard1' in your activity_level__selection layout.
Seems like your R.layout.activity_level__selection, doesn't containt of button which you set click listener or has different id
I'm getting this error when i create new user on firebase from my sign-up form :
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
I search about this error on google and on YouTube but i don't found something for my program.
Here is a part of my code on SignUpActivity.java:
final EditText email = findViewById(R.id.email_address);
final EditText display_name = findViewById(R.id.display_name);
final EditText password = findViewById(R.id.pass_sign_up);
final EditText comfirm_pass = findViewById(R.id.comfirm_pass);
final Button submit = findViewById(R.id.submit_btn_signup);
final TextView signin = findViewById(R.id.textView8);
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final String[] error = new String[1];
final ProgressBar loading_icon = findViewById(R.id.progressBar2);
// hide loading icon \\
loading_icon.setVisibility(View.GONE);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignupActivity.this,MainActivity.class);
startActivity(intent);
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loading_icon.setVisibility(View.VISIBLE);
String email_input = email.getText().toString();
String display_name_input = display_name.getText().toString();
String password_input = password.getText().toString();
String comfirm_pass_input = comfirm_pass.getText().toString();
if (email_input.isEmpty() || display_name_input.isEmpty() || password_input.isEmpty() || comfirm_pass_input.isEmpty()){
error[0] = "Please fill all the values and try again";
Toast.makeText(SignupActivity.this, error[0], Toast.LENGTH_LONG).show();
loading_icon.setVisibility(View.GONE);
}else{
if (!password_input.equals(comfirm_pass_input)){
error[0] = "passwords do not match";
Toast.makeText(SignupActivity.this, error[0], Toast.LENGTH_LONG).show();
loading_icon.setVisibility(View.GONE);
}else{
mAuth.createUserWithEmailAndPassword(email_input,password_input).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull #NotNull Task<AuthResult> task) {
if (task.isSuccessful()){
finish();
// set display name for user \\
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(display_name_input).build();
user.updateProfile(profileUpdates);
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
mRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot){
// Get the max_user_id to set the main user id and create the user on Firebase real-time DB \\
String maxUserId = dataSnapshot.child("max_user_id").getValue().toString();
int maxUserIdToInt = Integer.parseInt(maxUserId);
int userId = maxUserIdToInt+1;
newUserId = String.valueOf(userId);
mRef.child("users").child(newUserId).child("name").setValue(display_name_input);
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError){
Toast.makeText(SignupActivity.this,"error: " + databaseError, Toast.LENGTH_LONG).show();
}
});
mRef.child("users").child(newUserId);
Intent intent = new Intent(SignupActivity.this,HomeActivity.class);
startActivity(intent);
}else{
loading_icon.setVisibility(View.GONE);
error[0] = "failed to sign up, the email address aleready exist or the password lenght is lower than 6 characters";
Toast.makeText(SignupActivity.this, error[0], Toast.LENGTH_LONG).show();
}
}
});
}
}
}
});
}
}
NOTE: i'm beginner on firebase for android applications. Also i created today my account here and stackoverflow is so cool and helpfull
When you call child(), you need to pass a non-null String as the parameter. In your case, newUserId is null for some reason. Hence you call child(newUserId), Firebase throws an exception.
The way forward should be check if the way you are accessing child with path max_user_id is correct or not. You can keep a breakpoint at that location and then go through the structure of dataSnapshot to get the correct path.
The problem is in the last line in this fragment:
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
mRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot){
// Get the max_user_id to set the main user id and create the user on Firebase real-time DB \\
String maxUserId = dataSnapshot.child("max_user_id").getValue().toString();
int maxUserIdToInt = Integer.parseInt(maxUserId);
int userId = maxUserIdToInt+1;
newUserId = String.valueOf(userId);
mRef.child("users").child(newUserId).child("name").setValue(display_name_input);
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError){
Toast.makeText(SignupActivity.this,"error: " + databaseError, Toast.LENGTH_LONG).show();
}
});
mRef.child("users").child(newUserId);
That line does nothing meaningful, but it executes before newUserId = String.valueOf(userId), which means you're passing in an initialized newUserId and that causes the error messages.
Since this line mRef.child("users").child(newUserId); does nothing anyway, you can safely remove it.
As a general rule: you should only use the newUserId inside the onDataChange or in code that is called from there. For this reason, I recommend making it a local variable in onDataChange instead of a field or otherwise broader scope. For more on why this is, see Is it possible to synchronously load data from Firebase? and Setting Singleton property value in Firebase Listener.
I am working on my App, and till now the App runs fine despite some small errors. The user can sign in, login and change his profile information. In the last steps, I added a function to delete userinformation. The delete function works so the userinformation gets deleted from FirebaseAuth and the FirebaseRealtimeDatabase but the app crashes.
Before I already had problems with passing null values, maybe thats related to the problem.
Update: I changed the code and tried to implement the suggestions but its still crashing...
Logcat:
09-18 16:28:20.474 23342-23342/com.example.login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 23342
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.login.UserProfil.getVorname()' on a null object reference
at com.example.login.ProfileActivity$1.onDataChange(ProfileActivity.java:59)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.0.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.0.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.0.0:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Some part of my ProfileActivity
firebaseAuth=FirebaseAuth.getInstance();
firebaseDatabase= FirebaseDatabase.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
firebaseDatabase= FirebaseDatabase.getInstance();
final DatabaseReference databaseReference = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) ;
{
UserProfil userProfil = dataSnapshot.getValue(UserProfil.class);
profilVorname.setText(userProfil.getVorname());
profilNachname.setText(userProfil.getNachname());
profilStrasse.setText(userProfil.getStrasse());
profilHNr.setText(userProfil.getHnr());
profilPlz.setText(userProfil.getPlz());
profilStadt.setText(userProfil.getStadt());
profilLand.setText(userProfil.getLand());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, "Database Error", Toast.LENGTH_SHORT).show();
}
});
}else{
startActivity(new Intent(ProfileActivity.this,NavActivity.class));
}
Some part of my UpdatProfilActivity
loeschen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final DatabaseReference databaseReference = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
databaseReference.removeValue();
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
// firebaseAuth.signOut();
// startActivity(new Intent(UpdateProfilActivity.this, MainActivity.class));
//finish();
}
}
});
}
});
This is most probably due to that the 'dataSnapshot' object is null when onDataChange() is triggered upon deletion; you can return if it is null
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists())
return;
UserProfil userProfil = dataSnapshot.getValue(UserProfil.class);
profilVorname.setText(userProfil.getVorname());
profilNachname.setText(userProfil.getNachname());
profilStrasse.setText(userProfil.getStrasse());
profilHNr.setText(userProfil.getHnr());
profilPlz.setText(userProfil.getPlz());
profilStadt.setText(userProfil.getStadt());
profilLand.setText(userProfil.getLand());
}
When addValueEventListener is used, then it listens on every event what happened with current reference. And when you delete it then dataSnapshot in listener comes null and on getVorname() exception is thrown.
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"/>