I am stuck while coding and need help on that.
I am using view binding in my project.
I have unable binding and that is working fine.
I have used same code in my earlier project except view binding and that project was working fine.
Here is my XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".Home">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
Here is my Java code
package com.example.professionals;
public class Home extends AppCompatActivity {
private ActivityHomeBinding Homebinding;
protected ViewPager viewPager;
protected Mypager_Adapter mypager_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Homebinding = ActivityHomeBinding.inflate(getLayoutInflater());
View view = Homebinding.getRoot();
setContentView(view);
Homebinding.pager.findViewById(R.id.pager);
mypager_adapter = new Mypager_Adapter(this);
viewPager.setAdapter(mypager_adapter);
Homebinding.bottomNavigation.setOnItemSelectedListener(new
NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
showMsg("Home");
break;
case R.id.profile:
showMsg("Profile");
break;
}
return false;
}
});
}
private void showMsg(String msg) {
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
toast.show();
}
}
Here is the error list
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.professionals, PID: 17743
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.professionals/com.example.professionals.Home}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2473)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
at android.app.ActivityThread.access$1100(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
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 androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
at com.example.professionals.Home.onCreate(Home.java:32)
at android.app.Activity.performCreate(Activity.java:6321)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
at android.app.ActivityThread.access$1100(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
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)
Thanks in advance for help!
You need to add
viewPager = findViewById<ViewPager>(R.id.pager)
Before this line
viewPager.setAdapter(mypager_adapter);
Edit:
Actually it seems like you're attempting to use ViewBinding as well as regular findViewById, if I were you I'd stick with ViewBinding and delete this line
protected ViewPager viewPager;
Then try this instead
Homebinding.pager.setAdapter(mypager_adapter);
You haven't initialize your ViewPager.
You need initialize your viewPager. For that you have couple of options
Initialize with findViewById before setting adapter.
viewPager = findViewById(R.id.pager)
As you are using view binding would be the good idea
Homebinding.pager.setAdapter(mypager_adapter)
Related
I've seen a few other similar references to this issue, however have not yet found a solution to my issue.
I used to use android.preference.Preference however have recently moved over to androidx in order to use a SeekBarPreference.
Now, when I try to inflate the Preference screen I get the following error:
2021-11-17 20:57:20.623 18270-18270/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.test, PID: 18270
android.view.InflateException: Binary XML file line #1: Error inflating class (not found)android.support.v7.preference.PreferenceScreen
at androidx.preference.PreferenceInflater.createItemFromTag(PreferenceInflater.java:287)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:151)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:109)
at androidx.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:216)
at androidx.preference.PreferenceFragmentCompat.setPreferencesFromResource(PreferenceFragmentCompat.java:377)
at com.project.test.SettingsFragment.onCreatePreferences(SettingsFragment.java:33)
at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:160)
at com.project.test.SettingsFragment.onCreate(SettingsFragment.java:25)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:280)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1175)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1255)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1138)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:136)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1989)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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.ClassNotFoundException: android.support.v7.preference.PreferenceScreen
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:454)
at androidx.preference.PreferenceInflater.createItem(PreferenceInflater.java:214)
at androidx.preference.PreferenceInflater.createItemFromTag(PreferenceInflater.java:277)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:151)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:109)
at androidx.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:216)
at androidx.preference.PreferenceFragmentCompat.setPreferencesFromResource(PreferenceFragmentCompat.java:377)
at com.project.test.SettingsFragment.onCreatePreferences(SettingsFragment.java:33)
at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:160)
at com.project.test.SettingsFragment.onCreate(SettingsFragment.java:25)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:280)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1175)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1255)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1138)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:136)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1989)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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.ClassNotFoundException: android.support.v7.preference.PreferenceScreen
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:454)
at androidx.preference.PreferenceInflater.createItem(PreferenceInflater.java:214)
at androidx.preference.PreferenceInflater.createItemFromTag(PreferenceInflater.java:277)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:151)
at androidx.preference.PreferenceInflater.inflate(PreferenceInflater.java:109)
at androidx.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:216)
at androidx.preference.PreferenceFragmentCompat.setPreferencesFromResource(PreferenceFragmentCompat.java:377)
at com.project.test.SettingsFragment.onCreatePreferences(SettingsFragment.java:33)
at androidx.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:160)
at com.project.test.SettingsFragment.onCreate(SettingsFragment.java:25)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:280)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1175)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1255)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1138)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:136)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1989)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
An excerpt of my SettingsFragment.java file (error is reported on the setPreferencesFromResource line):
public class SettingsFragment extends PreferenceFragmentCompat {
Utilities utils = new Utilities();
Context context = ProjectGlobal.getAppContext();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor settingsEditor = settings.edit()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.pref_general, rootKey);
Preference pfPermissionsReset = findPreference("permissionsPrompt");
Preference pfBatterySaving = findPreference("batteryPrompt");
final SeekBarPreference pfVolumeValue = (SeekBarPreference) findPreference("sbVolume");
final SwitchPreference pfGlobalVolume = (SwitchPreference) findPreference("chkUseGlobalVolume");
//init global volume control
pfVolumeValue.setMax(100);
pfVolumeValue.setMin(0);
From my pref_general.xml preference layout:
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.preference.PreferenceCategory
android:summary="App Settings"
android:title="GENERAL" />
<android.support.v7.preference.SwitchPreference
android:key="chkNotificationListener"
android:summary="This option allows you to disable the app without uninstalling the application. [Default: On]"
android:title="Notification Listener"
android:defaultValue="true"
/>
<android.support.v7.preference.SwitchPreference
android:key="chkHideBanner"
android:summary="This option hides the banner notification at the top of the screen. Please note, this may impact the reliability of the application if disabled! [Default: Off]"
android:title="Hide Banner Notification"
android:defaultValue="false"
/>
<android.support.v7.preference.Preference android:title="Check Battery Saving"
android:key="batteryPrompt"
android:summary="Tap here to check that the app is allowed to run in the background/during startup on your device" />
<android.support.v7.preference.PreferenceCategory
android:summary="Audio"
android:title="AUDIO"/>
<android.support.v7.preference.SwitchPreference
android:key="chkOnlyUseSpeaker"
android:summary="This option will attempt to play audio alerts from the device loudspeaker only [Default: Off]"
android:title="Only Use Speaker"
android:defaultValue="false"
/>
<android.support.v7.preference.SwitchPreference
android:key="chkUseGlobalVolume"
android:summary="This option will override any volume settings set in each rule [Default: Off]"
android:title="Use Global Volume"
android:defaultValue="false"
/>
<android.support.v7.preference.SeekBarPreference
android:key="sbVolume"
android:title="Global Volume"
android:dependency="chkUseGlobalVolume"
android:max="100"
android:defaultValue="50"
/>
/>
<android.support.v7.preference.PreferenceCategory
android:summary="Security"
android:title="SECURITY"/>
<android.support.v7.preference.Preference android:title="Check Permissions"
android:key="#string/permissionsPrompt"
android:summary="Tap here to re-check permissions" />
</android.support.v7.preference.PreferenceScreen>
From my Launcher.java:
public class Launcher extends AppCompatActivity implements SettingsFragment.OnFragmentInteractionListener,RuleFragment.OnFragmentInteractionListener,HelpFragment.OnFragmentInteractionListener {
RuleFragment ruleFragment = new RuleFragment();
SettingsFragment prefsFragment = new SettingsFragment();
HelpFragment helpFragment = new HelpFragment();
Utilities utils = new Utilities();
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
getSupportFragmentManager().beginTransaction().remove(helpFragment).commit();
getSupportFragmentManager().beginTransaction().remove(prefsFragment).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.contentFrame,ruleFragment).commit();
return true;
case R.id.navigation_settings:
getSupportFragmentManager().beginTransaction().remove(ruleFragment).commit();
getSupportFragmentManager().beginTransaction().remove(helpFragment).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.contentFrame,prefsFragment).commit();
return true;
case R.id.navigation_help:
getSupportFragmentManager().beginTransaction().remove(prefsFragment).commit();
getSupportFragmentManager().beginTransaction().remove(ruleFragment).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.contentFrame,helpFragment).commit();
return true;
}
return false;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Launcher.context = getApplicationContext();
Utilities utils = new Utilities();
//initiate home screen
setContentView(R.layout.main);
getSupportFragmentManager().beginTransaction().replace(R.id.contentFrame,ruleFragment).commit();
}
My main.xml layout for Launcher:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/main_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layout_above="#+id/navigation"
app:titleTextColor="#color/Black"
>
<FrameLayout
android:id="#+id/contentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
</RelativeLayout>
Managed to solve this. It was because I hadn't updated android.support.v7.preference within pref_general.xml to androidx.preference.
After doing this, it worked fine!
So I have a VideoView but when I try to play video (which is in my res/raw folder)it gives me null pointer exception. I tried using video.setVideoUri(uri) and also video.setVideoPath(path) but it still shows null pointer exception.
Activity:
public class Player extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
VideoView videoView=findViewById(R.id.videoView);
String path="android.resource://"+getPackageName()+"/"+R.raw.playthis;
Uri uri=Uri.parse(path);
videoView.setVideoPath(uri.getPath());
}
public void goBackVideo(View view){
finish();
}
}
xml for VideoView:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/VideoPlayerFrameLayout" android:background="#drawable/player_video_pause">
<VideoView android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/videoView"/>
<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:src="#drawable/player_icon_play" android:onClick="setPlayORpause"
android:id="#+id/PauseButton" android:background="#fff"/>
<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="left|center" android:layout_marginLeft="160dp"
android:src="#drawable/player_icon_prev" android:id="#+id/PrevButton" android:background="#fff"/>
<ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="right|center" android:layout_marginRight="160dp"
android:src="#drawable/player_icon_next" android:id="#+id/NextButton" android:background="#fff"/>
<ImageButton
android:layout_width="46dp"
android:layout_height="34dp"
android:id="#+id/backPressButton"
android:rotation="180" android:backgroundTint="#fff"
android:background="#null"
android:src="#drawable/settings_icon_back"
android:layout_gravity="left"
android:onClick="goBackVideo" android:drawingCacheQuality="high"/>
</FrameLayout>
Logcat:
2020-10-29 06:58:50.965 13640-13640/com.testapp.test3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.testapp.test3, PID: 13640
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testapp.test3/com.testapp.test3.VideoPlayer}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setVideoPath(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2887)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2965)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1669)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6702)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setVideoPath(java.lang.String)' on a null object reference
at com.testapp.test3.VideoPlayer.onCreate(VideoPlayer.java:26)
at android.app.Activity.performCreate(Activity.java:7115)
at android.app.Activity.performCreate(Activity.java:7106)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2840)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2965)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1669)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6702)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
Do I need to set up a content provider before I can play any video?
How do I fix this?
EDIT:
Now i get another error
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
final VideoView videoView=findViewById(R.id.videoView);
Uri uri=Uri.parse("content://" +"sdcard/"+Environment.DIRECTORY_DOWNLOADS+"/"+"playthis.mp4");
MediaController mediaController=new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);
videoView.setVideoURI(uri);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videoView.seekTo(0);
videoView.start();
}
});
}
logcat:
2020-10-29 07:51:39.371 27420-27420/com.testapp.test3 E/ActivityThread: Failed to find provider info for sdcard
2020-10-29 07:51:39.371 27420-27420/com.testapp.test3 W/MediaPlayer: Couldn't open content://sdcard/Download/playthis.mp4: java.io.FileNotFoundException: No content provider: content://sdcard/Download/playthis.mp4
2020-10-29 07:51:39.375 27420-27420/com.testapp.test3 E/MediaPlayerNative: Unable to create media player
2020-10-29 07:51:39.381 27420-27420/com.testapp.test3 W/VideoView: Unable to open content: content://sdcard/Download/playthis.mp4
java.io.IOException: setDataSource failed.: status=0x80000000
at android.media.MediaPlayer.nativeSetDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1181)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1169)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1087)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1108)
at android.widget.VideoView.openVideo(VideoView.java:399)
at android.widget.VideoView.-wrap0(Unknown Source:0)
at android.widget.VideoView$7.surfaceCreated(VideoView.java:678)
at android.view.SurfaceView.updateSurface(SurfaceView.java:710)
at android.view.SurfaceView$2.onPreDraw(SurfaceView.java:145)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:977)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2427)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1446)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6954)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
at android.view.Choreographer.doCallbacks(Choreographer.java:737)
at android.view.Choreographer.doFrame(Choreographer.java:669)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6702)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
You should add a contentView on your activity onCreate So change your onCreate Like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_name) // Add this line,
VideoView videoView=findViewById(R.id.videoView);
String path="android.resource://"+getPackageName()+"/"+R.raw.playthis;
Uri uri=Uri.parse(path);
videoView.setVideoPath(uri.getPath());
}
After that you should check null video path, like
// If path is not null then set it to your videoView.
if(uri.getPath() != null) {
videoView.setVideoPath(uri.getPath());
}
This question already has answers here:
Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
(2 answers)
Closed 4 years ago.
I am running a basic app with one ImageView. It runs until I add the following
ImageView gohan = findViewById(R.id.gohanView);
These are the only things that I've done:
Created project
Created empty activity
Added ImageView to activity
Imported image to drawable folder
Attached image to src of ImageView
RUN (Everything works at this point)
I then add the code above to my MainActivity class and the app will not run anymore.
Java
package com.example.david.dragonballz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView gohan = findViewById(R.id.gohanView);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/gohanView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="69dp"
android:layout_marginEnd="114dp"
android:layout_marginLeft="114dp"
android:layout_marginRight="114dp"
android:layout_marginStart="114dp"
android:layout_marginTop="69dp"
android:src="#drawable/gohan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Logcat
04-18 13:02:51.416 15392-15392/com.example.david.dragonballz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.david.dragonballz, PID: 15392
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.david.dragonballz/com.example.david.dragonballz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2839)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:56)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.david.dragonballz.MainActivity.<init>(MainActivity.java:9)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1180)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2829)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Here is example of WORKING code from the Android classes I'm taking. Why does this work for him and used to work for me?
EXAMPLE
Never find id of any views before onCreate() method because the xml layout is loaded on onCreate().
setContentView(R.layout.activity_main);
find id in onCreate()
gohan = (ImageView) findViewById(R.id.gohanView);
Declare this
public ImageView gohan;
Add this line in oncreate()
gohan = (ImageView)findViewById(R.id.gohanView);
after this line
setContentView(R.layout.activity_main);
Finally your onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gohan = (ImageView)findViewById(R.id.gohanView);
gohan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
gohan.animate().alpha(0).setDuration(2000);
}
});
}
ALSO NOW ACCESS THIS IMAGEVIEW ANYWHERE
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Edit: I realize this has been marked as a duplicate. But I believe this is somewhat different because I am not asking what a Null Pointer Exception is or how to fix it on a "programming fundamentals" level. If I am wrong on that then please correct me, but I believe that my question touches on a more intricate matter dealing with the Android framework. My issue has I have been trying to create a simple media player app following a basic YouTube tutorial but the app continues to force close immediately upon opening in the emulator. I am assuming it is some sort of configuration error because I have followed the tutorial to the letter. I have updated my code snippets according to the advice given. In the emulator the app force closes, however when I run the device on my phone the toast message "Null Array" is shown. My question, therefore, is why the program is not adding items into the mySongs ArrayList because there are .mp3 files in both the internal and external storage directories of my device. My code is as follows....
MainActivity.java:
public class MainActivity extends AppCompatActivity
{
ListView lv;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvPlaylist);
final ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
items = new String[mySongs.size()];
if (mySongs != null && !mySongs.isEmpty())
{
for (int i = 0; i < mySongs.size(); i++)
{
//toast(mySongs.get(i).getName().toString());
items[i] = mySongs.get(i).getName().toString().replace("mp3", "").replace(".wav", "");
}
}
else
{
//Log.e(getString(R.string.Exception));
Toast.makeText(this, "Null Array", Toast.LENGTH_SHORT).show();
}
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), R.layout.song_layout, R.id.textView,items);
lv.setAdapter(adp);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(getApplicationContext(), Player.class).putExtra("pos", position).putExtra("songlist", mySongs));
}
});
}
public ArrayList<File> findSongs(File root)
{
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
for (File singleFile : files)
{
if (singleFile.isDirectory() && !singleFile.isHidden())
{
findSongs(singleFile);
}
else
{
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav"))
{
al.add(singleFile);
}
}
}
return al;
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.user.mediaplayer.MainActivity">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/lvPlaylist"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
The log file:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.mediaplayer/com.example.user.mediaplayer.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
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 get length of null array
at com.example.user.mediaplayer.MainActivity.findSongs(MainActivity.java:42)
at com.example.user.mediaplayer.MainActivity.onCreate(MainActivity.java:28)
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)
I have also included:
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
in the AndroidManifest.xml file. Any advice in the right direction would be appreciated. Thanks...
You're trying to get the length of ArrayList mySongs. It the ArrayList received from findSongs() methods is empty it might result in the Null Pointer exception on the line mySongs.length
Check whether the ArrayList mySongs is null or not before performing any operations on it.
This question already has answers here:
I would like to set my variables at the top of my class instead of in the method
(4 answers)
Closed 7 years ago.
I'm new to Android Studio (and am hating the transition experience from Eclipse). I'm trying to write an app that currently has two activities. I already wrote the Java code for the main logic and it works fine, but haven't put it in the second activity yet. As I'm trying to write and run the app, it gives me an error.
There's a LoginActivity and MainActivity. Currently LoginActivity just has a dummy text and a button that takes the user to MainActivity. Currently MainActivity has just a TextView in it. When I click it, the app crashes and gives the following error. I can see it has something to do with initiating MainActivity but I can't seem to fix it.
09-10 20:16:43.012 21126-21126/com.projects.example.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.projects.example.myapp, PID: 21126
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.projects.example.myapp/com.projects.example.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2072)
at com.projects.example.myapp.MainActivity.<init>(MainActivity.java:22)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
My xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".LoginActivity"
android:orientation="vertical" >
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/loginbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="goToMainActivity" />
</LinearLayout>
LoginActivity relevant code:
public void goToMainActivity(View view)
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
MainActivity code as requested (line 22 is indicated by the prefix **):
public class MainActivity extends AppCompatActivity {
String currentWinnerName = "";
**TextView currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentWinnerLabel.setText("Finding...");
//try
//{
//checkCurrentWinner(); //will implement this
//}
//catch (Exception e)
//{
//print e.getMessage() to log
//}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The reason is, that you are trying to assign value to currentWinnerLabel before activity is created.
Unless activity is created, the context is null, and you are calling findViewById method on a null object reference.
Just change your code:
TextView currentWinnerLabel;
and after:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentWinnerLabel = (TextView)findViewById(R.id.currentWinnerLabel);
...