App crashing after trying to enter fragment [duplicate] - java

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/

Related

Android chat app keeps on crashing when I run it

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);
}
}

Android java won't run [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I'm studying Android java, and I have this error and can't run it.
Could you help me fixing this error? What is the problem?
Is it related to the error that I can't make a onClickListener() lambda expression? It gives me error and I can't import. So I tried making new View.OnclickListener() and its color is grey.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 9974
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: 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:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
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:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
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.myapplication.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
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:2210) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7839) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I/Process: Sending signal. PID: 9974 SIG: 9
And this is my mainActivity.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
TextView txtViewResults;
EditText editTextInputWt;
Button btnConvertWt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setLogo(R.mipmap.ic_launcher_weight_round);
actionBar.setTitle(R.string.txtTitle);
btnConvertWt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1){
Toast.makeText(MainActivity.this, "Please select conversion type", Toast.LENGTH_SHORT).show();
} else if (editTextInputWt.getText().toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please select baggage weight", Toast.LENGTH_SHORT).show();
} else {
double inputWt, outputWt;
try{
inputWt = Double.parseDouble(editTextInputWt.getText().toString());
if (inputWt<0){
Toast.makeText(MainActivity.this, "Baggage weight can't be negative.", Toast.LENGTH_SHORT).show();
} else if (radioGroup.getCheckedRadioButtonId() == R.id.radBtnKgsToLbs){
if (inputWt > 500){
Toast.makeText(MainActivity.this, "Input bg wt can't be greater than 500Kilos", Toast.LENGTH_SHORT).show();
} else {
outputWt = inputWt*2.2;
txtViewResults.setText(String.format("Converted wt: %.2f Lbs", outputWt));
}
} else if (radioGroup.getCheckedRadioButtonId() == R.id.radBtnLbsToKgs){
if (inputWt > 1000){
Toast.makeText(MainActivity.this, "Input bg wt can't be greater than 1000 pounds", Toast.LENGTH_SHORT).show();
} else {
outputWt = inputWt/2.2;
txtViewResults.setText(String.format("Converted wt: %.2f Kgs", outputWt));
}
}
} catch (Exception ex){
ex.printStackTrace();
}
}
}
});
}
}
This is due to you haven't initialised your views and as of this stage they are null and you can't invoke method on null object in java which you can see in your error.
so for this you have to initalise your variable you can do like following
findViewById()
View Binding
Data Binding
Creating view programmatically
as you have used layout file you can do findViewById() as following
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
TextView txtViewResults;
EditText editTextInputWt;
Button btnConvertWt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
radioGroup = findViewById(R.id.my_radio_group);
btnConvertWt = findViewById(R.id.my_button); // the id's are same as defined in your layout file
....
btnConvertWt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
}
});
}
}

Android: Unable to pause activity : java.lang.NullPointerException: null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Everything works fine in my app but when I press the back button (I mean exit app) the app is crashing. And I don't know why? I tried a couple of solutions but nothing works. It's a sounds/ringtones application.
I am a newbie at Android and I need some advice like "delete this" / "add this"
Here my code
package com.app.trying;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.app.trying.tabs.Tab3;
import com.app.trying.tabs.Tab1;
import com.app.trying.tabs.Tab2;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public MediaPlayer mp;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Banner Ad
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
toolbarTabs();
sidebar();
externalStorageAccess();
}
// Creates sidebar and sets onClickListeners
public void sidebar(){
mNavigationView = (NavigationView) findViewById(R.id.navigationView);
mNavigationView.setItemIconTintList(null);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()){
case R.id.sounds:
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.app_name));
shareIntent.putExtra(Intent.EXTRA_TEXT, getText(R.string.share_text) + " " + getText(R.string.app_name) + "\n\n" + getText(R.string.playstore_link));
startActivity(Intent.createChooser(shareIntent, getText(R.string.share_via)));
break;
}
return false;
}
});
}
// Is listening which sound on Tab1 has been clicked
public void TabOneItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab1.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab2 has been clicked
public void TabTwoItemClicked(int position) {
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab2.soundfiles[position]);
mp.start();
}
// Is listening which sound on Tab3 has been clicked
public void TabThreeItemClicked ( int position){
cleanUpMediaPlayer();
mp=MediaPlayer.create(MainActivity.this, Tab3.soundfiles[position]);
mp.start();
}
// Cleans MediaPlayer
public void cleanUpMediaPlayer() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
// Access external storage
public void externalStorageAccess(){
final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/"+ getText(R.string.package_name) +"/files");
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w("error", "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
finish();
}
}
// Creates toolbar Tabs
public void toolbarTabs(){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
public void stopMediaPlayer()
{
mp.stop();
}
}
And this is my error logs.
2019-05-09 19:13:22.296 704-704/? E/cnss-daemon: Invalid mac address: 0x555555f110M
2019-05-09 19:13:32.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
2019-05-09 19:13:39.537 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:40.333 24095-24175/? E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2019-05-09 19:13:43.035 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:43.116 24095-24095/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.trying, PID: 24095
java.lang.RuntimeException: Unable to pause activity {com.app.trying/com.app.trying.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3735)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6111)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
at com.app.trying.MainActivity.stopMediaPlayer(MainActivity.java:155)
at com.app.trying.MainActivity.onPause(MainActivity.java:150)
at android.app.Activity.performPause(Activity.java:6917)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1323)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3724)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701) 
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675) 
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6111) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapAllocatedSize18887424
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapSize35651584
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, getNativeHeapFreeSize16764160
2019-05-09 19:13:51.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
How should I resolve this error? Any help would be great. Thanks.
Your MediaPlayer instance is null as shown in the stacktrace, so:
public void stopMediaPlayer()
{
if (mp != null) {
mp.stop();
}
}
It can happen that your MediaPlayer instance is never initialization. So you have to handle it.

App crashes after adding FirebaseAuth.getInstance

I had added firebase authentication yesterday and it was working fine but today after editing some files it is crashing.
App only crashes when I add "firebaseAuth =FirebaseAuth.getInstance()".
If I remove it then all things work fine but now I cannot add firebase.
SignUp.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class SignUp extends AppCompatActivity implements View.OnClickListener {
private TextView alreadyRegistered;
private EditText mEmailView;
private EditText mPasswordView;
private Button signup;
private FirebaseAuth firebaseAuth;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
progressDialog=new ProgressDialog(this);
mEmailView = (EditText) findViewById(R.id.email_signup);
mPasswordView = (EditText) findViewById(R.id.password_signup);
signup=(Button)findViewById(R.id.signup);
alreadyRegistered=(TextView)findViewById(R.id.already_registered);
// firebaseAuth =FirebaseAuth.getInstance();
//// if(firebaseAuth.getCurrentUser() != null){
//// //that means user is already logged in
//// //so close this activity
//// finish();
////
//// //and open profile activity
//// startActivity(new Intent(getApplicationContext(), Home.class));
//// }
alreadyRegistered.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void registerUser() {
//getting email and password from edit texts
String email = mEmailView.getText().toString().trim();
String password = mPasswordView.getText().toString().trim();
//checking if email and passwords are empty
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//display some message here
Toast.makeText(SignUp.this, "Successfully registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
} else {
//display some message here
Toast.makeText(SignUp.this, "Registration Error", Toast.LENGTH_LONG).show();
}
// progressDialog.dismiss();
}
});
}
#Override
public void onClick(View v) {
if(v==signup)
{
registerUser();
}
if(v==alreadyRegistered)
{
Intent intent = new Intent(SignUp.this,MainActivity.class);
startActivity(intent);
}
}
}
I tried debugging and it crashes when I run that particular line.
Crash Logs
2019-02-16 14:43:23.569 25053-25053/com.example.android.nirog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.nirog, PID: 25053
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.nirog/com.example.android.nirog.SignUp}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.android.nirog. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2949)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:200)
at android.app.ActivityThread.main(ActivityThread.java:6956)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:519)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.android.nirog. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##16.0.2:240)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source:1)
at com.example.android.nirog.SignUp.onCreate(SignUp.java:44)
at android.app.Activity.performCreate(Activity.java:7225)
at android.app.Activity.performCreate(Activity.java:7216)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:200) 
at android.app.ActivityThread.main(ActivityThread.java:6956) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:519) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836) 
2019-02-16 14:43:23.623 25053-25053/com.example.android.nirog I/Process: Sending signal. PID: 25053 SIG: 9
This is most helpful in android with fluuter and firebase
in app level build.gradle
defaultConfig {
minSdkVersion 23
}
in project level gradle.properties add
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
in build.gradle add
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.2.0'
}
you can skip that Kotlin plugin if you are not using Kotlin support
Dont forget to run flutter clean and then flutter pub upgrade
These changes helped me preventing my app crashes, It should help you too.
You have not initialised firebase. Add this in onCreate of your SignUp class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
FirebaseApp.initializeApp(Context)
Make sure to call FirebaseApp.initializeApp(Context) first in Android method added in MyApplication class in your project like :
override fun onCreate() {
super.onCreate()
{
FirebaseApp.initializeApp(Context);
}

SoundPool won't play a passed raw from an other Activity

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!

Categories