2
votes

Hello people Im always getting this error in debugger and the app will not start. If I am deleting the contextmenu it is working...

   public class MainActivity extends AppCompatActivity {


public int[] buttonArray = {R.id.button1, R.id.button2, R.id.button3}; // Button Array
public int[] soundsArray = {R.raw.sound1, R.raw.sound2, R.raw.sound3}; // Sound Array


private int[] tabIcons = {
        R.drawable.infoicon,
        R.drawable.soundicon,
        R.drawable.startop
};


int counters=1;
int counter=1;


final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;

public String ordnerpfad = Environment.getExternalStorageDirectory() + "/Sounds";
public String soundpfad = ordnerpfad + "/sound.mp3";
public File ordnerfile = new File(ordnerpfad);
public File soundfile = new File(soundpfad);
public Uri urisound = Uri.parse(soundpfad);
public byte[] byte1 = new byte [1024];
public int zwischenspeicher = 0;
public InputStream is1;
public FileOutputStream fos;

public Intent teilintent;


InterstitialAd mInterstitialAd;
TabLayout tabLayout;
ViewPager viewPager;
MediaPlayer MainMMP;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Handler handler1 = new Handler();
    handler1.postDelayed(new Runnable() {
        public void run() {
            requestNewInterstitial();
        }
    }, 14000);

    MobileAds.initialize(getApplicationContext(), "xxxxxxxxxxxxxxx");
    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest request = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
            .addTestDevice("2BB7955A07F972AC2D1DA7617768CE01")
            .build();
    mAdView.loadAd(request);



    mInterstitialAd = new InterstitialAd(this);
    mInterstitialAd.setAdUnitId("xxxxxxxxxxxxxx");
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {

            mInterstitialAd.show();
        }
    });


    for (int i = 0; i < buttonArray.length; i++) {
        Button contextMenuButton = (Button) findViewById(buttonArray[i]);
        registerForContextMenu(contextMenuButton);
    }

    MainMMP = MediaPlayer.create(this, R.raw.sound1);

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    setupViewPager(viewPager);


    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    });

}


@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setMessage("Close this App?\n\nWe are happy for each Feedback :) ")
            .setCancelable(false)
            .setNeutralButton("Rate Us", new    DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int rate){
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse("http...xxxx..xxx"));
                    startActivity(intent);
                }
            })

            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    MainMMP.release();
                    finish();
                    System.exit(0);
                }
            })
            .setNegativeButton("No", null)
            .show();
}

private void requestNewInterstitial() {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All  emulators
            .addTestDevice("2BB7955A07F972AC2D1DA7617768CE01")
            .build();
    mInterstitialAd.loadAd(adRequest);

}

public void Share(View view){

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey, check this Soundboard");
    sendIntent.setType("text/plain");
    startActivity(sendIntent);

}

@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);

    menu.setHeaderTitle("Context Menu");
    menu.add(0, view.getId(), 0, "Action 1");
    menu.add(0, view.getId(), 0, "Action 2");
}


@Override
public boolean onContextItemSelected(MenuItem item) {
    if(item.getTitle().equals("Action 1")){function1(item.getItemId());}
    else if(item.getTitle().equals("Action 2")){function2(item.getItemId());}
    else {return false;}
    return true;
}


public void function1(int id){

    for (int i=0; i<buttonArray.length; i++) {
        if (id == buttonArray[i]) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {


                if (!ordnerfile.exists()) {

                    try {
                        ordnerfile.mkdir();
                        Toast.makeText(getApplicationContext(), "Created Folder", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
                    }

                }

                try {


                    is1 = getResources().openRawResource(soundsArray[i]);
                    fos = new FileOutputStream(soundfile);

                    while ((zwischenspeicher = is1.read(byte1)) > 0) {

                        fos.write(byte1, 0, zwischenspeicher);

                    }

                    is1.close();
                    fos.close();

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();

                }
                teilintent = new Intent(Intent.ACTION_SEND);
                teilintent.setType("audio/*");
                teilintent.putExtra(Intent.EXTRA_STREAM, urisound);
                startActivity(Intent.createChooser(teilintent, "Share this Sound..."));
            }

            else {
                ActivityCompat.requestPermissions(MainActivity.this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
            }
            return;

        }

    }
}


public void function2(int id){
    Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();}



public void MainMMP(View view) {


    for (int i=0; i<buttonArray.length; i++) {
        if (view.getId() == buttonArray[i]) {
            MainMMP.release();
            MainMMP = MediaPlayer.create(MainActivity.this, soundsArray[i]);
            MainMMP.start();
        }
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        ordnerfile.mkdir();
        Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
    }
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[2]);
    tabLayout.getTabAt(2).setIcon(tabIcons[1]);
    tabLayout.getTabAt(3).setIcon(tabIcons[1]);
    tabLayout.getTabAt(4).setIcon(tabIcons[1]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new FragmentFavourite(), "");
    adapter.addFrag(new Fragment1(), "Top Sounds");
    adapter.addFrag(new Fragment2(), "Sounds 1");
    adapter.addFrag(new Fragment3(), "Sounds 2");
    adapter.addFrag(new Fragment4(), "Sounds 3");
    viewPager.setAdapter(adapter);
}

    class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();


        private ViewPagerAdapter(FragmentManager manager) {
            super(manager);}

    @Override
    public Fragment getItem(int position) {

        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }
    private void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

}

Now my tab1.xml Actual there are more buttons but just for some tests I do it with the first 3

<?xml version="1.0" encoding="utf-8"?>


<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">



    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
              android:layout_gravity="center_vertical|center_horizontal|center"
            android:layout_margin="15dp"
            android:minHeight="90dp">

            <Button
                android:id="@+id/button1"
                android:onClick="MainMMP"
                android:text="Fun Fun\nFun"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"
                android:layout_weight="1" />


            <Button
                android:id="@+id/button2"
                android:onClick="MainMMP"
                android:text="Sing, Dance,\nPretend"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button3"
                android:onClick="MainMMP"
                android:text="Kazoo\nSound1"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp" />

            <Button
                android:id="@+id/button4"
                android:onClick="MainMMP"
                android:text="Kaaaa-\nzooo"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button5"
                android:onClick="MainMMP"
                android:text="Kazoo\nSound2"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"/>

            <Button
                android:id="@+id/button6"
                android:onClick="MainMMP"
                android:text="Just Kazoo\nit"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button7"
                android:onClick="MainMMP"
                android:text="Special-\nfriends"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"/>

            <Button
                android:id="@+id/button8"
                android:onClick="MainMMP"
                android:text="I just \n wanna say"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button9"
                android:onClick="MainMMP"
                android:text="Before I\n met you"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"/>

            <Button
                android:id="@+id/button10"
                android:onClick="MainMMP"
                android:text="Right\n by my side"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button11"
                android:onClick="MainMMP"
                android:text="Sing a Song\n for you"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"/>

            <Button
                android:id="@+id/button12"
                android:onClick="MainMMP"
                android:text="Your my\n Friend"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button13"
                android:onClick="MainMMP"
                android:text="I was \n alone"
                style="?android:attr/borderlessButtonStyle"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"/>

            <Button
                android:id="@+id/button14"
                style="?android:attr/borderlessButtonStyle"
                android:onClick="MainMMP"
                android:text="Looking\n for a friend"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginStart="15dp"
                android:layout_marginLeft="15dp"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="15dp"
            android:layout_gravity="center_vertical|center_horizontal|center">

            <Button
                android:id="@+id/button15"
                android:onClick="MainMMP"
                style="?android:attr/borderlessButtonStyle"
                android:text="Speeeecial-\nfrieeeend"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:layout_height="wrap_content"
                android:background="@drawable/mybutton"
                android:layout_weight="1"
                android:layout_marginEnd="15dp"
                android:layout_marginRight="15dp"/>


        </TableRow>

    </TableLayout>
  </ScrollView>

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.apsps.someappsa..Soundboard, PID: 10970 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apsps.someappsa.Soundboard/com.apsps.someappsa.Soundboard.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnCreateContextMenuListener(android.view.View$OnCreateContextMenuListener)' 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.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnCreateContextMenuListener(android.view.View$OnCreateContextMenuListener)' on a null object reference at android.app.Activity.registerForContextMenu(Activity.java:3227) at com.apsps.someappsa.Soundboard.MainActivity.onCreate(MainActivity.java:86) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1
Please don't delete your code from the posts. If you want no one to see it, delete the question.OneCricketeer

1 Answers

0
votes

Your code for pointing to the button by calling findViewById is throwing a null point exception.

Button contextMenuButton = (Button) findViewById(buttanArray[i]);
registerForContextMenu(contextMenuButton);

Make sure that your buttonArray[i] has got the correct ID of the button and there exist a button in your xml file with that ID.