Null Pointer Exception error when calling method - exception

i have no idea what's wrong with what i am doing. It's supposed to print all patients who visited on a specific date but it keeps on throwing the null pointer error. It happens when I call on the printPatientsOnDate method.
code on the main/UI class
public void printPatientsOnDate() throws ParseException
{
System.out.print("Enter the date(mm-dd-yyyy): ");
Date dt = new SimpleDateFormat("MM-dd-yyyy").parse(sc.nextLine());
for(Patient i : app.getPatientsOnSpecDate(dt))
{
System.out.println(i.getName());
}
}
code on the clinic class
public ArrayList<Patient> getPatientsOnSpecDate(Date date)
{
ArrayList<Patient> patients = null;
for(Patient i : patientList)
{
if(i.searchDates(date)!=null)
{
patients.add(i);
}
}
return patients;
}
null pointer error code
Exception in thread "main" java.lang.NullPointerException
at pkg.Pagamutan.Clinic.UI.printPatientsOnDate(UI.java:81)

Your ArrayList<Patient> patients reference variable is null. Currently it doesn't point to any ArrayList<Patient> object .
ArrayList<Patient> patients = null;
And when you trying to invoke .add() on that null reference it throws NullPointerException.
Thrown when an application attempts to use null in a case where an object is required.
These include:
Calling the instance method of a null object.
.............
You need to instantiate an ArrayList<Patient> object before invoking .add() on it.
ArrayList<Patient> patients = new ArrayList<Patient>();
Or better use List<Patient> as the reference type :
List<Patient> patients = new ArrayList<Patient>();

Related

Null pointer exception due to calling a function in constructor and then creating a new object of that class

How to write j-unit for a class which calls a super function(non static) due to which a null pointer exception is happening.
public myActivity(Context context) {
super(context, android.R.style.Theme_Light_NoTitleBar_Fullscreen);
mContext = context;
Window window=getWindow();
window.dosomething();
}
Now when creating a spy object
Myactivity activity = spy(new Myactivity (mContext));
Its throwing a null pointer error in getWindow()
where getWindow() is a function of Dialog.class
getwindow is android code
public #Nullable Window getWindow() {
return mWindow;
}
I have to create the window in constructor .
Can you please help in removing the null pointer error

'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

I need to store my IEnumerable of objects into Tempdata for my next request from the server. Since Tempdata cannot store Objects I found the below extenstion method to serialize and deserialize before putting into Tempdata. After this method, I am able to store my object to Tempdata. But, when I am trying to use it in my next action method, I am facing following runtime error. "Cannot deserialize the current JSON array". Please help me to fix this issue.
my code :
public ActionResult GetData(){
List<EmployeeViewModel> webform =
_service.GetListOfWebformData(id).ToList();
TempData.Put("webform", webform); }
public ActionResult ShowData(){
var WebformData = TempData.Get<EmployeeViewModel>("webform");
return View(WebformData);}
Extension method i have used for Tempdata is below
public static class TempDataExtensions
{
public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
object o;
tempData.TryGetValue(key, out o);
return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
}
}

Findbugs reports Load of known null value while validating constructor argument

Upon scanning following code with findbugs, it reports Dodgy code:NP: Load of known null value in new ....(at line where new Exception is thrown)
Sometimes it is required to check null before initializing an object.
Why is this considered "dodgy"??
public class Employee{
#Valid
private Department dept;
#JsonCreator
public Employee(#JsonProperty(value = "department", required = true) Department aDepartment)
throws EmpServiceException{
if (aDepartment == null) {
throw new EmpServiceException(aDepartment, "Invalid Request");
}
this.dept= aDepartment;
}
My guess is that FindBugs is pointing out that the line where you throw the exception
throw new EmpServiceException(aDepartment, "Invalid Request");
is equivalent to
throw new EmpServiceException(null, "Invalid Request");
and wants you to use the latter. Is the first argument for that EmpServiceException constructor annotated with #NonNull?

Property StackTrace cannot be assigned, it's read only

I have my Exception handler, which is used for enterprise library exception handling.
This handler contains method HandleException:
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
Exception wrap = new Exception();
wrap.StackTrace = exception.StackTrace;
return wrap;
}
When I try to assign received exception.StackTrace property to my variable wrap, I get Error:
property or indexer 'System.Exception.StackTrace' cannot be assigned to -- it is read only
How I can assign it to my variable?
This is typically what I've seen.
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
//Do something with the Exception.
return exception;
}
or
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
ApplicationException appEx = new ApplicationException(exception.Message, exception);
return appEx ;
}

LINQ to SQL validate all fields, not just stop at first failed field

I just started using LINQ to SQL classes, and really like how this helps me write readable code.
In the documentation, typical examples state that to do custom validation, you create a partial class as so::
partial class Customer
{
partial void OnCustomerIDChanging(string value)
{
if (value=="BADVALUE") throw new NotImplementedException("CustomerID Invalid");
}
}
And similarly for other fields...
And then in the codebehind, i put something like this to display the error message and keep the user on same page so to correct the mistake.
public void CustomerListView_OnItemInserted(object sender, ListViewInsertedEventArgs e)
{
string errorString = "";
if (e.Exception != null)
{
e.KeepInInsertMode = true;
errorString += e.Exception.Message;
e.ExceptionHandled = true;
}
else errorString += "Successfully inserted Customer Data" + "\n";
errorMessage.Text = errorString;
}
Okay, that's easy, but then it stops validating the rest of the fields as soon as the first Exception is thrown!! Mean if the user made mode than one mistake, she/he/it will only be notified of the first error.
Is there another way to check all the input and show the errors in each ?
Any suggestions appreciated, thanks.
This looks like a job for the Enterprise Library Validation Application Block (VAB). VAB has been designed to return all errors. Besides this, it doesn't thrown an exception, so you can simply ask it to validate the type for you.
When you decide to use the VAB, I advise you to -not- use the OnXXXChanging and OnValidate methods of LINQ to SQL. It's best to override the SubmitChange(ConflictMode) method on the DataContext class to call into VAB's validation API. This keeps your validation logic out of your business entities, which keeps your entities clean.
Look at the following example:
public partial class NorthwindDataContext
{
public ValidationResult[] Validate()
{
return invalidResults = (
from entity in this.GetChangedEntities()
let type = entity.GetType()
let validator = ValidationFactory.CreateValidator(type)
let results = validator.Validate(entity)
where !results.IsValid
from result in results
select result).ToArray();
}
public override void SubmitChanges(ConflictMode failureMode)
{
ValidationResult[] this.Validate();
if (invalidResults.Length > 0)
{
// You should define this exception type
throw new ValidationException(invalidResults);
}
base.SubmitChanges(failureMode);
}
private IEnumerable<object> GetChangedEntities()
{
ChangeSet changes = this.GetChangeSet();
return changes.Inserts.Concat(changes.Updates);
}
}
[Serializable]
public class ValidationException : Exception
{
public ValidationException(IEnumerable<ValidationResult> results)
: base("There are validation errors.")
{
this.Results = new ReadOnlyCollection<ValidationResult>(
results.ToArray());
}
public ReadOnlyCollection<ValidationResult> Results
{
get; private set;
}
}
Calling the Validate() method will return a collection of all errors, but rather than calling Validate(), I'd simply call SubmitChanges() when you're ready to persist. SubmitChanges() will now check for errors and throw an exception when one of the entities is invalid. Because the list of errors is sent to the ValidationException, you can iterate over the errors higher up the call stack, and present them to the user, as follows:
try
{
db.SubmitChanges();
}
catch (ValidationException vex)
{
ShowErrors(vex.ValidationErrors);
}
private static void ShowErrors(IEnumerable<ValidationResult> errors)
{
foreach(var error in errors)
{
Console.WriteLine("{0}: {1}", error.Key, error.message);
}
}
When you use this approach you make sure that your entities are always validated before saving them to the database
Here is a good article that explains how to integrate VAB with LINQ to SQL. You should definitely read it if you want to use VAB with LINQ to SQL.
Not with LINQ. Presumably you would validate the input before giving it to LINQ.
What you're seeing is natural behaviour with exceptions.
I figured it out. Instead of throwing an exception at first failed validation, i store an error message in a class with static variable. to do this, i extend the DataContext class like this::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for SalesClassesDataContext
/// </summary>
public partial class SalesClassesDataContext
{
public class ErrorBox
{
private static List<string> Messages = new List<string>();
public void addMessage(string message)
{
Messages.Add(message);
}
public List<string> getMessages()
{
return Messages;
}
}
}
in the classes corresponding to each table, i would inherit the newly defined class like this::
public partial class Customer : SalesClassesDataContext.ErrorBox
only in the function OnValidate i would throw an exception in case the number of errors is not 0. Hence not attempting to insert, and keeping the user on same input page, without loosing the data they entered.