我试过在我的SplashScreen中使用Gif图像。当我运行它时,我收到以下错误,一个应用程序崩溃。
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'
请帮我修理一下。你的回答更受赞赏。
这是我的代码:
public class SplashScreen extends AppCompatActivity {
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MYGIFView(context));
context=this;
}
public class MYGIFView extends View {
Movie movie, movie1;
InputStream is = null, is1 = null;
long moviestart;
public MYGIFView(Context con) {
super(con); // ERROR IN THIS LINE
con=context;
is = con.getResources().openRawResource(R.raw.splash_screen);
movie = Movie.decodeStream(is);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now = android.os.SystemClock.uptimeMillis();
System.out.println("now=" + now);
if (moviestart == 0) { // first time
moviestart = now;
}
System.out.println("\tmoviestart=" + moviestart);
int relTime = (int) ((now - moviestart) % movie.duration());
System.out.println("time=" + relTime + "\treltime=" + movie.duration());
movie.setTime(relTime);
movie.draw(canvas, this.getWidth() / 2 - 20, this.getHeight() / 2 - 40);
this.invalidate();
}
}
}
答案 0 :(得分:1)
<强>不强>
setContentView(new MYGIFView(context));
context=this;
<强>不要强>
setContentView(new MYGIFView(SplashScreen.this));
修改强>
当应用程序尝试使用具有null值的对象引用时,将引发java.lang.NullPointerException:尝试调用虚方法 'android.content.res.Resources android.content.Context.getResources()' 在空对象引用上
context is not passing
NullPointerException 。
您可以尝试使用
context=this;
setContentView(new MYGIFView(context));
缺少
setContentView(R.layout.Your_Activity_xml); // Missing
setContentView(new MYGIFView(this));
试试这个
public class SplashScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MYGIFView(SplashScreen.this));
}