This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
-edit 2. Tested this on my mobile works as intended. Stupid android avd
I am getting a error and i am not quite sure how to fix it. I could remove the need for caching the image but that would increase the bandwidth needed for the application.
My current code should work but it is throwing a NullPointerException
here is the error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference
at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:232)
at com.program.programmy.application.FileCache.<init>(FileCache.java:18)
and this is the code causing the problem is the one surrounded by ** line 18
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"ParseListViewImgTxt");
else
**cacheDir = context.getCacheDir();**
if (!cacheDir.exists())
cacheDir.mkdirs();
}
if someone could help out with this one little thing my program should work no problem. cheers
-Edit
This is only when i try to leave the list intent to look at a single object. Here is some more code from the area that prompts the error
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SingleItemView.class);
context.startActivity(intent);
}
});
Also here is a link to something similar that i am doing except no one is having the problem i am
Whenever your constructor is called, you are not sending any object in context.
Exception occurred as context object is null, and you are calling getCacheDir() method on it.
If you have problem in getting context object. Please read top voted answer in following link:
Static way to get 'Context' on Android?
Related
I am starting EditCardActivity from MainActivity.
The app crashes first time and Android system shows an alert to "Open App Again".
When I reopen the app, it works as expected.
I have seen many answers on this site and I have done following according to those answers but it didn't work.
I have called the setContentView() inside onCreate() method before calling findViewByID().
I have verified that the ID I am passing in findViewByID() is spelled correctly.
I also tried to make the EditText a class member too and initialize it in onCreate() method.
I also tried using onStart(), onPostCreate() methods too.
I feel that the View has not been loaded when I am trying to call it and thus findViewByID() returns null. Hence I tried using Thread.sleep(1000) to give it 1 second to load but still same issue.
Here's the part of code that is having problem.
// MainActivity.java
public void editCard(View v) {
Intent i = new Intent(this, EditCardActivity.class);
startActivity(i);
}
<!--activity_edit_card.xml-->
...
<EditText
android:id="#+id/add_card_category_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin"
android:ems="10"
android:hint="#string/add_card_category_et_hint"
android:inputType="text"
android:textSize="#dimen/font_size" />
...
// EditCardActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_card);
showContents();
}
private void showContents() {
EditText editCardCategoryET = findViewById(R.id.add_card_category_et);
editCardCategoryET.setText(currentCard.getCategory()); // This line is throwing NullPointerException
}
Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Edit:
I got what was causing the error.
I was referring to the add_card_category_et instead of edit_card_category_et.
The former view belonged to the different layout file of another Activity of my application.
I am sorry I couldn't catch this small error.
Although small, it made me stuck for 3 days.
Anyway thanks for your answers and comments.
Because editCardCategoryET cant find any value. So it throws Exception. It can be solve by add extra character by adding " " . Then app will not crush. editCardCategoryET.setText(" "+currentCard.getCategory()); .
Also you can handle it in a try(), catch() method.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm new to app development. I can run my application from Android Studio on a real device. I followed a tutorial. Everything ran until I wrote the code that sums both numbers and I can't seem to fix it.
Here is the error message I get along with the code in Main.
(Click image to enlarge)
I don't understand most of this, and I can't continue without running the app. I don't run it on a virtual machine because it takes forever to load.
You should care about input must be number by adding this to both EditText in xml
android:inputType="number"
also add if statement to check EditText not have Null Value(not empty), you can use such code to check if EditText empty
int num1,num2;
if(firstNumEditText.getText().toString().isEmpty()) {
// is empty
return;
} else {
// is not empty
num1 = Integer.parseInt(firstNumEditText.getText().toString());
}
if(secondEditText.getText().toString().isEmpty()) {
// is empty
return;
} else {
// is not empty
num2 = Integer.parseInt(secondEditText.getText().toString());
}
resultTextView.setText(String.valueOf(num1+num2);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When I launch my app this problem shows. This is my Java code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
ImageView imageView = new ImageView(this);
imageView.setBackgroundColor(Color.WHITE);
SVG svg = SVGParser.getSVGFromResource(getResources(), raw.canel);`
imageView.setImageDrawable(svg.createPictureDrawable());
setContentView(imageView);
}
This is the line where the exception is thrown:
SVG svg = SVGParser.getSVGFromResource(getResources(), raw.canel);
There are two possibilities: either SVGParser is null and therefore has no getSVGFromResource, or raw is null and has no canel member.
If your error is that SVGParser is null, then the problem is that you did not import SVGParser. In this case the solution is to import the package which contains SVGParser, since it is a class and it was not imported, therefore the compiler thinks it is a variable and has not been initialized.
If your error is that raw is null, then the solution is to initialize it. In this case you have missed the part where the variable is being initialized. It is quite possible that you initialize it correctly, but after onCreate is being called, therefore the member is not initialized yet when you try to use it.
We need more information about the problem to give you a more specific solution.
I'm currently working on an Android App and, almost every time I use it, I get a an error. Most of the time it doesn't crash the app, but it is still frustrating that I'm seeing this error. I thought I did a check for it, but I could be wrong. Thanks for the help! The relevant code is below. (It's relevant because the line outside the if statement is throwing the NullPointerException.)
Activity activity;
if(activity == null)
{
activity = new Activity();
}
Intent intent = new Intent(activity, Service.class);
You don't usually instantiate the Activity class in this manner. Please see the documentation on the Android Activity class here:
http://developer.android.com/reference/android/app/Activity.html
You should post some more of the surrounding code, but your problem is that creating new Intent requires a valid Context. Usually you create an Intent within an Activity (or Service or BroadcastReceiver) class so you can just do something like:
Intent intent = new Intent(this, Service.class);
Occasionally you'll create it somewhere else and pass it that valid Context, but you should pretty much never create an Activity by calling the constructor directly. There's a lot of other initialization necessary to make it useful.
As postet previously there is more to initiate for an activity than calling the constructor. Probably you get a null pointer exception deep within the Intent Constructer where it is trying to get some of the Activityinformation usually provided.
If you really want to create a Service, heres a link for starting a Service, but you should really read the whole article and probably some more of the activity lifecycle ressources.
http://developer.android.com/guide/topics/fundamentals/services.html#StartingAService
A similar question was asked here for two times and never there was any answer. Or the answer was: "it is impossible!" Sorry, it is possible too much:
try{
...
// the line that causes the error
LinearLayout cell = (LinearLayout) inflater.inflate(R.layout.channels_list_cell, column);
...
}
catch(Throwable e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); < breakpoint here!
}
At the breakpoint e is null. How can I seek for the error, please? Very possibly it is not the problem of java or Android, but of the Eclipse debugger, that itself needs debugging badly. But what have I to do, except changing to a different IDE? Any ideas? Beforehand grateful.
I have tried Throwable, Exception, RuntimeException. The result is the same.
An attempt to step over breakpoint causes NullPointerException, so, e seems really null at that moment already. Where could it be lost?
Edit:
I bring my gratitude to everybody and +1 to every answerer. It was an Eclipse bug. After restart Eclipse the Exception is not null anymore, it is a normal RuntimeException: Binary XML file line #15: You must supply a layout_width attribute. It would be another problem to be solved, but that one is solved.
If the exception you caught was a NullPointerException, the getMessage() method returns "null" which may be confusing. I know that this has sometimes confused me!
In the debugger, you should be able to select e and see a type and its fields. Also, another way to debug when things get really confusing is to go
e.printStackTrace();
(note - I'm not an Android guru so if this works differently on Android somebody please comment!)
Have you verified whether e is actually null or not? I.e. by adding something like if (e == null) Log.d("Exception is null"). I would then check if the log statement gets triggered both during normal execution and while debugging. If the results are different between the two, it would indicate a VM bug (unlikely, but possible). If the message doesn't get triggered in either case, then it's likely a debugger issue.
A few thoughts on further things you can try to debug the issue:
Try something like jdb and see if you get the same behaviour
You could get a dump of the jdwp communications between the debugger and the device, and see what's going on at that level. Maybe use wireshark or tcpdump and grab the data going over the usb bus to the device.
You could try adding some debug statements to dalvik itself. E.g. grab a copy of AOSP and build an emulator image, and then add some debugging statements to dalvik to try and track down what's going on.
You could attempt to do some sort of scripted jdwp session with the device
You could look at the bytecode (baksmali/dexdump/dedexer), to see if anything looks funny
Android does not always throws exception in a Throwable. It actually drives all the exceptions to the catLog. There you will find details of your exceptions even if in the catch block your exception is null.
You can easily access the catlog console from eclipse and filter to view the errors only
UPDATE:
Your breakpoint should be inside the catch block
I know this question was posted a while ago, and many times too! I fell into this trap yesterday and I thought I'll post what I found.
Problem definition: I used the following code
public class myAppActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try { -- lots of code -- }
catch (Exception ex) {
Log.e ("eTutorPrism Error", "Caught this exception " + ex);
ex.printStackTrace();
}
}
}
Symptom was that 'ex' was always null and resume will give NullPointerException, although the actual exception was an IllegalArgumentException in a call made into another class from the code above.
ISSUE: onCreate() code does not display the exception caught. instead it shows exception = null.
Solution: do NOT use too much processing in onCreate(). Move as much as possible to another thread. So I changed the code to look like the following. voila, it works!!! I can see the actual exception displayed in the Logcat.
public class eTutorPrismAppActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
eTutorPrismTest myTest = new eTutorPrismTest (getApplicationContext());
myTest.start();
}
}
class eTutorPrismTest extends Thread
{
private Context m_AppContext = null;
public eTutorPrismTest (Context appContext)
{
m_AppContext = appContext;
}
public void run ()
{
-- lots of code that needs appContext --
}
}
I am unsure of what causes this -- it could be an Eclipse bug as stated earlier. Regardless of the cause, I did find a workaround that seems to work. I hope it is useful to others as well.
After the exception is caught, assign it to another variable. The assigned variable should contain the correct Exception in the debugger.
SpecificException assignedVar = null;
try {
...
}
catch (SpecificException exc) {
assignedVar = exc; // <-- exc comes up null in the debugger, but assignedVar will be the correct object.
}
Hope this works for others as a workaround.