I followed this tutorial: http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html?m=1 to make a layout with 5 tabs. Now I want to put an OnLongClickListener for a button in the first tab to make it share sound1. I have added this code in my MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setLongClickable(true);
button1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/ogg");
Uri uri = Uri.parse("android.resource://" + getPackageName()
+ "/raw/" + R.raw.sound1);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
}
});
But that makes it crash on startup, and the logcat says this:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLongClickable(boolean)' on a null object reference
You are using fragments. You should do that on the Fragment's onCreateView() or onViewCreated() callbacks
public class Tab1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
button1 = (Button) v.findViewById(R.id.button1);
button1.setLongClickable(true);
...
return v;
}
}