How can I start another activity with putextra class objects? - android-studio

I want to start another activity with some set class object like NavigationViewOptions.
My code:
public NavigationViewOptions options;
options=NavigationViewOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(false)
.navigationListener(MainActivity.this)
.build();
Intent navigationActivity=new Intent(MainActivity.this,NavigationActivity.class);
navigationActivity.putExtra("navigationOptions", options); startActivity(navigationActivity);
And what I got build error "no suitable method for putextra"
Then I tried (Parselable)options or (Serializable)options like below
navigationActivity.putExtra("navigationOptions", (Parcelable) options);
navigationActivity.putExtra("navigationOptions", (Serializable) options);
I got build successful. But when I was running app on device, I got errors
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mapbox_document, PID: 18374
java.lang.ClassCastException: com.mapbox.services.android.navigation.ui.v5.AutoValue_NavigationViewOptions cannot be cast to android.os.Parcelable
at com.example.mapbox_document.MainActivity$1.onClick(MainActivity.java:236)
at android.view.View.performClick(View.java:7346)
at android.widget.TextView.performClick(TextView.java:14275)
at android.view.View.performClickInternal(View.java:7312)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27794)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7100)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
I tried to add parcelable method to mainactivity class extends but I failed.
What is the method I have to follow?

For passing non primitive types via an intent between activities, you have 2 options:
Make the object parcelable or make it serializable.
In order for it to be parcelable (a parcel can be created from it), the NavigationViewOptions class would have to implement the Parcelable interface.
In order for it to be serializable (convertable from and to byte stream) the NavigationViewOptions class would have to implement the Serializable interface.
For reference have a look here: https://www.techjini.com/blog/passing-objects-via-intent-in-android/
Checking the implementation of NavigationViewOptions, I cannot find the implementation of neither the serializable nor the parcelable interface. Therefore passing the NavigationViewOptions object via an intent is not straightforward.
Recommendation:
I would recommend you to pass the primitive objects, that you use to build the NavigationViewOptions object with, instead of passing the object itself. The route object can be passed via an intent, as you can convert it to String. The other object is a Boolean. So this will work.

Related

Object can be used as class name even though a predefined Object class exists

i have created a class X in com.x package, since X class is there it didn't allowed me to create a class with name 'X' again.
now, i created a package java.lang and created a Object class with main method
its created, how it is allowing to create a class with same name and same package which is already exists.
when i try to execute it has thrown the below error
Error: Main method not found in class java.lang.Object, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
why is it happening? i know its pointing to predefined Object class and it didn't find main method.
thanks.

Error on SimpleTemplateEngine embedded in Java: Could not instantiate custom Metaclass for class: java.util.ArrayList

I have a app where my users input a HTML template with SimpleTemplateEngine notation, and execute this template with code above, in a Java Class:
new SimpleTemplateEngine().createTemplate(templateStr).make(map).toString()
and I obtain this error:
groovy.lang.GroovyRuntimeException: Could not instantiate custom Metaclass for class: java.util.ArrayList. Reason: java.lang.NoSuchMethodException: groovy.runtime.metaclass.java.util.ArrayListMetaClass.<init>(groovy.lang.MetaClass)
I observe that error occurrs in a loop in a java.util.ArrayLIst in a JPA Entity loaded by Hibernate:
<%for(int k=0; k< Registro[i].listUsers.size();k++){%>
HTML CODE
<%}%>
Anyone can help me? I no have more ideas about this error...
Thanks!
I'm guessing that the part Registro[i] is for getting the value of a static property which name is held under the variable i (or at least that is what will happen) unless the getAt(String) method has been overloaded on Registro.
Either way I also guess that returns an object that has a listUsers property that should be at least a Collection.
Maybe the problem is with the initialization of said listUsers property.
Some Registro code could be used for better understanding.

cast closure map to object with a private constructor in groovy

I am using groovy to create some mock classes for a test case. I am basically creating dummy objects where all the methods return null so that i can run my testcase.
I am using the following syntax:
MessageFactory.instance = ["getMessage": {a,b,c,d -> "dummy"}] as MessageFactory
So here i am trying to overwrite the singleton instance with my on fake factory object. The problem is that MessageFactory's constructor happens to be a private method. This gives me an illigal access exception when i run the code above. Is there a away i can create a proxy in groovy and overcome the private constructor issue?
If you have access to the MessageFactory, and are willing to modify it, then you use the standard dependency-injection solution, as detailed here: mock singleton
..Though it's not particularly Groovy.
Otherwise, the best workaround I've found is to override the method(s) on the singleton instance itself, like so:
#Singleton
class Test{
def method(){"Unmocked method called"}
}
def test = Test.instance
test.metaClass.method = {-> null}
test.method() // Now returns null
Naturally, as a singleton, this instance doesn't change (at least in theory)... So, overriding methods in this manner is effectively global.
Edit: Or you can use GMock, which supports constructor mocking (among other things).

SPPersistedObject and List<T>

I want sharepoint to "persist" a List of object
I wrote a class SPAlert wich inherit from SPPersistedObject :
public class SMSAlert: SPPersistedObject
{
[Persisted]
private DateTime _scheduledTime;
[Persisted]
private Guid _listId;
[Persisted]
private Guid _siteID;
}
Then I wrote a class wich inherit from SPJobDefinition an add a List of my previous object:
public sealed class MyCustomJob: SPJobDefinition
{
[Persisted]
private List<SMSAlert> _SMSAlerts;
}
The problem is :
when I call the Update method of y MyCustomJob:
myCustomJob.Update();
It throw an exception :
message :
An object in the SharePoint
administrative framework, depends on
other objects which do not exist.
Ensure that all of the objects
dependencies are created and retry
this operation.
stack
at
Microsoft.SharePoint.Administration.SPConfigurationDatabase.StoreObject(SPPersistedObject
obj, Boolean storeClassIfNecessary,
Boolean ensure) at
Microsoft.SharePoint.Administration.SPConfigurationDatabase.PutObject(SPPersistedObject
obj, Boolean ensure) at
Microsoft.SharePoint.Administration.SPPersistedObject.Update()
at
Microsoft.SharePoint.Administration.SPJobDefinition.Update()
at
Sigi.Common.AlertBySMS.SmsAlertHandler.ScheduleJob(SPWeb
web, SPAlertHandlerParams ahp)
inner exception
An object in the SharePoint
administrative framework depends on
other objects which do not exist.
The INSERT statement conflicted with
the FOREIGN KEY constraint
"FK_Dependencies1_Objects".
The conflict occurred in database
"SharePoint_Config, table
"dbo.Objects", column 'Id'. The
statement has been terminated.
Can anyone help me with that??
Ensure that your class is marked with a unique GUID, using [System.Runtime.InteropServices.Guid("GUID")] and ensure that the persisted object's class has a default constructor. Hope this help.
Both the above suggestions are very important, adding a Guid attribute and ensuring you have a default constructor. Not only for your persisted SMSAlert object, but make sure you have these for your SPJobDefinition as well.
Additionally, if you create collections of SPPersistedObject you have to ensure that each object in the collection is also updated. A better alternative is to make SMSAlert an SPAutoSerializingObject. Collections of SPAutoSerializingObject, as the name implies, are automatically serialized.
For more information on persisted objects see this extremely useful post:
http://www.chaholl.com/archive/2011/01/30/the-skinny-on-sppersistedobject-and-the-hierarchical-object-store-in.aspx
Did you specify the default constructor for SMSAlert?

How can I have JAXB call a method after it has completed unmarshalling an XML file into an object?

I am using JAXB to unmarshall an XML file into a Java object -- standard stuff. Once JAXB has completed this, I'd like a method to be called on the newly created object.
Is there a mechanism to do this? I'd prefer the object, not an external entity, do this to keep construction in one place.
Thanks.
You can simple add the following method to your object definition:
void afterUnmarshal(Unmarshaller u, Object parent) {
...
}
It will be called once the current object has been completely deserialized.
See also the documentation about unmarshalling callbacks
In addition to the Unmarshaller.Listener you can add the following methods to your domain model classes themselves.
public void beforeUnmarshal(Unmarshaller unmarshaller, Object parent)
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent)
From:
http://java.sun.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.Listener.html
To be able to execute code after unmarshalling took place, you need
an Unmarshaller-Listener
However, I'm not sure, if the listener is invoked after the
properties are set or before.
NOTE: The listener is available since JAXB-2.0 (JDK-6)

Resources