MPAndroidChart keeps throwing null error - java

I'm just trying this library out to see if it fits my needs and so far I have not been able to get it to work. Here is the code
package com.example.user.bottomnavigationbar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
PieChart pc;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
// case R.id.navigation_overview:
// Intent intentOverview = new Intent(MainActivity.this, activity_test.class);
// intentOverview.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// MainActivity.this.finish();
// startActivity(intentOverview);
// return true;
case R.id.navigation_expenses:
return true;
case R.id.navigation_reminder:
return true;
case R.id.navigation_income:
return true;
case R.id.navigation_login:
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
intentLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
MainActivity.this.finish();
startActivity(intentLogin);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
pc = findViewById(R.id.chart);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}
public void onBackPressed()
{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
And here is the error I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.bottomnavigationbar, PID: 4172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.bottomnavigationbar/com.example.user.bottomnavigationbar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setData(com.github.mikephil.charting.data.ChartData)' on a null object reference
at com.example.user.bottomnavigationbar.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I've searched for a bit and all I've found was that for others, they did not initialize the object hence it throws this error. Now someone did mention that it is possible to create the chart in code and then add it to the activity as the documentation's Getting Started page suggests but I have been unable to get it working. So what gives?
P.S Left in the code for navigation as I'm not sure if it might be the cause of the issue

You are first finding the view and then providing the content view to your activity replace with this code
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pc = findViewById(R.id.chart);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList <PieEntry> pieData = new ArrayList<>();
pieData.add(new PieEntry(10));
pieData.add(new PieEntry(20));
pieData.add(new PieEntry(30));
PieDataSet dataSet = new PieDataSet(pieData, "Survey Results");
PieData data = new PieData(dataSet);
pc.setData(data);
}

Related

My app crashed when clicking new dependency question. I don't know what is the error and how to solved it [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6969
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.login/com.example.login.NavigationDrawer}: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
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:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.navigation.NavigationView.getHeaderView(int)' on a null object reference
at com.example.login.ui.questionnaire.QuestionnaireFragment.onCreateView(QuestionnaireFragment.java:80)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2777)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3020)
at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:295)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:274)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:784)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:867)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:54)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:48)
E/AndroidRuntime: at com.example.login.NavigationDrawer.onCreate(NavigationDrawer.java:42)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
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:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873
Java Code
package com.example.login;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.login.databinding.ActivityNavigationDrawerBinding;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
public class NavigationDrawer extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityNavigationDrawerBinding binding;
private String username;
private EditText etUsername;
Pref pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = new Pref(getApplicationContext());
//get username from login page
username = pref.getUsername();
//System.out.println("username in 2nd "+username);
binding = ActivityNavigationDrawerBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(binding.navView);
setSupportActionBar(binding.appBarNavigationDrawer.toolbar);
binding.appBarNavigationDrawer.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_questionnaire, R.id.nav_submitsurvey, R.id.nav_responses, R.id.nav_imagecapture, R.id.nav_dashboard)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
//display welcome username
etUsername = findViewById(R.id.welcomeUsername);
etUsername.setText(username);
Button button_log_out = findViewById(R.id.button_log_out);
button_log_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutDialog();
}
});
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void logoutDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("LogOut Alert!");
alertDialog.setMessage("Are you sure want to LogOut this Application?");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pref.setLogin("no");
dialog.dismiss();
Intent intent = new Intent(NavigationDrawer.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
you have a NullPointerException. You should check whether the data you receive is full. For example
if(data != null){
.
.
.
...
}

Android application crashes in emulator with java code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
My android application crashes in emulator. The application did not open in emulator. I am working with java. It was working perfectly before i added the bottom navigation into my application. Please sort out my issue as i am new in this field. Here is the code of my main activity below.
package com.example.bottomnavigation;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import com.example.bottomnavigation.databinding.ActivityMainBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
ImageView picture, video, message, mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
binding.bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.first:
FragmentTransaction firsttrans = getSupportFragmentManager().beginTransaction();
firsttrans.replace(R.id.frame, new HomeFragment());
firsttrans.commit();
break;
case R.id.search:
FragmentTransaction searchtrans = getSupportFragmentManager().beginTransaction();
searchtrans.replace(R.id.frame, new SearchFragment());
searchtrans.commit();
break;
case R.id.exit:
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit")
.setIcon(R.drawable.exit)
.setMessage("Are you sure you want to exit")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).show();
}
return true;
}
});
picture = findViewById(R.id.arham);
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Pictures.class);
startActivity(intent);
}
});
}
}
Here is the logcat
2021-04-05 12:35:38.662 19375-19375/? E/ottomnavigatio: Unknown bits set in runtime_flags: 0x8000
2021-04-05 12:35:40.544 19375-19375/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bottomnavigation, PID: 19375
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bottomnavigation/com.example.bottomnavigation.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.bottomnavigation.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
The exception is being thrown because you are calling hide() on a null reference to an ActionBar. Assuming that this is the relevant code, it is occurring on this line:
getSupportActionBar().hide();
If you read the javadocs (here and here) for getSupportActionBar() you will see that it returns null if the activity doesn't have an action bar. That must be happening here.
(So why is your app trying to hide the activity bar when it doesn't have one??)
It would appear that the solution is to delete the offending line. Or if there are contexts in which your app might have an action bar, change it to:
ActionBar bar = getSupportActionBar();
if (bar != null) {
bar.hide();
}

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.

Launching activity from spinner crashes app

I cannot find the problem anywhere, the first activity works without a hitch, and the second (and all the others) are almost copies of it, just with different values and calculations, so they SHOULD be working
My first activity starts like this
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
....
....
private final String[] generations = {"Gen2", "Gen3", "Gen4", "Gen5", "Gen6", "Gen7"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Main);
Spinner spin = (Spinner) findViewById(R.id.genchoice);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, generations);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
The spinner code is
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case (1):
Intent intent2 = new Intent(this, gen2.class);
startActivity(intent2);
break;
case 2:
Intent intent3 = new Intent(this, Gen3.class);
startActivity(intent3);
break;
case 3:
Intent intent4 = new Intent(this, gen4.class);
startActivity(intent4);
break;
case 4:
Intent intent5 = new Intent(this, gen5.class);
startActivity(intent5);
break;
case 5:
Intent intent6 = new Intent(this, MainActivity.class);
startActivity(intent6);
break;
case 6:
Intent intent7 = new Intent(this, gen7.class);
startActivity(intent7);
break;
}
}
and my secong activity starts like this
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import java.text.DecimalFormat;
public class gen2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
....
.....
private final String[] generations = {"Gen2", "Gen3", "Gen4", "Gen5", "Gen6", "Gen7"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gen2);
Spinner spin = (Spinner) findViewById(R.id.genchoice);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, generations);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
errorlog
09-30 10:59:37.896 3646-3646/com.example.rune.shinycalculator
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rune.shinycalculator, PID: 3646
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.rune.shinycalculator/com.example.rune.shinycalculator.gen2}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
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 'void
android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)'
on a null object reference
at com.example.rune.shinycalculator.gen2.onCreate(gen2.java:27)
at android.app.Activity.performCreate(Activity.java:6285)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.access$900(ActivityThread.java:150) 
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)
09-30 10:59:39.823 3646-3646/com.example.rune.shinycalculator
I/Process: Sending signal. PID: 3646 SIG: 9
You should follow the Naming Convention. Class name should be CamelCase(start with Cpas).
gen.class should be Gen.class
Go through below link
http://www.oracle.com/technetwork/java/codeconventions-135099.html
Use
Intent intent2 = new Intent(MainActivity.this,Gen2.class);
startActivity(intent2);
When you are inside anonymous Class this refer to instances of that class . So Change "this" to "Mainactivity.this"
Intent intent2 = new Intent(MainActivity.this, gen2.class);
I think you are missing the Spinner in the layouts for the other activities (gen3, ...) but are still trying to set a listener for it and that's why you get the NPE.
=== Before stacktrace ===
You probably haven't added the other activities in the AndroidManifest.xml, like this
<activity android:name=".gen3"/>
<activity android:name=".gen4"/>
Remember to set the correct package for the class in android:name.
Also be careful with the uppercase/lowercase in the class name because it's case sensitive.

Application Closing When Calling Intent

I have 2 classes. I am calling an intent from my menu class, and when I call the intent to go to my MainActivity class, it gives me an error that says, Unfortunately, app name has stopped. I need help figuring out what is happening. I know it is because there is an error somewhere in MainActivity. I just need help finding it.
Here is MainActivity.java's code:
package com.arborhillsvet.arborhillsveterinarianclinic;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ViewAnimator;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "parse information", "parse information");
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
WebView appointWeb = (WebView) findViewById(R.id.appointments);
appointWeb.loadUrl("https://www.google.com");
WebSettings webSettings = appointWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
appointWeb.setWebViewClient(new WebViewClient());
WebView promosWeb = (WebView) findViewById(R.id.promos);
promosWeb.loadUrl("https://www.yahoo.com");
WebSettings webSettings2 = promosWeb.getSettings();
webSettings2.setJavaScriptEnabled(true);
promosWeb.setWebViewClient(new WebViewClient());
WebView infoWeb = (WebView) findViewById(R.id.info);
infoWeb.loadUrl("https://www.bing.com");
WebSettings webSettings3 = infoWeb.getSettings();
webSettings3.setJavaScriptEnabled(true);
infoWeb.setWebViewClient(new WebViewClient());
WebView medsWeb = (WebView) findViewById(R.id.medicines);
medsWeb.loadUrl("https://www.aol.com");
WebSettings webSettings4 = medsWeb.getSettings();
webSettings4.setJavaScriptEnabled(true);
medsWeb.setWebViewClient(new WebViewClient());
Button next = (Button) findViewById(R.id.next);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewAnimator anim = (ViewAnimator) findViewById(R.id.views);
anim.showNext();
}
};
next.setOnClickListener(listener);
Button prev = (Button) findViewById(R.id.prev);
View.OnClickListener listener2 = new View.OnClickListener() {
public void onClick(View view) {
ViewAnimator anim = (ViewAnimator) findViewById(R.id.views);
anim.showPrevious();
}
};
prev.setOnClickListener(listener2);
ImageButton menu = (ImageButton) findViewById(R.id.menu);
View.OnClickListener listener3 = new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, menu.class);
startActivity(intent);
}
};
menu.setOnClickListener(listener3);
}
}
I also have edited this post and added the Logcat after somebody has requested it. I think I see the error and it appears as if it is something wrong with the Parse.initialize and Parse.enableLocalDatastore methods, although I do not see anything wrong with their location. I am wondering if I need to put the thread to sleep for a couple seconds so local datastore can load first. I'm not sure but here is the Logcat.
>08-17 19:39:03.018 4601-4601/com.arborhillsvet.arborhillsveterinarianclinic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.arborhillsvet.arborhillsveterinarianclinic, PID: 4601
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arborhillsvet.arborhillsveterinarianclinic/com.arborhillsvet.arborhillsveterinarianclinic.MainActivity}: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: `Parse#enableLocalDatastore(Context)` must be invoked before `Parse#initialize(Context)`
at com.parse.Parse.enableLocalDatastore(Parse.java:58)
at com.arborhillsvet.arborhillsveterinarianclinic.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I need help! Please and thank you.
I guess you have to initialize in Application class may be problem arise because you initialize in MainActivity
do like this
public class ParseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ParseCrashReporting.enable(this);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "xxx", "xxx");
}
}

Categories