videoview.setVideoUri shows null pointer exception - java

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());
}

Related

java.lang.NullPointerException null object reference viewpager

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)

Android studio error: java.lang.RuntimeException: Unable to start activity ComponentInfo

I was trying this code, it can build successfully but it crashes immediately.
The errors shows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.logintest/com.example.logintest.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.gms.common.SignInButton.findViewById(int)' on a null object reference.
And it said it is caused by :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.gms.common.SignInButton.findViewById(int)' on a null object reference
I tried for a long time but still don't know how to fix it, any can help please, thanks!
The LoginActivity.java code are as follow:
public class LoginActivity extends AppCompatActivity {
public static final int GOOGLE_SIGN_IN_CODE = 10005;
SignInButton signIn;
GoogleSignInOptions gso;
GoogleSignInClient signInClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
signIn.findViewById(R.id.signIn);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
signInClient = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(signInAccount != null) {
startActivity(new Intent(this,MainActivity.class));
}
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sign = signInClient.getSignInIntent();
startActivityForResult(sign, GOOGLE_SIGN_IN_CODE);
}
});
}
}
and the error code:
2021-05-28 21:37:33.617 10526-10526/com.example.logintest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.logintest, PID: 10526
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.logintest/com.example.logintest.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.gms.common.SignInButton.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
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:6944)
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.View com.google.android.gms.common.SignInButton.findViewById(int)' on a null object reference
at com.example.logintest.LoginActivity.onCreate(LoginActivity.java:29)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
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:6944) 
part of activity_login.xml:
<androidx.constraintlayout.widget.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=".LoginActivity">
<com.google.android.gms.common.SignInButton
android:id="#+id/signIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="200dp"
android:layout_marginLeft="200dp"
android:layout_marginTop="300dp"
android:layout_marginEnd="200dp"
android:layout_marginRight="200dp"
android:layout_marginBottom="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

How to correctly use a snackbar in Android

I have created a simple counter application for Android. I have just started using support libraries and just to test it out, I wanted to show a snackbar which says Hello. Here is my code in the MainActivity.java file :
package com.mapsup.counter;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends Activity {
long count=0;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
SharedPreferences sp=getApplicationContext().getSharedPreferences("preferences",Context.MODE_PRIVATE);
count=sp.getLong("count",0);
tv=findViewById(R.id.counter);
tv.setText(String.valueOf(count));
//Create and display a snackbar
Snackbar snackbar = Snackbar.make(tv,"Hello",Snackbar.LENGTH_LONG);
snackbar.show();
}
public void increase(View view) {
++count;
tv.setText(String.valueOf(count));
}
public void decrease(View view) {
if(count>0) {
--count;
tv.setText(String.valueOf(count));
}
}
public void reset(View view) {
count=0;
tv.setText("0");
}
#Override
public void onStop() {
super.onStop();
Context ctx=getApplicationContext();
SharedPreferences sp=ctx.getSharedPreferences("preferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putLong("count",count);
editor.apply();
}
}
Here is the layout main_layout.xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0031A0"
android:orientation="vertical"
android:padding="20dp"
android:id="#+id/root">
<TextView
android:id="#+id/counter"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="20dp"
android:layout_weight="1"
android:background="#B2FFFFFF"
android:gravity="center"
android:textSize="36sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="increase"
android:text="#string/add"
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="decrease"
android:text="#string/subt"
android:textSize="30sp" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="reset"
android:text="#string/reset"
android:textAllCaps="false"
android:textSize="30sp" />
</LinearLayout>
When I am running the app, the app crashes. The logcat shows this as the error message :
2020-02-03 00:20:10.015 12849-12849/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mapsup.counter, PID: 12849
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mapsup.counter/com.mapsup.counter.MainActivity}: android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class <unknown>
Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class <unknown>
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:164)
at com.mapsup.counter.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:6712)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
at android.content.res.TypedArray.getColorStateList(TypedArray.java:531)
at android.widget.TextView.<init>(TextView.java:805)
at android.widget.TextView.<init>(TextView.java:727)
at android.widget.TextView.<init>(TextView.java:723)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:430) 
at android.view.LayoutInflater.createView(LayoutInflater.java:645) 
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58) 
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:518) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:426) 
at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:164) 
at com.mapsup.counter.MainActivity.onCreate(MainActivity.java:23) 
at android.app.Activity.performCreate(Activity.java:6712) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
The app runs all fine if I remove the snackbar code.
According to my thinking, creating a snackbar is the same as creating a toast, we just need to replace Toast with Snackbar. Is this correct?
What is my mistake and how to properly use a snackbar?
Please replace tv to rootLayout in Snackbar.make(llRootLayout,"Hello",Snackbar.LENGTH_LONG); as below.
public class MainActivity extends Activity {
long count=0;
TextView tv;|
LinearLayout llRootLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
SharedPreferences sp=getApplicationContext().getSharedPreferences("preferences",Context.MODE_PRIVATE);
count=sp.getLong("count",0);
tv=findViewById(R.id.counter);
llRootLayout=findViewById(R.id.root);
tv.setText(String.valueOf(count));
//Create and display a snackbar
Snackbar snackbar=Snackbar.make(llRootLayout,"Hello",Snackbar.LENGTH_LONG);
snackbar.show();
}
public void increase(View view) {
++count;
tv.setText(String.valueOf(count));
}
public void decrease(View view) {
if(count>0) {
--count;
tv.setText(String.valueOf(count));
}
}
public void reset(View view) {
count=0;
tv.setText("0");
}
#Override
public void onStop() {
super.onStop();
Context ctx=getApplicationContext();
SharedPreferences sp=ctx.getSharedPreferences("preferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putLong("count",count);
editor.apply();
}
}

no errors but still app force closes in android studio [duplicate]

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 trying to make an app to take an image when the button is clicked and then take that image and place it in the image view field.
The given code is fine with no errors, i have checked many times. Still i get this error of runtime exception even when i have instanciated the activity in the manifest file.
here is xml code:
<LinearLayout 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:orientation="vertical"
android:weightSum="10"
tools:context="com.example.android.tryingcamera.MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="9"/>
<Button
android:id="#+id/btnCamera"
android:layout_weight="1"
android:text="Tap To Open Camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btncameraClicked"/>
here is java code:
public class MainActivity extends AppCompatActivity {
private ImageView imageview=(ImageView)findViewById(R.id.imageView);
private Button btncamera = (Button) findViewById(R.id.btnCamera);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btncameraClicked(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data ){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
}
The logcat show this:
Process: com.example.android.tryingcamera, PID: 27769
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.tryingcamera/com.example.android.tryingcamera.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:2567)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
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.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
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.android.tryingcamera.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Check your code You need to
Do findViewById() inside your onCreate() method after setContentView()
Try this Change your code like below code
public class MainActivity extends AppCompatActivity {
private ImageView;
private Button ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview=(ImageView)findViewById(R.id.imageView);
btncamera = (Button) findViewById(R.id.btnCamera);
}
public void btncameraClicked(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data ){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
}
When you declare imageview and btnamera as class variables and assign it all using findViewById, the findViewById method called when the instance of MainActivity class created, but the view not ready.
you can assign the variables after the view already set.
private ImageView imageview;
private Button btncamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview=(ImageView)findViewById(R.id.imageView);
btncamera = (Button) findViewById(R.id.btnCamera);
}

App crashes on startup after adding ImageView [duplicate]

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

Categories