NullPointerException on getResources().getDisplayMetrics().density - java

Context
I'm working on a small test code right now. It selects an image, resizes it to fit the screen based on the screen density. While it does this, it makes a copy of the image at the size it would be in an xxhdpi display, and the converts into a Bitmap, then into a String. The String is then carried through an Intent to the next screen where the String is turned back into a Bitmap and then placed in an ImageButton.
This worked fine until I added in a chunk of code to resize the image given by the string based on the density. The odd thing is I copied and pasted the DPI() method from another activity and there were no issues in that activity.
Code
package com.example.zachary.imagetesting.Resizing;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.zachary.imagetesting.R;
public class PictureDecoded extends Activity {
TextView Text;
ImageButton Image;
String string;
Bitmap picture;
public float DPI(){return getResources().getDisplayMetrics().density;}
float dpi = DPI() * 180;
int size = (int) dpi;
public Bitmap Pic(String string){
try{
byte[] b = Base64.decode(string, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resizing);
string = getIntent().getStringExtra("String");
Image = (ImageButton) findViewById(R.id.image);
Text = (TextView) findViewById(R.id.text);
picture = Pic(string);
Image.setImageBitmap(Bitmap.createScaledBitmap(picture,size,size,false));
}
public void next(View view){ }
// I also tried addring DPI() here as well to no success.
//public float DPI(){return getResources().getDisplayMetrics().density;}
}
Error Log
01-15 19:55:17.104 30570-30570/com.example.zachary.imagetesting D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
01-15 19:55:17.194 30570-30570/com.example.zachary.imagetesting E/Bitmap String:: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAGVAhwDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDuKKKK
/wAVz/UgKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKK
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAo
oooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACii
igAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKK
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
KKKKACiiigAooooAKKKKACiiigA45GemM+3XGeTjOOPx5ODkruPAuv6DpWppYeMtHj1zwhqk0MOt
2qxqur2EO9h/bHhy/UpcadqtlkTeXFKLTU4l+wanBNA0RTtPjP8ABnU/hRqdldW102ueC/EUa3nh
XxKkaKl1bzo1zFYXqoxEWoQ2jQziQKltf2zpe2aoRd2cPBLMaFLH0svxF6NbEwnPBSk17LFqko+2
p056cuIopqc6EleVKUalKdRRrKMe0ipqnLRyTcG9p2spJa6SW/K9WtU3advE6KKK7ywooooAKKKK
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK0NM0jV9buB
Z6LpWo6vdHAFrpdhd39yckgYgtIZpecf3fT1yfcvDv7Lnxx8Rwpcx+Dn0a3fG2XxFqOn6TLg5wWs
J7htTQcZw1lu68E43cOLzLLcAr47H4TCLS31jE0aLe6SjGpUUpN8rsopvye7iVSnBXnOEF3lJR79
3/dfn69fn2ivtPTP2HPiTcgHVfFXhHSxgErA2salKOuRtOnWMeRgYImYHPJGDXWw/sG6gV/0j4oW
cb4HEPhCeZc5OfmfxJAQMYx8pJJOQNvPh1ON+FKTtLOaLa/590MZWXb4qOHqRf3v9TB43CK968dO
0Zvqlpyxafffa9z8/wCivvO8/YQ8RIrHT/iPo1w38K3nh6/s1PJxuaHU74rkY6I2CSPm25PBap+x
b8Y7EObCfwprQXO1bTWZ7OZ+Wxgatp9jApYAcG6wDn5sAtV0eM+Fq+kM6wsdv40a+GXXVvEUqSS0
1bemt72d3HGYWW1eH/b3NHy+0lf+vU+SaK9G8VfCH4oeCXlHiXwPr9hDCCXv47F9Q0kKCRu/tbTD
e6eBxnDXQbGMgE8+cjB5ByPUexx6nv8ArxknmvoMPicNi6aq4XEUcTSdrVKFWnVptO9rTpylHXld
tfn33jKM1eEoyXeLUl16pvt+ers7lfqF8ItCX43/ALKY8H6y8VxqGnHV9A0bULtRI2n6no85vPDV
wJOZIlsrS+06wkZCGbTvtFq2YpJA35e1+q37EW//AIVBrQb/AFf/AAnmseX97J/4p/wnv6nG3OCN
v8RfJyOfifEOc6GR4fG0ZezxOBzTB4nDVUlzQqReIirPezupTje0koqV0cWPbjh1OOkqdWnKL6p3
qLTtsm++zva7/LC5triyurmyu4mhurOea1uYWHzxXEEssM0TDqGjkiZWB5zkdiagr2T9oPQ4/Dvx
s+I+nRALFJrp1aJQOAuu2lvrbqOeiy38igdgGHG3nxuvs8BiY43A4PGR+HFYXD4mPkq9JVEt+zXV
9NW1JvtpyU6cJracIyXpJN9/T/PVtFFFFdRQUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFF
FABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUU
AFFFFABRRRQAUUUUAFH+f5+/t/Png57nwD8NvGfxN1f+x/B+jzahLGEa8vHJg0vTYXZlE+pag6GK
1Qlfkj+e6nO9bW3mkQof0q+E37JHgbwOINW8X+T428RKYZV+22+PD2mzIS2LHS5VYXrpIMrean5m
4CKWGxtZM181n3FeUcPxccVVdbF8t6eBw7jOvK/wyqXko0IPdSqtOUVJ04TkuU5q+Lo4dNTledtK
cdZP4rX1tFOyacnreVruPvfA3w3/AGfvif8AFBUu9E0UabopkRG8Q6+0unaWysTueyUwSXmqBVGd
2nW08AkBimuImJNfdvgH9jP4beGzHeeLrm98cX4jTNvdmTS9BilAfc8enWM32u4weAt9qU1u6lS9
mpyp+wFVUAVFCqAFAUAAKoIUADgADhQOAMADApa/G844+z7NHUp0K39mYWV0qWDlKNdxu7e0xbar
OXnR9jFqTjKDUU341XMMRUuoy9nF9IfFu3rP4uvSytdNO9zG0Lw54f8AC2nrpXhvRdM0LTkwRZaT
Y21halhxveG1iiSSQ4BMjhnJwSxIJOz/AJ/n7/5yeTzkor4qc51JynUnKc5tynOcnKcpdZSlKTcm
+rbb829Tibbbbbbe7bd2+7bbf5+reoUUUVIgooooAMf4Z5zjnv1/+sT1GQfDfH37Onwm+IMd7LqH
hq20fWLs7/8AhIfDqx6Vqqz5YmeZYonsNQd8gSHUrK6Yj7jo43V7lRXVg8bjMvrKvgcVXwtZW/eU
Ks6cmoybUZcskpwvq4T5oSTalFq97hOdN81OcoPvFtXt3s9V5PTvc/I34r/so+Pfh6l7rHh/d408
L2y+c93YW7R67YQguJG1HRlMrzRQgAveaZLdRiMNPcwWkQc19r/shaNcaR8DtFmuYmhfW9W17W1R
1KsYZL4aZbSEH+Ga20mKeMnJMcgOSDX03gf5/H/Pr05OKZHHHFGsUSpFGoCqqIERRuP3UQAAclsK
PzJ4+kzXjLMs6yWnlWYU6VSrTxVKu8bBeznVp06deHs6tGK9nzuVRTdSlyRaUYOjf94+mrjKlagq
NRJtSUvaLRtRUrJxStf3m7rva29/xq/akvY7749+P3iZWS2m0KyLD/n
01-15 19:55:17.194 30570-30570/com.example.zachary.imagetesting I/Timeline: Timeline: Activity_launch_request id:com.example.zachary.imagetesting time:50420468
01-15 19:55:17.244 30570-30570/com.example.zachary.imagetesting D/AndroidRuntime: Shutting down VM
01-15 19:55:17.244 30570-30570/com.example.zachary.imagetesting E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zachary.imagetesting, PID: 30570
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.zachary.imagetesting/com.example.zachary.imagetesting.Resizing.PictureDecoded}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:90)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at com.example.zachary.imagetesting.Resizing.PictureDecoded.DPI(PictureDecoded.java:20)
at com.example.zachary.imagetesting.Resizing.PictureDecoded.<init>(PictureDecoded.java:21)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1650)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2536)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5942) 
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:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
The large block of text is the String converted from Bitmap that was passed to the Activity. I left it in just in case it was useful. The line before the large block of text was the button click that started the intent to the activity which crashes due to NullPointerException.
I can add the other activities on request, but since it worked before I tried resizing based on screen density I didn't feel it was needed.

An Activity's base Context won't have been setup until after onCreate() has finished executing. Simply move the initialization of dpi to onCreate() after super.onCreate() has been called.

Related

splash screen is not working in android 6

I have added splash screen in my app but the app crashes when is run on Android 6. The interesting thing is that the app runs fine on Android 9.
Don't know what to do.
Target SDK - 28.
min SDK= 19
it is showing error on oncreate method while run app on android 6
splash.java
import android.os.Bundle;
import android.os.Handler;
public class splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // it showing error here.
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 4000;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent splashintent=new Intent(splash.this,MainActivity.class);
startActivity(splashintent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
logs
06-22 16:17:30.930 10294-10294/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.napps.wallpaper, PID: 10294
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.napps.wallpaper/com.napps.wallpaper.splash}: android.content.res.Resources$NotFoundException: Resource ID #0x7f07009e
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5896)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f07009e
at android.content.res.Resources.getValue(Resources.java:1595)
at androidx.appcompat.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:331)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:198)
at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:260)
at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
at com.napps.wallpaper.splash.onCreate(splash.java:13)
at android.app.Activity.performCreate(Activity.java:6298)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5896) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
There might be problem with your drawable Image. While copying image Please check the folder in which you are copying.
Try to add the image in drawable folder not drawable-21
I would suggest to remove old image and Add Image again to proper directory.

My App runs for a split second showing a white screen and then crashes without showing any error

I am beginner to android studio i was trying to make ping pong game, so i started testing my program by setting the content view to pong class object and tried to set the color of the surface. but As soon as i run the program on my phone, the app runs for a split sec showing a white screen and then closing on its own. please help me with this
package com.example.pong;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creating object of Pong class
Pong pongObj;
Display display;
//getting the resolution of the screen
display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
//passing those resolution to the create a surface which would be be needed to drawn upon
pongObj = new Pong(this,size.x,size.y);
setContentView(pongObj);
}
}
Pong class
package com.example.pong;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class Pong extends SurfaceView{
private final SurfaceHolder SurfaceHolder;
private Canvas myCanvas;
private Paint myPaint;
public Pong(Context context,int x,int y)
{
super(context);
SurfaceHolder = getHolder();
myCanvas.drawColor(Color.argb(0,0,0,255));
}
}
Here is the logact window, i can't understand the error, please help me with this
2020-05-28 05:31:27.477 8238-8238/com.example.pong E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pong, PID: 8238
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pong/com.example.pong.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference
at com.example.pong.Pong.<init>(Pong.java:19)
at com.example.pong.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:6857)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:163) 
at android.app.ActivityThread.main(ActivityThread.java:6238) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) 
2020-05-28 05:31:27.513 8238-8238/com.example.pong I/Process: Sending signal. PID: 8238 SIG: 9

How to pass a variable to findViewById method using classes and instances? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've been trying to make this tic-tac-toe game on android studios recently, I only have basic knowledge about android studio and java so i wanted to accomplish this app by making classes and objects, but whenever i try to run my app the app crashes i don't know what's wrong with the code it compiles correctly, can someone help me out?
this is the logcat window:
11-04 23:48:20.249 4534-4534/? I/zygote: Not late-enabling -Xcheck:jni (already on)
11-04 23:48:20.258 4534-4534/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
11-04 23:48:20.480 4534-4534/com.example.home.tictactoe I/InstantRun: starting instant run server: is main process
11-04 23:48:20.845 4534-4534/com.example.home.tictactoe D/AndroidRuntime: Shutting down VM
11-04 23:48:20.851 4534-4534/com.example.home.tictactoe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.home.tictactoe, PID: 4534
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.home.tictactoe/com.example.home.tictactoe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()' on a null object reference
at com.example.home.tictactoe.MainActivity$1pawn.hideObj(MainActivity.java:45)
at com.example.home.tictactoe.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
and this is my MainActivity.java file
package com.example.home.tictactoe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public void clickButton(View view){
Log.i("test","working");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
class pawn{
int resID = 0;
ImageView object2 = (ImageView) findViewById(resID);
public void showObj()
{
object2.animate().alpha(1f).setDuration(1000);//add code here to change alpha of object
}
public void hideObj()
{
object2.animate().alpha(0f).setDuration(1000);
}
}
final pawn x_11 = new pawn();
final pawn zero_11 = new pawn();
x_11.resID = R.id.x11;
zero_11.resID=R.id.zero11;
x_11.hideObj();
}
}
See picture:
ImageView object2 = (ImageView) findViewById(resID); is called when your pawn object created. At this point you've not set resId for your object yet so it will be 0. This cause object2 to null.
You can change your class like this:
class pawn {
int resID = 0;
ImageView object2;
public pawn(int resID) {
this.resID = resID;
object2 = (ImageView) findViewById(resID)
}
public void showObj()
{
object2.animate().alpha(1f).setDuration(1000);//add code here to change alpha of object
}
public void hideObj()
{
object2.animate().alpha(0f).setDuration(1000);
}
}
Then use it
pawn x_11 = new pawn(R.id.x11);
x_11.hideObj();

Switch between fragments with MapView

I have a main_activity with a bottom bar. I am using this bottom bar to navigate between fragments. However, there's this one fragment that's not directly navigatable via that bottom bar. It must be accessible from the fragment with MapView and upon onInfoWindowClick. However, the app crashes whenever I consume the infoWindow. Here's my code
public void onMapReady(GoogleMap googleMap) {
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.tesla);
mMap=googleMap;
for (Location item : array_list) {
String _title = item.getLocation_name();
String _snippet = item.getLocation_address();
LatLng _latLng = new LatLng(item.getLatitude(), item.getLongitude());
final MarkerOptions mMarkerOptions = new MarkerOptions().icon(icon);
mMarkerOptions.position(_latLng).title(_title).snippet(_snippet).flat(true);
Marker marker = mMap.addMarker(mMarkerOptions);
mMarkerHashMap.put(marker, item);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(marker.getPosition())
.zoom(12.0f)
.build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
LocationDetailFragment detailedlocation = new LocationDetailFragment();
detailedlocation.LOCATION = mMarkerHashMap.get(marker);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, detailedlocation);
ft.addToBackStack(null);
ft.commit();
}
});
}
--------- beginning of crash 04-23 19:41:11.380 2573-2573/com.teslaqubitsins.fasih.teslahcm E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.teslaqubitsins.fasih.teslahcm, PID: 2573
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null
object reference
at
com.teslaqubitsins.fasih.teslahcm.LocationDetailFragment.onCreateView(LocationDetailFragment.java:35)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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) 04-23
19:41:11.383 1564-1957/system_process W/ActivityManager: Force
finishing activity com.teslaqubitsins.fasih.teslahcm/.MainActivity
04-23 19:41:11.414 1296-1653/? E/SurfaceFlinger: ro.sf.lcd_density
must be defined as a build property
[ 04-23 19:41:11.456 1564: 3367 D/ ]
HostConnection::get() New Host Connection established 0x87cb5680, tid 3367 04-23
19:41:11.457 1296-1653/? D/gralloc_ranchu: gralloc_alloc: format 1 and
usage 0x900 imply creation of host color buffer 04-23 19:41:11.457
1564-3367/system_process I/OpenGLRenderer: Initialized EGL, version
1.4 04-23 19:41:11.458 1564-3367/system_process D/OpenGLRenderer: Swap behavior 1 04-23 19:41:11.458 1564-3367/system_process
W/OpenGLRenderer: Failed to choose config with
EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 04-23 19:41:11.458
1564-3367/system_process D/OpenGLRenderer: Swap behavior 0 04-23
19:41:11.462 1296-1653/? D/gralloc_ranchu: gralloc_alloc: format 1 and
usage 0x900 imply creation of host color buffer 04-23 19:41:11.476
1296-1653/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900
imply creation of host color buffer 04-23 19:41:11.892
1564-1591/system_process W/ActivityManager: Activity pause timeout for
ActivityRecord{34a233 u0
com.teslaqubitsins.fasih.teslahcm/.MainActivity t141 f} 04-23
19:41:11.921 1296-1962/? D/gralloc_ranchu: gralloc_alloc: format 1 and
usage 0x900 imply creation of host color buffer 04-23 19:41:11.940
1296-1962/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900
imply creation of host color buffer 04-23 19:41:11.951 1296-1962/?
D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply
creation of host color buffer 04-23 19:41:11.968 1296-1426/?
D/PermissionCache: checking android.permission.READ_FRAME_BUFFER for
uid=1000 => granted (252 us) 04-23 19:41:12.025 1296-1426/?
D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x333 imply
creation of host color buffer
Blockquote
package com.teslaqubitsins.fasih.teslahcm;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class LocationDetailFragment extends Fragment {
public static Location LOCATION;
TextView _campusName;
TextView _campusAddress;
public LocationDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_location_detail, container, false);
_campusName = (TextView) getView().findViewById(R.id.campus_name);
_campusAddress = (TextView) getView().findViewById(R.id.campus_address);
_campusName.setText(LOCATION.getLocation_name());
_campusAddress.setText(LOCATION.getLocation_address());
return view;
}
public void onClick_call(View view) {
dialPhoneNumber(LOCATION.getLocation_phone());
}
public void dialPhoneNumber(String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber));
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(intent);
}
}
}
04-23 19:58:11.735 6856-6856/com.teslaqubitsins.fasih.teslahcm
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.teslaqubitsins.fasih.teslahcm, PID: 6856
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null
object reference
at
com.teslaqubitsins.fasih.teslahcm.LocationDetailFragment.onCreateView(LocationDetailFragment.java:35)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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) 04-23
19:58:12.507 2006-2282/com.google.android.gms.persistent W/GCoreFlp:
No location to return for getLastLocation() 04-23 19:58:42.534
2134-2214/com.google.android.googlequicksearchbox:search
W/GmsLocationProvider: Error removing location updates: 16
Instead of:
_campusName = (TextView) getView().findViewById(R.id.campus_name);
_campusAddress = (TextView) getView().findViewById(R.id.campus_address);
use the fragment's inflated view to get the ID's:
_campusName = (TextView) view.findViewById(R.id.campus_name);
_campusAddress = (TextView) view.findViewById(R.id.campus_address);
the exception occurs as your getView() returns null, it is not associated with the fragment's View. In fragment You have to always use the inflated view's reference.

NullPointerException (GameActivity does not open)

Please check whats the problem with my code here :
Main Activity :
I'm using Android Studio. Import statements are managed for me. It won't be necessary to write them here
public class MainActivity extends Activity implements View.OnClickListener {
SharedPreferences prefs;
String dataName = "MyData";
String intName = "MyString";
int defaultInt = 0;
public static int highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.btnPlay);
TextView textHighScore = (TextView) findViewById(R.id.textHighScore);
buttonPlay.setOnClickListener(this);
prefs = getSharedPreferences(dataName, MODE_PRIVATE);
highScore = prefs.getInt(intName, defaultInt);
textHighScore.setText("High Score: " + highScore);
}
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, GameActivity.class);
startActivity(intent);
}
}
When I run this application Main Activity is loaded but when I hit play button application closes. I have checked the play button's ID is O.K. I had the same problem in GameActivity but at last I figured out that the problem was with the ID but this time I think problem is with the this I used in Intent();. Activity fails to load.
Exception :
06-24 01:34:05.196 12826-12826/com.cruzerblade.memorygame E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cruzerblade.memorygame, PID: 12826
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cruzerblade.memorygame/com.cruzerblade.memorygame.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
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 invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
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) 
Please help me out! It took me too much time still I couldn't figure out the problem.
Quoting from your logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
This last line is the only line in the trace that is your code:
Look on line 55 of GameActivity.java. It is calling loadAnimation. There is something wrong with the animation it is trying to load (probably a missing resource ID, but it could also be a null or invalid context argument for loadAnimation.)

Categories

Resources