getting null pointer exception java.lang.Class java.lang.Object.getClass() - java

I implemented Direction API in my app it works perfectly on debug build but getting crash on release build I think it is because of proguard rules what rule I want to add in proguard to resolve this issue.
private void getDirections() {
DirectionsResult result = getDirectionsDetails("place_id:" + pickupPlaceID, "place_id:" + dropPlaceID, TravelMode.DRIVING);
if (result != null) {
addPolyline(result);
positionCamera(result.routes[0]);
}
}
private DirectionsResult getDirectionsDetails(String origin, String destination, TravelMode mode) {
return DirectionsApi.newRequest(geoApiContext).mode(mode).origin(origin).destination(destination).await();
}
private void addPolyline(DirectionsResult results) {
try {
DirectionsRoute[] routes = results.routes;
DirectionsRoute route = routes[0];
EncodedPolyline overviewPolyline = route.overviewPolyline; //getting error here
String encodedPath = overviewPolyline.getEncodedPath();
List<LatLng> decodedPath = PolyUtil.decode(encodedPath);
nGoogleMap.addPolyline(new PolylineOptions().addAll(decodedPath));
}catch (Exception e){
e.printStackTrace();
}
}
java.lang.NullPointerException:
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
System.err com.example.newapp at com.example.newapp.ui.home.HomeFragment.lambda$addPolyline$30(HomeFragment.java:1110)

Related

Sonar is throwing an error Null Pointer Exception should not be caught and how can i fix it?

Sonar qube is giving this error in aem6.5 -- NullPointerException should not be catch
#PostConstruct
protected void init() {
try{
pageManager = resourceResolver.adaptTo(PageManager.class);
requestedPage = pageManager.getPage(rootvalue);
Iterator<Page> siblingPages = requestedPage.listChildren();
while (siblingPages.hasNext()) {
Page siblingPage = siblingPages.next();
if (siblingPage.getProperties().get("hideInNav") == null)
siblingItems.add(siblingPage);
}
} catch (NullPointerException exception) {
log.error("NullPointerException exception occured in SideNavigation " + exception.getMessage());
}
}
can some one help me on this.
#PostConstruct
protected void init() {
if(resourceResolver!=null){
pageManager = resourceResolver.adaptTo(PageManager.class);
assert pageManager != null;
requestedPage = pageManager.getPage(rootvalue);
Iterator<Page> siblingPages = requestedPage.listChildren();
while (siblingPages.hasNext()) {
Page siblingPage = siblingPages.next();
if (siblingPage.getProperties().get("hideInNav") == null)
siblingItems.add(siblingPage);
}
} else {
log.error("exception occurred in SideNavigation ");
}
}
How can we fix this sonar qube error?
requestedPage = pageManager.getPage(rootvalue);
assert requestedPage != null;
Iterator<Page> siblingPages = requestedPage.listChildren();
suggest check this requestedPage before listChildren as well

java.lang.NullPointerException: Cannot read the array length because "<local3>" is null [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am working on a JDA Discord Bot and everytime I run it, I get this exception.
java.lang.NullPointerException: Cannot read the array length because "<local3>" is null
at com.houseofkraft.handler.CommandHandler.scanIndex(CommandHandler.java:42)
at com.houseofkraft.core.DiscordBot.<init>(DiscordBot.java:68)
at com.houseofkraft.Stratos.main(Stratos.java:13)
I was attempting to make a basic Command Handler and here is the code for it:
public void scanIndex(Index index) throws IOException, InvalidLevelException {
String[] commandList = index.indexClass;
for (String classPath : commandList) {
if (classPath.startsWith("com.houseofkraft")) {
String[] classPathSplit = classPath.split("\\.");
String commandName = classPathSplit[classPathSplit.length-1].toLowerCase();
commandPaths.put(commandName, classPath);
DiscordBot.logger.log("Added " + commandName + " / " + classPath + " to path.", Logger.DEBUG);
}
}
}
Index.java:
package com.houseofkraft.command;
public class Index {
public String[] indexClass;
public String[] getIndexClass() {
return indexClass;
}
public Index() {
String[] indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
}
}
I'm not exactly sure why it causes the Exception. Thanks!
EDIT: Here is my DiscordBot Code
public DiscordBot() throws IOException, ParseException, LoginException, InvalidLevelException {
try {
if ((boolean) config.get("writeLogToFile")) {
logger = new Logger(config.get("logFilePath").toString());
} else {
logger = new Logger();
}
logger.debug = debug;
info("Stratos V1");
info("Copyright (c) 2021 houseofkraft");
info("Indexing commands...");
// Add the Commands from the Index
commandHandler.scanIndex(new Index()); // here is the part that I call
info("Done.");
info("Connecting to Discord Instance...");
jda = JDABuilder.createDefault(config.get("token").toString()).addEventListeners(new EventHandler(commandHandler)).build();
if (jda != null) {
info("Connection Successful!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You have a member variable public String[] indexClass in your Index class. In your constructor you create a new variable with
String[] indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
This way your member variable stays uninitialized. Change the code in the constructor to
this.indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
BTW, the member variable should be private, not public, since you want to access it by getter (and than do access it by the getter in the CommandHandler).

NullPointerException in creating ProvisioningJob for headless update of eclipse rcp application

I am implementing headless force update of the eclipse application. I have used the P2Util class from https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fp2_startup.htm but my code is returning null pointer exception at ProvisioningJob job = operation.getProvisioningJob(null); the job object is coming null. Does anyone know the possible reason for this null object.
public class P2Util {
// XXX Check for updates to this application and return a status.
static IStatus checkForUpdates(IProvisioningAgent agent, IProgressMonitor monitor) throws OperationCanceledException {
ProvisioningSession session = new ProvisioningSession(agent);
// the default update operation looks for updates to the currently
// running profile, using the default profile root marker. To change
// which installable units are being updated, use the more detailed
// constructors.
UpdateOperation operation = new UpdateOperation(session);
SubMonitor sub = SubMonitor.convert(monitor,
"Checking for application updates...", 200);
IStatus status = operation.resolveModal(sub.newChild(100));
if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
return status;
}
if (status.getSeverity() == IStatus.CANCEL)
throw new OperationCanceledException();
if (status.getSeverity() != IStatus.ERROR) {
// More complex status handling might include showing the user what updates
// are available if there are multiples, differentiating patches vs. updates, etc.
// In this example, we simply update as suggested by the operation.
ProvisioningJob job = operation.getProvisioningJob(null);
status = job.runModal(sub.newChild(100));//null pointer here
if (status.getSeverity() == IStatus.CANCEL)
throw new OperationCanceledException();
}
return status;
}
}
I am calling this method as follows.
private Integer checkUpdate(final String updateServerURL, final IProvisioningAgent provisioningAgent, ProgressMonitorSplash monitor) {
returnValue = IApplication.EXIT_OK;
final IRunnableWithProgress runnable = new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
P2Util.addRepository(provisioningAgent, updateServerURL);
final IStatus updateStatus = P2Util.checkForUpdates(provisioningAgent, monitor);
if (updateStatus.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
logger.debug("No Updates");
} else if (updateStatus.getSeverity() != IStatus.ERROR) {
logger.debug("Updates applied, attempting restart");
returnValue = IApplication.EXIT_RESTART;
} else {
logger.error(updateStatus.getMessage());
}
}
};
try {
monitor.run(true, runnable);
} catch (final InvocationTargetException e) {
e.printStackTrace();
} catch (final InterruptedException e) {
logger.error("interrupted: " + e.getMessage());
}
return returnValue;
}
where I am creating ProvisingAgent using EclipseContext
final IEclipseContext localContext = EclipseContextFactory.getServiceContext(Activator.getContext());
final IProvisioningAgent provisioningAgent = getService(localContext, IProvisioningAgent.class);
String env = System.getProperty("env").toLowerCase();
String repo = System.getProperty("validUrl." + env);
if ( repo == null ){
repo = System.getProperty("validUrl");
}
if ( repo != null ){
ret = checkUpdate(repo, provisioningAgent, sp);
if ( ret == IApplication.EXIT_RESTART ){
logger.info("Update successful, restarting...");
return ret;
}
}
The javadoc on the UpdateOperation#getProvisioningJob(IProgressMonitor) says:
* #return a job that can be used to perform the provisioning operation. This may be <code>null</code>
* if the operation has not been resolved, or if a plan could not be obtained when attempting to
* resolve. If the job is null and the operation has been resolved, then the resolution result
* will explain the problem.

Java NullPointerException When try to recieve a JSON String from external web page [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to connect my android app to PHP page..
this is AsyncTask class function:
#Override
protected String doInBackground(String... params) {
try {
accountDetails.add(new BasicNameValuePair("Name",params[0]));
JSONObject json = jparser.makeHttpRequest("http://site.page.php","POST",accountDetails);
/*My Problem is here..*/
String registerReport = json.getString("registerReport");
} catch (Exception e) {
error = e.toString();
}
return null;
}
and my php page return this:
{"registerReport":"1"}
And then i got this error:
java.lang.NullPointerException: Attemp to invoke virtual method 'java.lang.Stringorg.json.JSONObject.getString(java.lang.String)' on a null object reference
Your error
java.lang.NullPointerException: Attemp to invoke virtual method
'java.lang.Stringorg.json.JSONObject.getString(java.lang.String)' on a
null object reference
means that you are trying to call the getString() method on a null object.
In your specific case, your object called 'json' is null after this initialization :
JSONObject json =
jparser.makeHttpRequest("http://site.page.php","POST",accountDetails);
To fix this error, you can try if your object is null before to call the getString() method :
#Override
protected String doInBackground(String... params) {
try {
accountDetails.add(new BasicNameValuePair("Name",params[0]));
JSONObject json = jparser.makeHttpRequest("http://site.page.php","POST",accountDetails);
if (json == null) {
return null;
}
String registerReport = json.getString("registerReport");
} catch (Exception e) {
error = e.toString();
}
return null;
}

A class's instance gets destroyed when inner class's method exits?

I am going to use Xposed Bridge API to customize my status bar on my Android phone.
Hooking methods are working pretty well, but there's a problem.
public class WPSModule implements IXposedHookLoadPackage {
final int ICON_SIZE = 100;
FrameLayout FlStatusBar;
...
void HideWidget(FrameLayout FlLayout, String Name)
{
int ViewId = FlLayout.getResources().getIdentifier(Name, "id", "com.android.systemui");
if(ViewId == 0)
{
XposedBridge.log("Failed to find resource " + Name + " on systemui package.");
return;
}
View v = FlLayout.findViewById(ViewId);
if(v == null)
{
XposedBridge.log("v == null with resource " + Name + " on systemui package.");
return;
}
v.setVisibility(View.INVISIBLE);
}
public static TextView TvText = null;
public void handleLoadPackage(final LoadPackageParam LppParam) throws Throwable {
if (!LppParam.packageName.equals("com.android.systemui"))
return;
XposedBridge.log("WPS: SystemUI package found.");
//Hook
findAndHookMethod("com.android.systemui.statusbar.phone.PhoneStatusBarView", LppParam.classLoader, "onFinishInflate", new XC_MethodHook() {
#Override
protected void beforeHookedMethod(MethodHookParam MhpParam) throws Throwable {
// this will be called before the clock was updated by the original method
}
#Override
protected void afterHookedMethod(MethodHookParam MhpParam) throws Throwable {
FlStatusBar = (FrameLayout) MhpParam.thisObject;
}
});
....
}
}
And when I try to use FlStatusBar like this:
HideWidget(FlStatusBar, "notification_lights_out");
It doesn't work. On Xposed's log...
07-31 20:22:09.962 E/Xposed (18737): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.widget.FrameLayout.getResources()' on a null object reference.
Other things which uses FlStatusBar doesn't work too..(ex: FlStatusBar.toString() gives me NullPointerException)

Categories