Unable to fetch a value from the Firestore database. Trying to retrieve the value of the mobile number as and when the value of flat and block matches the entry in the database. Below is the code I am using. I have also attached the issues that are registered in LogCat file. Please check and help.
public class Test extends AppCompatActivity {
Button btn;
private FirebaseFirestore firestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
firestore = FirebaseFirestore.getInstance();
btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getmobile();
//makecall();
}
});
}
private void makecall(){
Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
intent.setData(Uri.parse("tel:9890910640"));
startActivity(intent);
}
private void getmobile() {
firestore.collection("users").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
String a = "101";
String b = "F1A";
for(DocumentSnapshot document: documentSnapshots){
if(document.getString("flat")==a&&document.getString("block")==b){
String mobilefromdatabase = document.get("mobile").toString();
Toast.makeText(Test.this, "mobile" + mobilefromdatabase, Toast.LENGTH_LONG).show();
break;
}
}
}
});
}
}
Logcat Details
05-05 03:59:26.721 8805-8805/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
05-05 03:59:26.721 8805-8805/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
05-05 03:59:26.722 8805-8805/? I/art: Not late-enabling -Xcheck:jni (already on)
05-05 03:59:26.770 8805-8805/com.example.myrwaapp I/MultiDex: VM with version 2.1.0 has multidex support
05-05 03:59:26.770 8805-8805/com.example.myrwaapp I/MultiDex: Installing application
05-05 03:59:26.770 8805-8805/com.example.myrwaapp I/MultiDex: VM has multidex support, MultiDex support library is disabled.
05-05 03:59:26.842 8805-8805/com.example.myrwaapp V/FA: Registered activity lifecycle callback
05-05 03:59:26.857 8805-8831/com.example.myrwaapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
05-05 03:59:26.861 8805-8805/com.example.myrwaapp I/FirebaseInitProvider: FirebaseApp initialization successful
05-05 03:59:26.907 8805-8834/com.example.myrwaapp W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
05-05 03:59:26.925 8805-8834/com.example.myrwaapp I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
05-05 03:59:26.986 8805-8805/com.example.myrwaapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-05 03:59:27.010 8805-8805/com.example.myrwaapp V/FA: onActivityCreated
05-05 03:59:27.047 8805-8805/com.example.myrwaapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
05-05 03:59:27.047 8805-8805/com.example.myrwaapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
05-05 03:59:27.048 8805-8830/com.example.myrwaapp V/FA: App measurement collection enabled
05-05 03:59:27.049 8805-8830/com.example.myrwaapp V/FA: App measurement enabled for app package, google app id: com.example.myrwaapp, 1:649640616763:android:9025242f82dd4767798d1e
05-05 03:59:27.052 8805-8830/com.example.myrwaapp I/FA: App measurement initialized, version: 21028
05-05 03:59:27.052 8805-8830/com.example.myrwaapp I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
05-05 03:59:27.052 8805-8830/com.example.myrwaapp I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.myrwaapp
05-05 03:59:27.052 8805-8830/com.example.myrwaapp D/FA: Debug-level message logging enabled
05-05 03:59:27.077 8805-8830/com.example.myrwaapp V/FA: Connecting to remote service
05-05 03:59:27.089 8805-8830/com.example.myrwaapp V/FA: Connection attempt already in progress
05-05 03:59:27.143 8805-8830/com.example.myrwaapp V/FA: Activity resumed, time: 8622127
05-05 03:59:27.145 8805-8830/com.example.myrwaapp I/FA: Tag Manager is not found and thus will not be used
05-05 03:59:27.151 8805-8838/com.example.myrwaapp D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
05-05 03:59:27.154 8805-8805/com.example.myrwaapp D/Atlas: Validating map...
05-05 03:59:27.159 8805-8830/com.example.myrwaapp V/FA: Connection attempt already in progress
05-05 03:59:27.159 8805-8830/com.example.myrwaapp V/FA: Connection attempt already in progress
05-05 03:59:27.188 8805-8838/com.example.myrwaapp I/OpenGLRenderer: Initialized EGL, version 1.4
05-05 03:59:27.188 8805-8838/com.example.myrwaapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
05-05 03:59:27.215 8805-8838/com.example.myrwaapp D/EGL_emulation: eglCreateContext: 0xa2003100: maj 2 min 0 rcv 2
05-05 03:59:27.240 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:27.243 8805-8838/com.example.myrwaapp D/OpenGLRenderer: Enabling debug mode 0
05-05 03:59:27.294 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:27.738 8805-8830/com.example.myrwaapp D/FA: Connected to remote service
05-05 03:59:27.738 8805-8830/com.example.myrwaapp V/FA: Processing queued up service tasks: 4
05-05 03:59:32.795 8805-8830/com.example.myrwaapp V/FA: Inactivity, disconnecting from the service
05-05 03:59:38.884 8805-8830/com.example.myrwaapp V/FA: Recording user engagement, ms: 11740
05-05 03:59:38.886 8805-8830/com.example.myrwaapp V/FA: Connecting to remote service
05-05 03:59:38.892 8805-8830/com.example.myrwaapp V/FA: Activity paused, time: 8633867
05-05 03:59:38.894 8805-8805/com.example.myrwaapp V/FA: onActivityCreated
05-05 03:59:38.913 8805-8830/com.example.myrwaapp V/FA: Connection attempt already in progress
05-05 03:59:38.913 8805-8830/com.example.myrwaapp V/FA: Activity resumed, time: 8633895
05-05 03:59:38.926 8805-8830/com.example.myrwaapp V/FA: Connection attempt already in progress
05-05 03:59:38.926 8805-8830/com.example.myrwaapp V/FA: Connection attempt already in progress
05-05 03:59:38.993 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:39.034 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:39.051 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:39.177 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:39.222 8805-8830/com.example.myrwaapp D/FA: Connected to remote service
05-05 03:59:39.222 8805-8830/com.example.myrwaapp V/FA: Processing queued up service tasks: 4
05-05 03:59:39.224 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:39.335 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:44.247 8805-8830/com.example.myrwaapp V/FA: Inactivity, disconnecting from the service
05-05 03:59:48.704 8805-8838/com.example.myrwaapp D/EGL_emulation: eglMakeCurrent: 0xa2003100: ver 2 0 (tinfo 0xb4233e90)
05-05 03:59:48.871 8805-8849/com.example.myrwaapp W/DynamiteModule: Local module descriptor class for providerinstaller not found.
05-05 03:59:48.877 8805-8849/com.example.myrwaapp I/DynamiteModule: Considering local module providerinstaller:0 and remote module providerinstaller:0
05-05 03:59:48.877 8805-8849/com.example.myrwaapp W/ProviderInstaller: Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
05-05 03:59:48.881 8805-8849/com.example.myrwaapp W/ResourcesManager: Asset path '/system/framework/com.android.media.remotedisplay.jar' does not exist or contains no resources.
05-05 03:59:48.881 8805-8849/com.example.myrwaapp W/ResourcesManager: Asset path '/system/framework/com.android.location.provider.jar' does not exist or contains no resources.
05-05 03:59:48.942 8805-8849/com.example.myrwaapp W/linker: libconscrypt_gmscore_jni.so: unused DT entry: type 0x6ffffffe arg 0x13dc
05-05 03:59:48.942 8805-8849/com.example.myrwaapp W/linker: libconscrypt_gmscore_jni.so: unused DT entry: type 0x6fffffff arg 0x2
05-05 03:59:48.948 8805-8849/com.example.myrwaapp V/NativeCrypto: Registering com/google/android/gms/org/conscrypt/NativeCrypto's 284 native methods...
05-05 03:59:48.963 8805-8820/com.example.myrwaapp I/art: Background sticky concurrent mark sweep GC freed 976(49KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 8MB/8MB, paused 5.861ms total 31.265ms
05-05 03:59:48.992 8805-8849/com.example.myrwaapp I/art: Rejecting re-init on previously-failed class java.lang.Class<com.google.android.gms.org.conscrypt.Java7ExtendedSSLSession>
05-05 03:59:48.992 8805-8849/com.example.myrwaapp I/art: Rejecting re-init on previously-failed class java.lang.Class<com.google.android.gms.org.conscrypt.Java7ExtendedSSLSession>
05-05 03:59:48.992 8805-8849/com.example.myrwaapp I/art: Rejecting re-init on previously-failed class java.lang.Class<com.google.android.gms.org.conscrypt.Java8ExtendedSSLSession>
05-05 03:59:48.992 8805-8849/com.example.myrwaapp I/art: Rejecting re-init on previously-failed class java.lang.Class<com.google.android.gms.org.conscrypt.Java8ExtendedSSLSession>
05-05 03:59:49.002 8805-8849/com.example.myrwaapp I/ProviderInstaller: Installed default security provider GmsCore_OpenSSL
First of all, String comparison in Java, should not be performed using == operator, as it will always compare the address of the objects from the memory and not the actual values. String comparison should be done using equals() method.
Moreover, if you need an AND operation, you should not get all documents that exist within the users collection and make the comparison on the client. For that, you should use a query that looks exactly like this:
String a = "101";
String b = "F1A";
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
Query query = usersRef.whereEqualTo("flat", a).whereEqualTo("block", b);
query.get().addOnSuccessListener(/* ... */);
In this way, you are going to get only the documents where the flat property holds the value of 101 AND the value of block holds F1A. As I think that only one apartment has that constraint, you'll be billed with only one read operation.
Related
i am making login page so i have connected this app with firebase database there is email and password in database so i am trying to
Signinwithemailandpassword but it doesn't work whenever i try to run the apps it crashes
loginpage.java
public class loginpage extends AppCompatActivity {
ActivityLoginpageBinding binding;
Button loginbtn;
TextView login;
FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLoginpageBinding.inflate(getLayoutInflater());
setContentView(R.layout.activity_loginpage);
login=findViewById(R.id.login);
auth=FirebaseAuth.getInstance();
loginbtn=findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
final String email=binding.email.getText().toString();
final String password=binding.pwd.getText().toString();
#Override
public void onClick(View view) {
auth.signInWithEmailAndPassword(binding.email.getText().toString(),binding.pwd.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent=new Intent(loginpage.this,MainActivity.class);
startActivity(intent);
Toast.makeText(loginpage.this, "successfull", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(loginpage.this, "failed", Toast.LENGTH_SHORT).show();
Log.d("MyTag", task.getException().getMessage());
}
}
});
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(loginpage.this,signup.class);
startActivity(intent);
}
});
}
}
loginpage.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".loginpage">
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Instagram"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="242dp"
android:layout_height="235dp"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView14"
app:srcCompat="#drawable/instagram" />
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to social world"
android:textSize="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView3" />
<EditText
android:id="#+id/email"
android:layout_width="297dp"
android:layout_height="49dp"
android:layout_marginTop="44dp"
android:background="#drawable/inputbg"
android:ems="10"
android:hint="Email"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView16" />
<EditText
android:id="#+id/pwd"
android:layout_width="297dp"
android:layout_height="49dp"
android:layout_marginTop="16dp"
android:background="#drawable/inputbg"
android:ems="10"
android:hint="Password"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email"
app:layout_constraintVertical_bias="0.017" />
<Button
android:id="#+id/loginbtn"
android:layout_width="298dp"
android:layout_height="51dp"
android:layout_marginTop="36dp"
android:text="login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pwd" />
<TextView
android:id="#+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Don't have a account? "
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/login"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loginbtn"
app:layout_constraintVertical_bias="0.859" />
<TextView
android:id="#+id/login"
android:layout_width="63dp"
android:layout_height="18dp"
android:text="Sign up!"
android:textColor="#F10606"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/textView15"
app:layout_constraintTop_toBottomOf="#+id/loginbtn"
app:layout_constraintVertical_bias="0.86" />
</androidx.constraintlayout.widget.ConstraintLayout>`
Error
12/24 12:13:07: Launching 'app' on Pixel 5 API 26.
App restart successful without requiring a re-install.
$ adb shell am start -n "com.example.instagram/com.example.instagram.signup" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 28962 on device 'Pixel_5_API_26 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/zygote: Late-enabling -Xcheck:jni
W/zygote: Unexpected CPU variant for X86 using defaults: x86
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
W/zygote: Skipping duplicate class check due to unrecognized classloader
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:86 and remote module com.google.android.gms.measurement.dynamite:15
I/DynamiteModule: Selected local version of com.google.android.gms.measurement.dynamite
D/FirebaseAuth: Notifying id token listeners about user ( xmoP2dPpYhUD9acalVCdTqBiJ7e2 ).
I/FirebaseInitProvider: FirebaseApp initialization successful
I/zygote: Background concurrent copying GC freed 5896(1215KB) AllocSpace objects, 2(40KB) LOS objects, 62% free, 910KB/2MB, paused 1.368ms total 117.164ms
V/FA: onActivityCreated
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id: com.example.instagram, 1:582042892352:android:f97df8209dee5aa33f87a5
I/FA: App measurement initialized, version: 74029
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.instagram
D/FA: Debug-level message logging enabled
D/FA: Resetting session stitching token to not null
I/zygote: NativeAllocBackground concurrent copying GC freed 4528(591KB) AllocSpace objects, 7(140KB) LOS objects, 59% free, 1046KB/2MB, paused 3.590ms total 105.851ms
V/FA: Connecting to remote service
V/FA: Detected application was in foreground
V/FA: Session started, time: 37468155
I/zygote: Do partial code cache collection, code=30KB, data=30KB
V/FA: Connection attempt already in progress
I/zygote: After code cache collection, code=24KB, data=28KB
I/zygote: Increasing code cache capacity to 128KB
I/FA: Tag Manager is not found and thus will not be used
I/zygote: Do partial code cache collection, code=24KB, data=46KB
I/zygote: After code cache collection, code=24KB, data=46KB
I/zygote: Increasing code cache capacity to 256KB
I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
D/OpenGLRenderer: HWUI GL Pipeline
V/FA: Connection attempt already in progress
I/chatty: uid=10097(u0_a97) Measurement Wor identical 1 line
V/FA: Connection attempt already in progress
V/FA: Activity resumed, time: 37468263
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/: HostConnection::get() New Host Connection established 0x9f3f98c0, tid 29000
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/EGL_emulation: eglCreateContext: 0x9f4d4620: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x9f4d4620: ver 2 0 (tinfo 0x9f6ff450)
D/EGL_emulation: eglMakeCurrent: 0x9f4d4620: ver 2 0 (tinfo 0x9f6ff450)
I/Choreographer: Skipped 51 frames! The application may be doing too much work on its main thread.
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 7
W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
I/AssistStructure: Flattened final assist data: 3448 bytes, containing 1 windows, 12 views
I/zygote: Do full code cache collection, code=124KB, data=61KB
I/zygote: After code cache collection, code=120KB, data=46KB
V/FA: Inactivity, disconnecting from the service
I/zygote: Do partial code cache collection, code=122KB, data=50KB
I/zygote: After code cache collection, code=122KB, data=50KB
I/zygote: Increasing code cache capacity to 512KB
V/FA: Recording user engagement, ms: 54118
V/FA: onActivityCreated
V/FA: Connecting to remote service
V/FA: Connection attempt already in progress
V/FA: Activity paused, time: 37522383
V/FA: Activity resumed, time: 37522548
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/EGL_emulation: eglMakeCurrent: 0x9f4d4620: ver 2 0 (tinfo 0x9f6ff450)
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 4
W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
I/AssistStructure: Flattened final assist data: 2780 bytes, containing 1 windows, 10 views
I/zygote: Do full code cache collection, code=249KB, data=167KB
I/zygote: After code cache collection, code=249KB, data=134KB
V/FA: Inactivity, disconnecting from the service
I/zygote: Do partial code cache collection, code=249KB, data=139KB
I/zygote: After code cache collection, code=249KB, data=139KB
I/zygote: Increasing code cache capacity to 1024KB
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.instagram, PID: 28962
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(com.google.android.gms:play-services-basement##18.1.0:2)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(com.google.firebase:firebase-auth##21.1.0:1)
at com.example.instagram.loginpage$1.onClick(loginpage.java:44)
at android.view.View.performClick(View.java:6256)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
at android.view.View$PerformClick.run(View.java:24701)
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)
need to find out the mistake and why app crashes
Where have you set the values for the email and password when you are authenticating with firebase?
In your code, you are doing binding.email.getText().toString() and binding.pwd.getText().toString(). These are potentially empty as I am not seeing you set the value of those views either in your xml or in your code and hence the exception is being thrown.
Just try setting those in your xml or via code and try authentication, it should work.
I'm trying to create an app if someone want to use my app they must create a user.
When they register they will insert first name, last name, phone and email address.
After I confirm that the phone is theirs by using Firebase authorization I want to insert his data to a table named Users in my RealTime Database.
When I tried to do it by using this function:
**EDIT: I added the onComplete function but it doesn't execute **
private void storeNewUserData() {
FirebaseDatabase rootNode = FirebaseDatabase.getInstance();
DatabaseReference reference = rootNode.getReference("Users");
User user = new User(phone,firstName,lastName,email);
reference.setValue(user).addOnCompleteListener(this);
}
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(this, "Inserted User: "+phone+firstName+lastName+email, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
The database has not been updated but the Toast appeared (with all the data).
I don't think there is a problem in my code maybe it's a problem in my Firebase account.. Anyway I add the rules to this database and an image of the table.
Rules
{
"rules": {
".read": "true",
".write": "true"
}
}
build.gradle(app)
dependencies {
implementation platform('com.google.firebase:firebase-bom:26.8.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-auth:20.0.3'
implementation 'com.google.firebase:firebase-database:19.7.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "androidx.browser:browser:1.3.0"
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
}
';
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
progressDialog.dismiss();
User user = new User(phone,firstName,lastName,email);
storeNewUserData();
Toast.makeText(PhoneAuthActivity.this, "Logged in as "+phone, Toast.LENGTH_SHORT).show();
startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(PhoneAuthActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
logcat
2021-03-30 03:41:02.326 15207-15345/com.example.teorialearning E/FirebaseAuth: [GetAuthDomainTask] Error getting project config. Failed with INVALID_CERT_HASH 400
2021-03-30 03:41:02.344 15207-15257/com.example.teorialearning V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 396
2021-03-30 03:41:02.345 15207-15257/com.example.teorialearning V/FA: Activity paused, time: 15824705
2021-03-30 03:41:02.389 15207-15207/com.example.teorialearning E/zzf: Failed to get reCAPTCHA token with error [There was an error while trying to get your package certificate hash.]- calling backend without app verification
2021-03-30 03:41:02.391 15207-15257/com.example.teorialearning V/FA: Activity resumed, time: 15824751
2021-03-30 03:41:02.395 15207-15245/com.example.teorialearning W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-30 03:41:02.641 15207-15207/com.example.teorialearning D/MAIN_TAG: onCodeSent:ALiwoWIdFZrl9ResXiUM94aPJW-csmRjdDOqoa9DTOkNQbv2Vf8YN7X6mvBwXgg9MJxEnFUVoE2rWAP2JzpT8QdBcRK2kIi82e_uO3pXW_rC5CZqWgJaqYqPO6nMOxiavmaJELnkSRtTXo6HoYoEY2_CmtVplEbz2Q
2021-03-30 03:41:02.644 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:02.677 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:02.739 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:04.679 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:04.789 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:07.416 15207-15257/com.example.teorialearning V/FA: Inactivity, disconnecting from the service
2021-03-30 03:41:08.627 15207-15245/com.example.teorialearning W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-30 03:41:08.668 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.685 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.691 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.696 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.755 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:08.936 15207-15245/com.example.teorialearning W/System: Ignoring header X-Firebase-Locale because its value was null.
2021-03-30 03:41:09.147 15207-15245/com.example.teorialearning D/FirebaseAuth: Notifying id token listeners about user ( QgYB9guxYgT2AQbr8u9CVrGnELw2 ).
2021-03-30 03:41:09.149 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.178 15207-15257/com.example.teorialearning V/FA: Recording user engagement, ms: 6787
2021-03-30 03:41:09.180 15207-15257/com.example.teorialearning V/FA: Connecting to remote service
2021-03-30 03:41:09.181 15207-15257/com.example.teorialearning V/FA: Activity paused, time: 15831539
2021-03-30 03:41:09.189 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.193 15207-15257/com.example.teorialearning V/FA: Connection attempt already in progress
2021-03-30 03:41:09.212 15207-15225/com.example.teorialearning V/FA: onActivityCreated
2021-03-30 03:41:09.229 15207-15257/com.example.teorialearning V/FA: Activity resumed, time: 15831590
2021-03-30 03:41:09.233 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.243 15207-15257/com.example.teorialearning V/FA: Connection attempt already in progress
2021-03-30 03:41:09.244 15207-15257/com.example.teorialearning V/FA: Connection attempt already in progress
2021-03-30 03:41:09.295 15207-15257/com.example.teorialearning D/FA: Connected to remote service
2021-03-30 03:41:09.296 15207-15257/com.example.teorialearning V/FA: Processing queued up service tasks: 4
2021-03-30 03:41:09.298 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:09.329 15207-15207/com.example.teorialearning W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
2021-03-30 03:41:09.330 15207-15207/com.example.teorialearning W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
2021-03-30 03:41:11.206 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:13.170 15207-15333/com.example.teorialearning D/EGL_emulation: eglMakeCurrent: 0xae4856c0: ver 3 1 (tinfo 0xae483990)
2021-03-30 03:41:14.310 15207-15257/com.example.teorialearning V/FA: Inactivity, disconnecting from the service
2021-03-30 03:42:02.393 15207-15348/com.example.teorialearning W/FirebaseAuth: [SmsRetrieverHelper] Timed out waiting for SMS.
P.S: I'm using Android studio
I could resolve this issue by changing my device's internet connection network. The app won't work on mobile data, but it worked on the WIFI of some other device.
The reason behind the problem isn't clear yet.
Reference answer -> https://stackoverflow.com/a/51122769/13546426
I am unable to write any data to my firebase database, however it is connected. My rules of both read and write are set to true, and I added the required SDK's but I still cannot add data.
Button RegisterBttn;
EditText userEmail, userPassword, userName;
//Firebase setup
FirebaseDatabase mydatabase;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_page);
RegisterBttn = (Button) findViewById(R.id.registerBttn);
//Firebase
mydatabase = FirebaseDatabase.getInstance();
users = mydatabase.getReference("Users");
userEmail = (EditText) findViewById(R.id.emailRegisterText);
userPassword = (EditText) findViewById(R.id.passwordRegisterText);
userName = (EditText) findViewById(R.id.nameRegisterText);
RegisterBttn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
final User user = new User(userName.getText().toString(),
userPassword.getText().toString(),
userEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists()) {
Toast.makeText(RegisterPage.this, "The Username already exists", Toast.LENGTH_SHORT).show();
}
else{
users.child(user.getUserName()).setValue(user);
// Log.i("Info", "Button Pressed");
Toast.makeText(RegisterPage.this, "Registered successfully", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Toast.makeText(RegisterPage.this, "Error registering", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
I have a seperate class for "User", containing username, pass and email.
I am using Realtime DB. The rules are:
{
"rules": {
".read": true,
".write": true
}
}
Here is the Logcat:
2020-04-11 23:30:54.483 25114-25114/? I/xample.fitnote: Not late-enabling -Xcheck:jni (already on)
2020-04-11 23:30:54.563 25114-25114/? E/xample.fitnote: Unknown bits set in runtime_flags: 0x8000
2020-04-11 23:30:54.571 25114-25114/? W/xample.fitnote: Unexpected CPU variant for X86 using defaults: x86
2020-04-11 23:30:55.411 25114-25114/com.example.fitnotes V/FA: Registered activity lifecycle callback
2020-04-11 23:30:55.412 25114-25114/com.example.fitnotes I/FirebaseInitProvider: FirebaseApp initialization successful
2020-04-11 23:30:55.440 25114-25114/com.example.fitnotes W/RenderThread: type=1400 audit(0.0:124): avc: denied { write } for name="property_service" dev="tmpfs" ino=620 scontext=u:r:untrusted_app:s0:c134,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0
2020-04-11 23:30:55.456 25114-25156/com.example.fitnotes D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
2020-04-11 23:30:55.456 25114-25156/com.example.fitnotes W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
2020-04-11 23:30:55.669 25114-25156/com.example.fitnotes D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2020-04-11 23:30:55.694 25114-25156/com.example.fitnotes D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2020-04-11 23:30:55.696 25114-25156/com.example.fitnotes D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2020-04-11 23:30:55.700 25114-25114/com.example.fitnotes V/FA: onActivityCreated
2020-04-11 23:30:55.806 25114-25114/com.example.fitnotes W/xample.fitnote: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-04-11 23:30:55.806 25114-25114/com.example.fitnotes W/xample.fitnote: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-04-11 23:30:55.945 25114-25167/com.example.fitnotes D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-04-11 23:30:56.021 25114-25153/com.example.fitnotes W/xample.fitnote: Verification of java.lang.Long com.google.android.gms.measurement.internal.zzap.zzbz() took 116.979ms
2020-04-11 23:30:56.201 25114-25154/com.example.fitnotes D/HostConnection: HostConnection::get() New Host Connection established 0xdbf3f320, tid 25154
2020-04-11 23:30:56.209 25114-25154/com.example.fitnotes D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
2020-04-11 23:30:56.225 25114-25154/com.example.fitnotes W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-04-11 23:30:56.227 25114-25154/com.example.fitnotes D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
2020-04-11 23:30:56.227 25114-25154/com.example.fitnotes D/EGL_emulation: eglCreateContext: 0xdbf1a120: maj 3 min 0 rcv 3
2020-04-11 23:30:56.229 25114-25154/com.example.fitnotes D/EGL_emulation: eglMakeCurrent: 0xdbf1a120: ver 3 0 (tinfo 0xdbf0f1a0)
2020-04-11 23:30:56.253 25114-25154/com.example.fitnotes W/Gralloc3: mapper 3.x is not supported
2020-04-11 23:30:56.266 25114-25154/com.example.fitnotes D/HostConnection: createUnique: call
2020-04-11 23:30:56.267 25114-25154/com.example.fitnotes D/HostConnection: HostConnection::get() New Host Connection established 0xdbf3f460, tid 25154
2020-04-11 23:30:56.267 25114-25154/com.example.fitnotes D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
2020-04-11 23:30:56.268 25114-25154/com.example.fitnotes D/eglCodecCommon: allocate: Ask for block of size 0x1000
2020-04-11 23:30:56.268 25114-25154/com.example.fitnotes D/eglCodecCommon: allocate: ioctl allocate returned offset 0x3ffff6000 size 0x2000
2020-04-11 23:30:56.294 25114-25154/com.example.fitnotes D/EGL_emulation: eglMakeCurrent: 0xdbf1a120: ver 3 0 (tinfo 0xdbf0f1a0)
2020-04-11 23:30:56.313 25114-25153/com.example.fitnotes V/FA: App measurement collection enabled
2020-04-11 23:30:56.314 25114-25153/com.example.fitnotes V/FA: App measurement enabled for app package, google app id: com.example.fitnotes, 1:247538218926:android:4af44b308740275bc97a3f
2020-04-11 23:30:56.323 25114-25153/com.example.fitnotes I/FA: App measurement initialized, version: 21028
2020-04-11 23:30:56.323 25114-25153/com.example.fitnotes I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
2020-04-11 23:30:56.324 25114-25153/com.example.fitnotes I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.fitnotes
2020-04-11 23:30:56.324 25114-25153/com.example.fitnotes D/FA: Debug-level message logging enabled
2020-04-11 23:30:56.328 25114-25154/com.example.fitnotes D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 1 0
2020-04-11 23:30:56.675 25114-25125/com.example.fitnotes I/xample.fitnote: Background concurrent copying GC freed 12091(2542KB) AllocSpace objects, 9(244KB) LOS objects, 49% free, 1893KB/3787KB, paused 11.909ms total 108.785ms
2020-04-11 23:30:56.824 25114-25153/com.example.fitnotes V/FA: Connecting to remote service
2020-04-11 23:30:56.864 25114-25153/com.example.fitnotes V/FA: Connection attempt already in progress
2020-04-11 23:30:56.868 25114-25153/com.example.fitnotes V/FA: Activity resumed, time: 23076629
2020-04-11 23:30:56.881 25114-25153/com.example.fitnotes I/FA: Tag Manager is not found and thus will not be used
2020-04-11 23:30:56.919 25114-25153/com.example.fitnotes V/FA: Connection attempt already in progress
2020-04-11 23:30:56.920 25114-25153/com.example.fitnotes V/FA: Connection attempt already in progress
2020-04-11 23:30:56.920 25114-25153/com.example.fitnotes D/FA: Connected to remote service
2020-04-11 23:30:56.921 25114-25153/com.example.fitnotes V/FA: Processing queued up service tasks: 4
2020-04-11 23:31:00.791 25114-25114/com.example.fitnotes W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#1e91d36
2020-04-11 23:31:00.799 25114-25153/com.example.fitnotes V/FA: Recording user engagement, ms: 4674
2020-04-11 23:31:00.815 25114-25114/com.example.fitnotes V/FA: onActivityCreated
2020-04-11 23:31:00.928 25114-25153/com.example.fitnotes V/FA: Activity paused, time: 23081303
2020-04-11 23:31:01.142 25114-25154/com.example.fitnotes D/EGL_emulation: eglMakeCurrent: 0xdbf1a120: ver 3 0 (tinfo 0xdbf0f1a0)
2020-04-11 23:31:01.170 25114-25154/com.example.fitnotes D/EGL_emulation: eglMakeCurrent: 0xdbf1a120: ver 3 0 (tinfo 0xdbf0f1a0)
2020-04-11 23:31:01.209 25114-25154/com.example.fitnotes D/EGL_emulation: eglMakeCurrent: 0xdbf1a120: ver 3 0 (tinfo 0xdbf0f1a0)
2020-04-11 23:31:01.271 25114-25153/com.example.fitnotes V/FA: Activity resumed, time: 23081552
2020-04-11 23:31:03.148 25114-25114/com.example.fitnotes I/AssistStructure: Flattened final assist data: 3084 bytes, containing 1 windows, 18 views
2020-04-11 23:31:06.509 25114-25153/com.example.fitnotes V/FA: Inactivity, disconnecting from the service
2020-04-11 23:31:10.941 25114-25114/com.example.fitnotes I/AssistStructure: Flattened final assist data: 3132 bytes, containing 1 windows, 18 views
2020-04-11 23:31:14.486 25114-25114/com.example.fitnotes I/Info: Button Pressed
2020-04-11 23:31:14.486 25114-25114/com.example.fitnotes I/Info: uu
I have a phonegap hybrid app with Facebook connect plugin. First time when I login then the FB login works but after I logout and then again try to login via Facebook then the app crashes with the following Logcat results :
Plugin URL :
https://github.com/jeduan/cordova-plugin-facebook4
06-18 21:31:50.071 3129-3219/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9b2370a0
06-18 21:31:50.096 3129-3129/? I/Choreographer: Skipped 39 frames! The application may be doing too much work on its main thread.
06-18 21:31:50.104 3129-3234/? D/EGL_emulation: eglMakeCurrent: 0x9e677300: ver 2 0 (tinfo 0xaa366e80)
06-18 21:31:50.356 3129-3129/? D/CordovaActivity: Incoming Result. Request code = 64206
06-18 21:31:50.356 3129-3129/? D/CordovaInterfaceImpl: Sending activity result to plugin
06-18 21:31:50.356 3129-3129/? D/ConnectPlugin: activity result in plugin: requestCode(64206), resultCode(-1)
06-18 21:31:50.372 3129-3129/? D/com.facebook.FacebookSdk: getGraphApiVersion: v3.0
06-18 21:31:50.372 3129-3129/? D/com.facebook.FacebookSdk: getGraphApiVersion: v3.0
06-18 21:31:50.378 3129-3129/? D/CordovaActivity: Resumed the activity.
06-18 21:31:50.379 3129-3129/? W/com.facebook.appevents.AppEventsLogger: activateApp events are being logged automatically. There's no need to call activateApp explicitly, this is safe to remove.
06-18 21:31:50.551 3129-3219/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x98eed520
06-18 21:31:51.043 3129-3129/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-18 21:31:51.044 3129-3129/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sqlchild.app1, PID: 3129
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(int)' on a null object reference
at libcore.net.UriCodec.decode(UriCodec.java:153)
at java.net.URLDecoder.decode(URLDecoder.java:60)
at org.apache.cordova.facebook.ConnectPlugin.makeGraphCall(ConnectPlugin.java:751)
at org.apache.cordova.facebook.ConnectPlugin.access$200(ConnectPlugin.java:55)
at org.apache.cordova.facebook.ConnectPlugin$2$1.onCompleted(ConnectPlugin.java:111)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:301)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1380)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
06-18 21:31:51.052 1667-2063/? W/ActivityManager: Force finishing activity com.sqlchild.app1/.MainActivity
06-18 21:31:51.067 1259-1321/? D/gralloc_ranchu: gralloc_alloc: Creating ashmem region of size 589824
[ 06-18 21:31:51.097 1667: 2063 D/ ]
HostConnection::get() New Host Connection established 0x9aa0cc00, tid 2063
[ 06-18 21:31:51.099 1667: 2063 W/ ]
Unrecognized GLES max version string in extensions: ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1
06-18 21:31:51.113 1259-1259/? E/EGL_emulation: tid 1259: eglCreateSyncKHR(1881): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-18 21:31:51.199 1667-1667/? W/art: Long monitor contention event with owner method=void com.android.server.am.ActivityManagerService.crashApplication(com.android.server.am.ProcessRecord, android.app.ApplicationErrorReport$CrashInfo) from ActivityManagerService.java:12502 waiters=0 for 133ms
06-18 21:31:51.289 1667-1677/? I/art: Background partial concurrent mark sweep GC freed 36018(2MB) AllocSpace objects, 1(20KB) LOS objects, 33% free, 7MB/11MB, paused 3.358ms total 105.317ms
06-18 21:31:51.381 1667-1729/? I/OpenGLRenderer: Initialized EGL, version 1.4
06-18 21:31:51.390 1667-1729/? D/EGL_emulation: eglCreateContext: 0xa07fc120: maj 2 min 0 rcv 2
06-18 21:31:51.414 1667-1729/? D/EGL_emulation: eglMakeCurrent: 0xa07fc120: ver 2 0 (tinfo 0xa0ea42f0)
06-18 21:31:51.484 1667-1729/? D/EGL_emulation: eglMakeCurrent: 0xa07fc120: ver 2 0 (tinfo 0xa0ea42f0)
06-18 21:31:51.691 1667-3205/? I/AccountManagerService: getTypesVisibleToCaller: isPermitted? true
06-18 21:31:51.698 1667-1683/? W/ActivityManager: Activity pause timeout for ActivityRecord{21fdafb u0 com.sqlchild.app1/.MainActivity t8 f}
06-18 21:31:51.877 1667-3206/? W/art: Long monitor contention event with owner method=void com.android.server.am.ActivityStack$ActivityStackHandler.handleMessage(android.os.Message) from ActivityStack.java:283 waiters=0 for 175ms
06-18 21:31:51.896 1667-1683/? I/ActivityManager: Killing 2545:com.android.keychain/1000 (adj 15): empty #17
06-18 21:31:52.070 2029-2239/? D/EGL_emulation: eglMakeCurrent: 0xae594600: ver 2 0 (tinfo 0xae5924b0)
06-18 21:31:59.062 3129-3129/? I/Process: Sending signal. PID: 3129 SIG: 9
06-18 21:31:59.075 1667-1729/? D/EGL_emulation: eglMakeCurrent: 0xa07fc120: ver 2 0 (tinfo 0xa0ea42f0)
06-18 21:31:59.079 1667-1729/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9e8d1360
06-18 21:31:59.128 1667-3206/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
06-18 21:31:59.130 1667-1721/? W/InputDispatcher: channel '7f56d84 com.sqlchild.app1/com.sqlchild.app1.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
06-18 21:31:59.130 1667-1721/? E/InputDispatcher: channel '7f56d84 com.sqlchild.app1/com.sqlchild.app1.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-18 21:31:59.129 1667-3206/? W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 3129 uid 10061
06-18 21:31:59.132 1667-1721/? W/InputDispatcher: channel 'e76402c com.sqlchild.app1/com.facebook.FacebookActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
06-18 21:31:59.133 1667-1721/? E/InputDispatcher: channel 'e76402c com.sqlchild.app1/com.facebook.FacebookActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-18 21:31:59.153 1667-3206/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
06-18 21:31:59.168 1667-1680/? I/WindowState: WIN DEATH: Window{e76402c u0 com.sqlchild.app1/com.facebook.FacebookActivity}
06-18 21:31:59.169 1667-1680/? W/InputDispatcher: Attempted to unregister already unregistered input channel 'e76402c com.sqlchild.app1/com.facebook.FacebookActivity (server)'
06-18 21:31:59.174 1667-2280/? D/GraphicsStats: Buffer count: 3
06-18 21:31:59.207 1667-1681/? I/ActivityManager: Process com.sqlchild.app1 (pid 3129) has died
06-18 21:31:59.257 1667-3110/? I/WindowState: WIN DEATH: Window{7f56d84 u0 com.sqlchild.app1/com.sqlchild.app1.MainActivity}
06-18 21:31:59.257 1667-3110/? W/InputDispatcher: Attempted to unregister already unregistered input channel '7f56d84 com.sqlchild.app1/com.sqlchild.app1.MainActivity (server)'
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am executing a very basic task of opening another activity using a button. The code seems to be error-free but the app crashes without even showing the main activity. This happens on both the emulator as well as my device.
When the app has no function, i.e. when the app has just buttons which do nothing, the app works fine. But if I try to make them do anything(intent to open another activity, or to play with their visibility) the app crashes.
The logcat is as follows:
11-12 13:55:56.627 2962-2962/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
11-12 13:55:56.628 2962-2962/? D/AndroidRuntime: CheckJNI is ON
11-12 13:55:56.672 2962-2962/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
11-12 13:55:56.754 2962-2962/? E/memtrack: Couldn't load memtrack module (No such file or directory)
11-12 13:55:56.754 2962-2962/? E/android.os.Debug: failed to load memtrack module: -2
11-12 13:55:56.755 2962-2962/? I/Radio-JNI: register_android_hardware_Radio DONE
11-12 13:55:56.761 2962-2962/? D/AndroidRuntime: Calling main entry com.android.commands.pm.Pm
11-12 13:55:56.772 2962-2962/? I/art: System.exit called, status: 0
11-12 13:55:56.772 2962-2962/? I/AndroidRuntime: VM exiting with result code 0.
11-12 13:55:57.068 2977-2977/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
11-12 13:55:57.069 2977-2977/? D/AndroidRuntime: CheckJNI is ON
11-12 13:55:57.129 2977-2977/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
11-12 13:55:57.199 2977-2977/? E/memtrack: Couldn't load memtrack module (No such file or directory)
11-12 13:55:57.199 2977-2977/? E/android.os.Debug: failed to load memtrack module: -2
11-12 13:55:57.200 2977-2977/? I/Radio-JNI: register_android_hardware_Radio DONE
11-12 13:55:57.205 2977-2977/? D/AndroidRuntime: Calling main entry com.android.commands.pm.Pm
11-12 13:55:57.216 2977-2977/? I/art: System.exit called, status: 0
11-12 13:55:57.220 2977-2977/? I/AndroidRuntime: VM exiting with result code 0.
11-12 13:55:59.484 2987-2987/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
11-12 13:55:59.487 2987-2987/? D/AndroidRuntime: CheckJNI is ON
11-12 13:55:59.522 2987-2987/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
11-12 13:55:59.602 2987-2987/? E/memtrack: Couldn't load memtrack module (No such file or directory)
11-12 13:55:59.602 2987-2987/? E/android.os.Debug: failed to load memtrack module: -2
11-12 13:55:59.603 2987-2987/? I/Radio-JNI: register_android_hardware_Radio DONE
11-12 13:55:59.615 2987-2987/? D/AndroidRuntime: Calling main entry com.android.commands.wm.Wm
11-12 13:55:59.643 2987-2987/? D/AndroidRuntime: Shutting down VM
11-12 13:56:01.407 2999-2999/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
11-12 13:56:01.408 2999-2999/? D/AndroidRuntime: CheckJNI is ON
11-12 13:56:01.465 2999-2999/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
11-12 13:56:01.542 2999-2999/? E/memtrack: Couldn't load memtrack module (No such file or directory)
11-12 13:56:01.542 2999-2999/? E/android.os.Debug: failed to load memtrack module: -2
11-12 13:56:01.543 2999-2999/? I/Radio-JNI: register_android_hardware_Radio DONE
11-12 13:56:01.553 2999-2999/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am
--------- beginning of system
11-12 13:56:01.562 1585-1920/system_process I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.dell.crash/.MainActivity} from uid 0 on display 0
11-12 13:56:01.579 2147-2341/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.speech.audio.u#20f33e2
11-12 13:56:01.605 3007-3007/? I/art: Not late-enabling -Xcheck:jni (already on)
11-12 13:56:01.606 2147-2347/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Stopping hotword detection.
11-12 13:56:01.606 2147-2699/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Hotword detection finished
11-12 13:56:01.610 1585-1598/system_process I/ActivityManager: Start proc 3007:com.example.dell.crash/u0a64 for activity com.example.dell.crash/.MainActivity
11-12 13:56:01.604 2999-2999/? D/AndroidRuntime: Shutting down VM
[ 11-12 13:56:01.697 1585: 1608 D/ ]
HostConnection::get() New Host Connection established 0x7f8480e69e40, tid 1608
11-12 13:56:01.728 3007-3007/com.example.dell.crash W/System: ClassLoader referenced unknown path: /data/app/com.example.dell.crash-1/lib/x86_64
11-12 13:56:01.729 3007-3007/com.example.dell.crash I/InstantRun: Instant Run Runtime started. Android package is com.example.dell.crash, real application class is null.
11-12 13:56:02.906 1891-2316/com.google.android.googlequicksearchbox E/Surface: getSlotFromBufferLocked: unknown buffer: 0xe9e5e990
11-12 13:56:03.510 3007-3007/com.example.dell.crash W/System: ClassLoader referenced unknown path: /data/app/com.example.dell.crash-1/lib/x86_64
11-12 13:56:03.707 3007-3007/com.example.dell.crash D/AndroidRuntime: Shutting down VM
--------- beginning of crash
11-12 13:56:03.707 3007-3007/com.example.dell.crash E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell.crash, PID: 3007
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.crash/com.example.dell.crash.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.dell.crash.MainActivity.<init>(MainActivity.java:10)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)
11-12 13:56:03.708 1585-2055/system_process W/ActivityManager: Force finishing activity com.example.dell.crash/.MainActivity
11-12 13:56:04.016 1585-2055/system_process I/WindowManager: Screenshot max retries 4 of Token{9795bf6 ActivityRecord{989c091 u0 com.example.dell.crash/.MainActivity t51 f}} appWin=Window{a3bf3ce u0 Starting com.example.dell.crash} drawState=4
11-12 13:56:04.116 1585-2485/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
11-12 13:56:04.518 1585-1601/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{989c091 u0 com.example.dell.crash/.MainActivity t51 f}
11-12 13:56:04.550 2328-2336/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/networkstatistics.sqlite' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
11-12 13:56:04.550 2328-2336/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/metrics.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
11-12 13:56:04.551 2328-2336/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/help_responses.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
11-12 13:56:04.572 2328-2336/com.google.android.gms W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
11-12 13:56:04.860 1585-1602/system_process I/Choreographer: Skipped 35 frames! The application may be doing too much work on its main thread.
11-12 13:56:04.925 2147-3076/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
11-12 13:56:04.943 2147-3078/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.speech.audio.u#76753fd
11-12 13:56:04.955 1585-1599/system_process I/ActivityManager: Killing 2527:com.android.settings/1000 (adj 15): empty #17
11-12 13:56:04.965 1202-2042/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
11-12 13:56:04.969 1202-3080/? I/AudioFlinger: AudioFlinger's thread 0xf3b80000 ready to run
11-12 13:56:04.988 2147-3078/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.speech.audio.u#76753fd
11-12 13:56:04.991 2147-2341/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.speech.audio.u#76753fd
11-12 13:56:04.992 2147-3078/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error -4 during AudioRecord native read
11-12 13:56:05.009 2147-2347/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Stopping hotword detection.
11-12 13:56:05.010 2147-3076/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Hotword detection finished
11-12 13:56:05.140 1585-1599/system_process I/ActivityManager: Killing 2649:com.android.dialer/u0a4 (adj 15): empty #17
11-12 13:56:05.395 1891-2316/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: em, destroying layer...
11-12 13:56:05.447 1585-1608/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
11-12 13:56:05.466 2328-2472/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true
11-12 13:56:05.486 2328-2504/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true
11-12 13:56:05.499 1585-1920/system_process I/ActivityManager: Killing 2670:com.android.managedprovisioning/u0a8 (adj 15): empty #17
11-12 13:56:15.034 1585-1601/system_process W/ActivityManager: Activity destroy timeout for ActivityRecord{989c091 u0 com.example.dell.crash/.MainActivity t51 f}
11-12 13:56:15.075 2147-3230/com.google.android.googlequicksearchbox:search W/CronetSyncConnectionRcs: Upload content type not set.
11-12 13:56:17.062 3007-3007/com.example.dell.crash I/Process: Sending signal. PID: 3007 SIG: 9
11-12 13:56:17.093 1585-2485/system_process E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f849297e160
11-12 13:56:17.101 1585-2485/system_process D/OpenGLRenderer: endAllStagingAnimators on 0x7f84835bfc00 (RippleDrawable) with handle 0x7f847ee9ee60
11-12 13:56:17.131 1585-1920/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#9d97b24 attribute=null, token = android.os.BinderProxy#32922a9
11-12 13:56:17.165 1585-1920/system_process I/ActivityManager: Process com.example.dell.crash (pid 3007) has died
11-12 13:56:17.367 1585-1608/system_process W/AppOps: Finishing op nesting under-run: uid 1000 pkg android code 24 time=0 duration=0 nesting=0
11-12 13:56:17.409 2147-3268/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
11-12 13:56:17.413 2147-3269/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.speech.audio.u#898b349
11-12 13:56:17.423 1202-1546/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
11-12 13:56:17.444 1202-3273/? I/AudioFlinger: AudioFlinger's thread 0xf3b80000 ready to run
11-12 13:56:17.449 2147-2157/com.google.android.googlequicksearchbox:search I/art: Background sticky concurrent mark sweep GC freed 1466(93KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 4MB/4MB, paused 25.294ms total 31.038ms
11-12 13:56:17.456 2147-3269/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.speech.audio.u#898b349
11-12 13:56:17.493 2147-2147/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady
11-12 13:56:17.504 2328-3272/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated.
11-12 13:56:17.564 2328-2472/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true
11-12 13:56:17.571 2328-2472/com.google.android.gms I/Icing: Usage reports 0 indexed 0 rejected 0 imm upload true
11-12 13:56:18.155 1202-1544/? W/AudioFlinger: write blocked for 408 msecs, 4 delayed writes, thread 0xf4500000
The .java file has the following block:
public class MainActivity extends AppCompatActivity {
Button btn1 = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
}
The XML file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dell.crash.MainActivity">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp"
android:id="#+id/button" />
</RelativeLayout>
I am using Android Studio 2.2.2
After
setContentView(R.layout.activity_main);
Add call like this
Button button = (Button) findViewById(R.id.button);
issue was you didn't created reference for button.
put Button btn1 = (Button) findViewById(R.id.button); in oncreate method.
The reason is you try add an event to your button but didn't show the reference id inside oncreate from where every app start its activity.
You should always instantiate button inside onCreate(). So your code should be like
public class MainActivity extends AppCompatActivity {
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
}
If you init your btn1 variable in declarations section, it will run before the setContextView(...) function call. Put btn1 initialization after setContextView(...)!
public class MainActivity extends AppCompatActivity {
private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = Button.class.cast(findViewById(R.id.button));
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
}