I have just begun writing some code for my Chat app after days of planning but the problem is that keeps on crashing right after the Gradle Build has finished and the app is installed on my device. I have created a button that is expected to open a new activity but instead of doing so it crashes. Everything works before I have written any code, the app opens and logcat doesn't show any errors. Here is the error:
2022-08-10 19:26:48.372 15348-15348/? E/e.myapplicatio: Unknown bits set in runtime_flags: 0x40000000
2022-08-10 19:26:48.391 15348-15348/? E/RefClass: java.lang.reflect.InvocationTargetException
2022-08-10 19:26:48.474 15348-15348/com.example.myapplication E/Perf: perftest packageName : com.example.myapplication App is allowed to use Hide APIs
2022-08-10 19:26:48.515 15348-15374/com.example.myapplication E/libEGL: Invalid file path for libcolorx-loader.so
2022-08-10 19:26:48.528 15348-15348/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 15348
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3887)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:263)
at android.app.ActivityThread.main(ActivityThread.java:8292)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:183)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.myapplication.MainActivity.<init>(MainActivity.java:12)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3616)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3887)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:263)
at android.app.ActivityThread.main(ActivityThread.java:8292)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
I tried following some other suggestions but they didn't work. Here's the snippet of my code:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public Button signUp = findViewById(R.id.signUpBtn);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity();
}
});
}
public void openActivity(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
You can not use findViewById() outside of onCreate() like this and if you really wanna do that, do it by creating a new method for setting up IDs and then add that method in onCreate().
this code will do the work now:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public Button signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signUp = findViewById(R.id.signUpBtn);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity();
}
});
}
public void openActivity(){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Related
I am very new to Android Studio and am trying to create a log in screen which then opens an inventory screen. The problem I am having is when I click Submit to the username and password, the app completely crashes. Right now, I am just working out how to organize the layout portion of things, but need to figure out how to get this transition to work. Any help would be great!
This is the main activity code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText username, password;
Button buttonLogIn, buttonRegister;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.newPassword);
buttonLogIn = (Button) findViewById(R.id.buttonLogIn);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(username.getText().toString().trim().length() <1 || password.getText().toString().trim().length() <1){
username.setError("You must enter a valid username and password");
}
else {
openInventory();
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openRegisterScreen();
}
});
}
public void openRegisterScreen() {
Intent intent = new Intent(this, RegisterScreen.class);
startActivity(intent);
}
public void openInventory() {
Intent intent = new Intent(this, InventoryScreen.class);
startActivity(intent);
}
}
This is the inventory screen code:
package com.example.cs360projectone;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class InventoryScreen extends AppCompatActivity {
Button buttonSMS, buttonSignOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_screen);
buttonSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
openSMSPermission();
}
});
}
public void openSMSPermission() {
Intent intent = new Intent(this, SMSPermissionScreen.class);
startActivity(intent);
}
}
This is the error from logcat when the button is pressed:
2022-08-03 16:54:09.037 8043-8043/com.example.cs360projectone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cs360projectone, PID: 8043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cs360projectone/com.example.cs360projectone.InventoryScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.cs360projectone.InventoryScreen.onCreate(InventoryScreen.java:18)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2022-08-03 16:54:09.062 8043-8043/com.example.cs360projectone I/Process: Sending signal. PID: 8043 SIG: 9
You need to get the SMS button in the InventoryScreen onCreate method the same way you did with the other buttons in MainActivity.
This means doing a
buttonSMS = (Button) findViewById(R.id.buttonSMS);
before setting up an onClickListener.
When starting my activity there is always an error message and the app does not open.
Error:
2022-05-11 23:18:12.470 17222-17222/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 17222
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.feuerwerkzndanlage.Biometric_Authentication}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8056)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:133)
at com.example.feuerwerkzndanlage.Biometric_Authentication.<init>(Biometric_Authentication.java:23)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3443)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8056)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Activity:
package com.example.feuerwerkzndanlage;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import java.util.concurrent.Executor;
public class Biometric_Authentication extends AppCompatActivity {
private TextView authStatusTv;
private BiometricPrompt biometricPrompt;
private BiometricPrompt.PromptInfo promptInfo;
Context context = getApplicationContext();
CharSequence error_txt = "Indentifizierung Fehlgeschlagen: ";
CharSequence suceed_txt = "Indentifizierung Erfolgreich";
CharSequence failed_txt = "Indentifizierung Fehlgeschlagen";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biometric_authentication);
authStatusTv = findViewById(R.id.authStatusTv);
Button btn_auth = findViewById(R.id.btn_auth);
Executor executor = ContextCompat.getMainExecutor(this);
biometricPrompt = new BiometricPrompt(Biometric_Authentication.this, executor, new BiometricPrompt.AuthenticationCallback() {
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
authStatusTv.setText("Indentifizierung Fehlgeschlagen: " + errString);
Toast.makeText(context, error_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
authStatusTv.setText("Indentifizierung Erfolgreich");
Toast.makeText(context, suceed_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
authStatusTv.setText("Indentifizierung Fehlgeschlagen");
Toast.makeText(context, failed_txt, duration).show();
}
});
promptInfo = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometrische Indentifizierung")
.setSubtitle("Login")
.setNegativeButtonText("Benutzer Passwort")
.build();
btn_auth.setOnClickListener(view -> biometricPrompt.authenticate(promptInfo));
}
}
Context context = getApplicationContext();
You can't do that at init time. You can't call any Context related functions, including getApplicationContect() until onCreate is called. This is because the framework hasn't fully initialized the activity before then. To make this work, you'd need to move this line into onCreate, and move any code that depends on this variable being set into onCreate or later as well.
I am learning how to develop for Android (and development in general). I am trying to create a Quiz App, so I can learn the basics.
While trying to use an Intent to go to another class with an extra variable on it, I found this problem (which I think is pretty usual): My app crashes when I go to the next Activity.
This is the code in the activity that gets the username ("usuario and nomeUsuario"):
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class HomeActivity extends AppCompatActivity {
public EditText usuario;
public EditText senha;
public Button botaoLogin;
public String nomeUsuario;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
botaoLogin = findViewById(R.id.botaoLogin);
senha = findViewById(R.id.senha);
usuario = findViewById(R.id.usuario);
nomeUsuario = usuario.getText().toString();
Log.d("nome de usuario", nomeUsuario);
botaoLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(HomeActivity.this, FirstQuestionActivity.class);
i.putExtra("nome", nomeUsuario);
startActivity(i);
}});
}
}
And this is the code on the SecondQuestionActivity:
package com.isa56.quiz2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class FirstQuestionActivity extends AppCompatActivity {
public Button prox1;
public Button respUm1;
public Button respUm2;
public TextView texto1;
public int pontuacao = 0;
Intent i = getIntent();
String nome = i.getStringExtra("nome");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstquestion);
prox1 = findViewById(R.id.prox1);
respUm1 = findViewById(R.id.botao1a);
respUm2 = findViewById(R.id.botao1b);
texto1 = findViewById(R.id.texto1);
respUm1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta errada!");
respUm1.setEnabled(false);
respUm2.setEnabled(false);
prox1.setEnabled(true);
}});
respUm2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
texto1.setText("Resposta certa!");
respUm2.setEnabled(false);
respUm1.setEnabled(false);
pontuacao += 1;
prox1.setEnabled(true);
}});
prox1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(FirstQuestionActivity.this, SecondQuestionActivity.class);
i.putExtra("pontos", pontuacao);
i.putExtra("nome", nome);
startActivity(i);
}
});
}
}
What is wrong with it? How can I prevent it?
Thank you!
P.S.: I am not used to forum or development in general, so I might have done this wrongly. I'm sorry.
Edit: Also, if anyone wanna take a look at the whole project, it's here.
Edit2: This is the Logcat output:
2020-11-13 21:05:18.531 7517-7517/com.isa56.quiz2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.isa56.quiz2, PID: 7517
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.isa56.quiz2/com.isa56.quiz2.FirstQuestionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
at com.isa56.quiz2.FirstQuestionActivity.<init>(FirstQuestionActivity.java:18)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Keep these lines inside onCreate() method.
Intent i = getIntent();
String nome = i.getStringExtra("nome");
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Hello my question is about my app is crash after I am trying to hit next fragment.
Code is compiling but i don't know how to solve this problem.
Something with onclicklistner.
I tried some solutions but didn't succeed.
This is my code:
ProfileFragment.java
package com.statusionew.statusio.fragments;
import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.statusionew.statusio.ForgetchangePasswordActivity; import com.statusionew.statusio.LoginActivity; import com.statusionew.statusio.R; import com.statusionew.statusio.MainActivity;
import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
public class ProfileFragment extends BaseFragment implements View.OnClickListener{
FirebaseAuth auth;
FirebaseUser user;
ProgressDialog PD;
#BindView(R.id.sign_out_button) Button btnSignOut;
#BindView(R.id.change_password_button) Button btnChangePass;
#BindView(R.id.change_email_button) Button btnChangeEmail;
#BindView(R.id.delete_user_button) Button btnDeleteUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_setting, container, false);
ButterKnife.bind(getActivity(), view);
((MainActivity) getActivity()).updateToolbarTitle("Profile");
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
PD = new ProgressDialog(getActivity());
PD.setMessage("Loading...");
PD.setCancelable(true);
PD.setCanceledOnTouchOutside(false);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.sign_out_button)
public void onClick(View view) {
auth.signOut();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
}
};
}
});
btnChangePass.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_password_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 1));
}
});
btnChangeEmail.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_email_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 2));
}
});
btnDeleteUser.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.delete_user_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 3));
}
});
}
#Override
public void onClick(View v) {
if (auth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
super.onResume();
} }
this the log that say 'Attempt to invoke virtual method'-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.statusionew.statusio, PID: 9206
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.statusionew.statusio.fragments.ProfileFragment.onCreate(ProfileFragment.java:65)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2339)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1109)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:996)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:99)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2364)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:781)
at com.statusionew.statusio.views.FragNavController.executePendingTransactions(FragNavController.java:631)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:142)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:158)
at com.statusionew.statusio.MainActivity.switchTab(MainActivity.java:149)
at com.statusionew.statusio.MainActivity.access$100(MainActivity.java:30)
at com.statusionew.statusio.MainActivity$1.onTabSelected(MainActivity.java:87)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Connected to process 10580 on device 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/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.statusionew.statusio-1/lib/x86
D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
V/FA: Registered activity lifecycle callback
I/FirebaseInitProvider: FirebaseApp initialization successful
I/InstantRun: starting instant run server: is main process
E/InstantRun: IO Error creating local socket at com.statusionew.statusio
java.io.IOException: Address already in use
at android.net.LocalSocketImpl.bindLocal(Native Method)
at android.net.LocalSocketImpl.bind(LocalSocketImpl.java:308)
at android.net.LocalServerSocket.<init>(LocalServerSocket.java:48)
at com.android.tools.ir.server.Server.<init>(Server.java:91)
at com.android.tools.ir.server.Server.create(Server.java:85)
at com.android.tools.ir.server.InstantRunContentProvider.onCreate(InstantRunContentProvider.java:49)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
It seems like you've got some misunderstandings about how Fragments and ButterKnife work.
OnCreate is called BEFORE onCreateView in a Fragment. So all your views are null when you're trying to access them in onCreate.
See Fragment Lifecycle:
https://www.tutorialspoint.com/android/images/fragment.jpg
OnCreate is not used that much in Fragments, onCreateView is used more.
Your ButterKnife bind code is also wrong. You're trying to bind the Activity to the views in the Fragment.
See ButterKnife documentation for correct usage: http://jakewharton.github.io/butterknife/
I have this problem I want to pass a raw from Activity 1 to be played in Activity 2
Here is my code
Activity 1
package com.ze.zeggar.tewt;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
int ThePlayedSound= R.raw.waterdrop;
Intent MyIntent= new Intent(this, MainActivity.class);
MyIntent.putExtra("key",ThePlayedSound);
startActivity(MyIntent);
}
}
Activity 2
package com.ze.zeggar.tewt;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
SoundPool Sound_Pool_thing;
int Click;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent MyIntent=getIntent();
int ThePlayedSound= MyIntent.getIntExtra("key", 0);
Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);
Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sound_Pool_thing.play(Click,1,1,1,0,1);
}
});
}
}
and when I try to open the app I got "Unfortunately , My_App has stopped"
The app crashes
and here's the new crash Log after suggestions:
06-06 10:49:09.069 3424-3424/com.ze.zeggar.tewt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ze.zeggar.tewt, PID: 3424
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ze.zeggar.tewt/com.ze.zeggar.tewt.MainActivity}:
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:1269)
at android.content.res.Resources.openRawResourceFd(Resources.java:1227)
at android.media.SoundPool$SoundPoolImpl.load(SoundPool.java:566)
at android.media.SoundPool.load(SoundPool.java:229)
at com.ze.zeggar.tewt.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Any idea ?
Ur getting resource not found exception since your not opening the raw type Resources properly
Try getting the raw audio file from resources like this:
int ThePlayedSound = this.getResources().getIdentifier("waterdrop", "raw", getPackageName());
Intent MyIntent= new Intent(this, MainActivity.class);
MyIntent.putExtra("key",ThePlayedSound);
startActivity(MyIntent);
What about using the MediaPlayer class?
Check this code below:
MainActivity class (or whatever class you want to start the new activity from)
Intent intent = new Intent(this,Main2Activity.class);
intent.putExtra("key",R.raw.waterdrop);
startActivity(intent);
Main2Activity (class that will play the audio)
public class Main2Activity extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitiy_main2);
int soundId = getIntent().getIntExtra("key",0);
final MediaPlayer mPlayer =new MediaPlayer();
mPlayer.setAudioSessionId(soundId);
mPlayer.setLooping(true);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.start();
}
});
}
}
This code worked for me.
If it says that that specific constructor doesnt work try the below one:
final MediaPlayer mPlayer =new MediaPlayer(this,soundId);
Hope it helps you out!