大家好,我总是在调试器中收到此错误,应用程序无法启动。如果我删除上下文菜单,它正在工作......
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);
}
}
}
现在我的tab1.xml 实际上有更多的按钮,但只是对于一些测试,我使用前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:致命异常:主要过程:com.apsps.someappsa..Soundboard,PID:10970了java.lang.RuntimeException:无法启动活动ComponentInfo {com.apsps.someappsa.Soundboard / com.apsps.someappsa .Soundboard.MainActivity}:java.lang.NullPointerException:尝试在android.app.ActivityThread.performLaunchActivity上的空对象引用上调用虚方法'void android.view.View.setOnCreateContextMenuListener(android.view.View $ OnCreateContextMenuListener)' ActivityThread.java:2416)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)在android.app.ActivityThread.-wrap11(ActivityThread.java)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java: 1344)在android.os.Handler.dispatchMessage(Handler.java:102)的android.app.Looper.loop(Looper.java:148)在android.app.ActivityThread.main(ActivityThread.java:5417)在java。 com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteI)中的lang.reflect.Method.invoke(Native Method)显示java.lang.NullPointerException:nit.java:726)在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)所致尝试调用虚拟方法“无效android.view.View.setOnCreateContextMenuListener(机器人上在android.app.Activity.registerForContextMenu(Activity.java:3227)在com.apsps.someappsa.Soundboard.MainActivity.onCreate(MainActivity.java:86)在机器人空对象引用.view.View $ OnCreateContextMenuListener)”。 android.app.ActivityThread.handleLaunchActivity上的android.app.Anstrumentation.callActivityOnCreate(Instrumentation.java:1107)android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)的app.Activity.performCreate(Activity.java:6237) (ActivityThread.java:2476)在android.app.ActivityThread.-wrap11(ActivityThread.java)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)在android.os.Handler.dispatchMessage(Handler.java :102)在android.app.Looper.loop(Looper.java:148)android.app.ActivityThread.main(ActivityT) hread.java:5417)在java.lang.reflect.Method.invoke(本机方法)在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)在com.android.internal.os。 ZygoteInit.main(ZygoteInit.java:616)
答案 0 :(得分:0)
通过调用findViewById指向按钮的代码抛出了一个空点异常。
Button contextMenuButton = (Button) findViewById(buttanArray[i]);
registerForContextMenu(contextMenuButton);
确保buttonArray [i]已获得正确的按钮ID,并且xml文件中存在一个带有该ID的按钮。