This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wanted to load an image into an imageview of the app from my mobile storage. Just to be sure, I kept the image in both internal and external storage. But while compiling, I am getting a null pointer exception. I also placed the same image in drawable folder and tried to set the imageview from there. But faced the same issue. Can anyone help me here!. I am adding the code snippets that I tried.
Method-1:
File imageFile = new File(Environment.getExternalStorageDirectory(),"golden_eagle.jpg");
if(imageFile.exists()) {
Log.v(LOGTAG, "Image file exists");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap outputImageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView.setImageBitmap(outputImageBitmap);
}
Method-2:
Bitmap bitimage;
bitimage = BitmapFactory.decodeResource(getResources(), R.drawable.golden_eagle);
if(bitimage == null)
Log.v(LOGTAG,"bitimage is empty");
else
Log.v(LOGTAG,"bitimage is not empty");
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView.setImageBitmap(bitimage);
Method-3:
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
int resid = getResources().getIdentifier("golden_eagle","drawable",getPackageName());
imageView.setImageResource(resid);
//imageView.setImageResource(R.drawable.golden_eagle);
Method 4:
//Some class extending AppCompatActivity
asyncTask.execute();
//some asyncTask
onpostExecute(){
//Method:1
//Method:2
//Method:3
}
All the above methods ended with same compilation error
12-24 20:16:42.520 1349-1349/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.home.BequestProto, PID: 1349
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.home.BequestProto/com.example.home.BequestProto.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
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: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.example.home.BequestProto.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:6582)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
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)
The Error is occurring at at the line where I am setting image to imageview.
I know that It is a null pointer exception because some where I forgot to initialize the required object. I want to know which one.
"Method 4:" Shows that you are executing with async task. I guess the layout changed and it tryed to set the image after.
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
if (imageView != null)
imageView.setImageBitmap(outputImageBitmap);
This will set the image only if View is present
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
This would appear to be from "Method-3", where you are calling setImageResource().
This error means that this line is where your problem lies:
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView is null in all four cases, because findViewById() cannot find this widget.
Double check if you have ImageView with id sample_image. It's not found in your layout
Related
I am working on an App that use camera for face recognition. But i have some problem when i resume my app the the app always crash.
This is my code Onresume Activity:
#Override
public synchronized void onResume() {
// LOGGER.d("onResume " + this);
super.onResume();;
handlerThread = new HandlerThread("inference");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
This is my code in CameraActivity:
CameraActivity.java
And this is the class that i used for recognize the face that extends from cameraActivity:
Detector Activity
I forgot to show the erorr:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.samples.flironecamera, PID: 30923
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.samples.flironecamera.tracking.MultiBoxTracker.trackResults(java.util.List, long)' on a null object reference
at com.samples.flironecamera.DetectorActivity.updateResults(DetectorActivity.java:728)
at com.samples.flironecamera.DetectorActivity.onRestart(DetectorActivity.java:761)
at android.app.Instrumentation.callActivityOnRestart(Instrumentation.java:1443)
at android.app.Activity.performRestart(Activity.java:8067)
at android.app.ActivityThread.performRestartActivity(ActivityThread.java:5188)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:243)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2270)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8125)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
And Another Erorr
java.lang.RuntimeException: Unable to resume activity {com.samples.flironecamera/com.samples.flironecamera.DetectorActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.startPreview()' on a null object reference
In my layout applications I have a card view where each card contains a representations of an application.
In each card there are: the name of an applications, a description and his icon.
#Override
public void onBindViewHolder(#NonNull final AdapterForCard.ViewHolder holder, final int position) {
holder.iv.setImageDrawable(myCards.get(position).getIcon());
holder.titleView.setText(myCards.get(position).getTitle());
holder.descView.setText(myCards.get(position).getInfo());
holder.cv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(holder.cv.getContext(), "Cliccked card: "+(holder.titleView.getText()), Toast.LENGTH_SHORT).show();
Context context = v.getContext();
Intent i = new Intent(context,DetailsAppActivity.class);
//First Convert Image into Byte Array
// and then pass into Intent and in next activity
// get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView
// holder.iv.getId_ 2131296339 v.getId_ 2131296348.
//
int id1 = holder.iv.getId();
int id2 = v.getId();
int id3 = R.id.iconView;
System.out.println("id1_ "+id1);
System.out.println("id2_ "+id2);
System.out.println("id3_ "+id3);
Bitmap btm = BitmapFactory.decodeResource(v.getResources(),id1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
System.out.println("bitmap is null ? "+(btm==null));
btm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
i.putExtra("title", ""+holder.titleView.getText());
i.putExtra("title", ""+holder.titleView.getText());
i.putExtra("icon",byteArray);
context.startActivity(i);
}
});
}
I want pass the three date to my DetailsActivity, but i have the follow error:
id1_ 2131296339
id2_ 2131296348
id3_ 2131296339
bitmap is null ? true
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.salvatorefiorilla.systemmonitor, PID: 6151
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.salvatorefiorilla.systemmonitor.AdapterForCard$1.onClick(AdapterForCard.java:90)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19858)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
How to set id correctly?
Update 2
As you told that you don't have resource id. You have application package, and have to get application icon, so you can pass package name of that app. And in next activity just get application icon.
Important Edit
I did not notice that you are using Drawable object instead of using an int id. There is no need to store drawable objects in List. So do the following.
First change type of icon as int (Resource id).
list.setIconId(R.drawable.ic_launcher)
BitmapFactory.decodeResource(getResources(), myCards.get(position).getIconId());
set ImageView image by below method.
Old solution is also edited for same.
holder.iv.setImageResource(myCards.get(position).getIconId());
Solution
Just change holder.iv.getId(); with myCards.get(position).getIconId()
Bitmap btm = BitmapFactory.decodeResource(v.getResources(),myCards.get(position).getIconId());
Reason of crash
Because holder.iv.getId() returns you ImageView id NOT drawable resource id.
Suggestion (must use)
Pass resource id instead of passing bitmap array. There is no need to pass byte array of bitmap.
i.putExtra("icon",myCards.get(position).getIconId());
in next activity
imageView.setImageResource(getIntent().getIntExtra("icon",0));
Isn't it simple :)
well your stream is null because you are giving id instead of position. use this one
mCard.get(position).getIcon()
I am trying to scale a bitmap image. However, when I scale it, I get an error. This is my full stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nodomain.speedtap2, PID: 3113
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nodomain.speedtap2/com.nodomain.speedtap2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3322)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3418)
at android.app.ActivityThread.access$1100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Bitmap.setHasAlpha(boolean)' on a null object reference
at android.graphics.Bitmap.createBitmap(Bitmap.java:979)
at android.graphics.Bitmap.createBitmap(Bitmap.java:946)
at android.graphics.Bitmap.createBitmap(Bitmap.java:877)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:753)
at com.nodomain.speedtap2.MainMenu.<init>(MainMenu.java:47)
at com.nodomain.speedtap2.MainActivity$GameView.<init>(MainActivity.java:54)
at com.nodomain.speedtap2.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3418)
at android.app.ActivityThread.access$1100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) `
But didn't I already make a Bitmap with BitmapFactory.decodeResource(...)? This is my code:
public class MainMenu {
private Bitmap playButton;
public MainMenu (Context context) {
playButton = BitmapFactory.decodeResource(context.getResources(), R.drawable.play_button);
float aspectRatio = 421/475;
int playButtonWidth = MainActivity.screenX / 5;
int playButtonHeight = (int)(MainActivity.screenX / (aspectRatio));
playButton = Bitmap.createScaledBitmap(playButton, playButtonWidth, playButtonHeight, false);
}
Maybe I'm not fully understanding the error...
public class MainMenu {
public static Bitmap playButton;
Context mcontext;
public static Bitmap MainMenu(Context context) {
playButton = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
float aspectRatio = 421/475;
int playButtonWidth = MainActivity.screenX / 5;
int playButtonHeight = (int)(MainActivity.screenX / (aspectRatio));
playButton = Bitmap.createScaledBitmap(playButton, 100, 100, false);
return playButton;
}
}
the issue is that your playButtonWidth ,playButtonHeight returns null. so it crash please share how you getting MainActivity.screenX , try this
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My problem is that one specific activity in my app can't be launched for some reason, and it throws:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
All other launching code that looks like this work fine, the problem is ONLY when I'm launching Player1. The class surely exists, and I can't understand what is the problem.
I'm launching an activity called Player1 from an activity called ChooseLevel. When some button is pressed, the call is:
Intent intent = new Intent(ChooseLevel.this, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
The logs show that the error is in: Player1.onCreate(Player1.java:50)
The code in line Player1:50 is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
changeIndex = 0;
cards = new ArrayList<Card>(8);
score = (TextView) findViewById(R.id.score_text);
message = (TextView) findViewById(R.id.msg_text);
timer = (TextView) findViewById(R.id.timer);
timer.setText(String.valueOf(definitions.TIMER_START)); # LINE 50
Bundle b = getIntent().getExtras();
...
}
When this launching code runs, I get this in my logs:
33:04.338 18302-18302/com... D/AndroidRuntime: Shutting down VM
01-18 10:33:04.338 18302-18302/com... E/AndroidRuntime: FATAL EXCEPTION: main
Process: com..., PID: 18302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.../com....Player1}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com....Player1.onCreate(Player1.java:50)
EDIT:
I found my answer, it had to do with some object that I had in my Player1.onCreate() method. In a wierd way, android-studio raised the exception regarding getClass(). If someone knows why this happend, please share :)
use context,getApplicationContext()orgetActivity()`
Intent intent = new Intent(context, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
i try to add onClick this button then create contact in database
Here is code i try to add it to main_fragment
final Button addBtn = (Button) view.findViewById(R.id.btnadd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri imageUri = Uri.parse("android.resource://org.intracode.contactmanager/drawable/no_user_logo.png");
import_fragment.Contact contact = new import_fragment.Contact(dbHandler.getContactsCount(), String.valueOf(nametxt.getText()), String.valueOf(phoneTxt.getText()), String.valueOf(emailTxt.getText()), String.valueOf(addressTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged(); // Error in this line
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(nametxt.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}
});
When i press this button in my app, 'app has stopped working'
Here is my logcat
01-22 08:31:04.014 29398-29398/com.al3almya.users.al3almya E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.al3almya.users.al3almya, PID: 29398
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
at com.al3almya.users.al3almya.main_fragment$1.onClick(main_fragment.java:77)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Either the contactAdapter is not initialized(contactAdater is null) or the object on which the adapter is set is null.
Make sure you have initialized all the variables. Else try running dubugger.
It appears that the variable contactAdapter has not been set.