I followed the sample code realtime database at https://github.com/firebase/quickstart-android/tree/master/database
Everything works find in debug mode. However, if i install the signed apk , download from google play , change the build variant from debug to release in android studio. Signing in will crash.
I have obtained the SHA1 for release and updated the json file accordingly.
I have observed this, do not know if t is relevant.
If i use debug mode to login successfully, the database will change
In release mode, the change do not appear in the database console
from
a:
"test#gmail.com"
b:
"test"
to
email:
"test#gmail.com"
username:
"test"
The error logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: simonhcm.multiplay, PID: 18928
java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.view.View]
at com.a.a.a.d.a(Unknown Source)
at android.support.v7.widget.ek.b(Unknown Source)
at android.support.v7.widget.fb.a(Unknown Source)
at android.support.v7.widget.fb.c(Unknown Source)
at android.support.v7.widget.dj.a(Unknown Source)
at android.support.v7.widget.LinearLayoutManager.a(Unknown Source)
at android.support.v7.widget.LinearLayoutManager.a(Unknown Source)
at android.support.v7.widget.LinearLayoutManager.c(Unknown Source)
at android.support.v7.widget.RecyclerView.J(Unknown Source)
at android.support.v7.widget.RecyclerView.k(Unknown Source)
at android.support.v7.widget.RecyclerView.t(Unknown Source)
at android.support.v7.widget.RecyclerView.c(Unknown Source)
at android.support.v7.widget.ee.run(Unknown Source)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NoSuchMethodException: <init> [class android.view.View]
at java.lang.Class.getConstructor(Class.java:528)
at java.lang.Class.getConstructor(Class.java:492)
at com.a.a.a.d.a(Unknown Source)
at android.support.v7.widget.ek.b(Unknown Source)
at android.support.v7.widget.fb.a(Unknown Source)
at android.support.v7.widget.fb.c(Unknown Source)
at android.support.v7.widget.dj.a(Unknown Source)
at android.support.v7.widget.LinearLayoutManager.a(Unknown Source)
at android.support.v7.widget.LinearLayoutManager.a(Unknown Source)
at android.support.v7.widget.LinearLayoutManager.c(Unknown Source)
at android.support.v7.widget.RecyclerView.J(Unknown Source)
at android.support.v7.widget.RecyclerView.k(Unknown Source)
at android.support.v7.widget.RecyclerView.t(Unknown Source)
at android.support.v7.widget.RecyclerView.c(Unknown Source)
at android.support.v7.widget.ee.run(Unknown Source)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
W/ActivityManager: Force finishing activity simonhcm.multiplay/.MainActivity
W/DropBoxManagerService: Dropping: data_app_crash (1883 > 0 bytes)
I/OpenGLRenderer: Initialized EGL, version 1.4
I/art: Background partial concurrent mark sweep GC freed 6907(456KB) AllocSpace objects, 1(20KB) LOS objects, 28% free, 41MB/57MB, paused 1.419ms total 107.537ms
E/DropBoxTask: null InputStream
java.io.IOException: null InputStream
at wtd.a(:com.google.android.gms:182)
at wtd.b(:com.google.android.gms:124)
at wsi.a(:com.google.android.gms:88)
at com.google.android.gms.stats.service.DropBoxEntryAddedChimeraService.onHandleIntent(:com.google.android.gms:1176)
at bdz.handleMessage(:com.google.android.gms:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148) at android.os.HandlerThread.run(HandlerThread.java:61)
The sign in activity
public class SignInActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "SignInActivity";
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private EditText mEmailField;
private EditText mPasswordField;
private Button mSignInButton;
private Button mSignUpButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
// Views
mEmailField = (EditText) findViewById(R.id.field_email);
mPasswordField = (EditText) findViewById(R.id.field_password);
mSignInButton = (Button) findViewById(R.id.button_sign_in);
mSignUpButton = (Button) findViewById(R.id.button_sign_up);
// Click listeners
mSignInButton.setOnClickListener(this);
mSignUpButton.setOnClickListener(this);
}
#Override
public void onStart() {
super.onStart();
// Check auth on Activity start
if (mAuth.getCurrentUser() != null) {
onAuthSuccess(mAuth.getCurrentUser());
}
}
private void signIn() {
Log.d(TAG, "signIn");
if (!validateForm()) {
return;
}
showProgressDialog();
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signIn:onComplete:" + task.isSuccessful());
hideProgressDialog();
if (task.isSuccessful()) {
onAuthSuccess(task.getResult().getUser());
} else {
Toast.makeText(SignInActivity.this, "Sign In Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void signUp() {
Log.d(TAG, "signUp");
if (!validateForm()) {
return;
}
showProgressDialog();
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUser:onComplete:" + task.isSuccessful());
hideProgressDialog();
if (task.isSuccessful()) {
onAuthSuccess(task.getResult().getUser());
} else {
Toast.makeText(SignInActivity.this, "Sign Up Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void onAuthSuccess(FirebaseUser user) {
String username = usernameFromEmail(user.getEmail());
// Write new user
writeNewUser(user.getUid(), username, user.getEmail());
// Go to MainActivity
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}
private String usernameFromEmail(String email) {
if (email.contains("#")) {
return email.split("#")[0];
} else {
return email;
}
}
private boolean validateForm() {
boolean result = true;
if (TextUtils.isEmpty(mEmailField.getText().toString())) {
mEmailField.setError("Required");
result = false;
} else {
mEmailField.setError(null);
}
if (TextUtils.isEmpty(mPasswordField.getText().toString())) {
mPasswordField.setError("Required");
result = false;
} else {
mPasswordField.setError(null);
}
return result;
}
// [START basic_write]
private void writeNewUser(String userId, String name, String email) {
User user = new User(name, email);
mDatabase.child("users").child(userId).setValue(user);
}
// [END basic_write]
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_sign_in:
signIn();
break;
case R.id.button_sign_up:
signUp();
break;
}
}
}
Related
I am trying to retrieve information uploaded in firebase. Some of the uploaded data contains an imgURl and some don't.
My database looks like this:
This is the code I use to retrieve the data:
public class ListRequests extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
DatabaseReference Mref;
ArrayList<String>list;
ArrayAdapter<String>adapter;
Uri imgURI;
req req1;
Upload upload1;
TextView textView;
private static final String TAG = "ListRequests";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_requests);
// req1=new req();
upload1=new Upload();
listView=(ListView)findViewById(R.id.listView);
textView=findViewById(R.id.requestinfo);
database= FirebaseDatabase.getInstance();
ref=database.getReference("uploads");
list = new ArrayList<>();
adapter=new ArrayAdapter<String>(this,R.layout.requestinfo,R.id.requestinfo,list);
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("uploads"); //ur child name of the database
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
upload1=singleSnapshot.getValue(Upload.class);
if(upload1.getmImageUrl().toString()!=""){
list.add("\n"+" "+"Title: "+upload1.getTitle().toString()+"\n"
+" "+"Content: "+upload1.getContent().toString()+"\n"+" "+"Date: "+upload1.getDate().toString()+
"\n"+" "+"Time:"+upload1.getTime().toString()+"\n"+" "+"Location: "+upload1.getLocation().toString()+"\n"+" "+
"Type of notification: "+ upload1.getTypeof()+"\n"+" "+ "\n"+" "
+"Status: "+ upload1.getStatus().toString()+"\n"+" "+upload1.getmImageUrl().toString());
} else {
list.add("\n"+" "+"Title: "+upload1.getTitle().toString()+"\n"
+" "+"Content: "+upload1.getContent().toString()+"\n"+" "+"Date: "+upload1.getDate().toString()+
"\n"+" "+"Time:"+upload1.getTime().toString()+"\n"+" "+"Location: "+upload1.getLocation().toString()+"\n"+" "+
"Type of notification: "+ upload1.getTypeof()+"\n"+" "+ "\n"+" "
+"Status: "+ upload1.getStatus().toString()+"\n"+" ");
}
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
}
Some data did not have an ImgURl to be retrieved and caused a crash in the program because of upload1.getmImageUrl().toString().
I want all the childern to be retrieved if its containing the ImgURl or not.
Does anyone have solution for that, how can I retrieve all the data?
Here is the error I got in logs:
04-10 13:11:35.282 17684-17684/com.example.hp.upload E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hp.upload, PID: 17684
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.hp.upload.ListRequests$1.onDataChange(ListRequests.java:60)
at com.google.firebase.database.zzp.onDataChange(Unknown Source)
at com.google.android.gms.internal.to.zza(Unknown Source)
at com.google.android.gms.internal.vj.zzHX(Unknown Source)
at com.google.android.gms.internal.vp.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
I have updated the answer, try it
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child(""); //ur child name of the database
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
upload1=singleSnapshot.getValue(Upload.class);
if(upload1.getmImageUrl().toString()!=""){
System.out.println("Location: "+upload1.getLocation().toString()+"\n"+" "+" "+upload1.getmImageUrl().toString());
list.add(upload1.getmImageUrl().toString());
} else {
list.add(upload1.getLocation().toString());
}
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
I tried to manually add "org.hibernate.AnnotationException" to the whitelist. I tried to implement serializationWhitelist interface in my state class.
lets say my state class is of type Person and has Address type defined inside it. Every time I try to get the states out of the vault I get this error. or another for "org.hibernate.MappingException". Also When my state implements QueryableState I'm not even able to persist the data. and get the below error
Starting as webserver: localhost:10007
Webserver started up in 59.55 sec
>> Generating transaction based on new create.
>> Verifying contract constraints.
>> Signing transaction with our private key.
>> Gathering the counterparty's signature.
>> Structural step change in child of Gathering the counterparty's signature.
>> Collecting signatures from counter-parties.
>> Done
>> Obtaining notary signature and recording transaction.
>> Structural step change in child of Obtaining notary signature and recording transaction.
>> Requesting signature by notary service
[1;31mE 14:01:20+0530 [qtp9538928-76] controller.DMSController.create - com.esotericsoftware.kryo.KryoException: Class org.hibernate.MappingException is not annotated or on the whitelist, so cannot be used in serialization
Serialization trace:
cause (rx.exceptions.OnErrorNotImplementedException)
throwable (rx.Notification)
[m java.util.concurrent.ExecutionException: com.esotericsoftware.kryo.KryoException: Class org.hibernate.MappingException is not annotated or on the whitelist, so cannot be used in serialization
Serialization trace:
cause (rx.exceptions.OnErrorNotImplementedException)
throwable (rx.Notification)
at java.util.concurrent.CompletableFuture.reportGet(Unknown Source) ~[?:1.8.0_151]
at java.util.concurrent.CompletableFuture.get(Unknown Source) ~[?:1.8.0_151]
at net.corda.core.internal.concurrent.CordaFutureImpl.get(CordaFutureImpl.kt) ~[corda-core-1.0.0.jar:?]
at com.den.managment.controller.DMSController.create(DMSController.java:124) [DisputeManagmentSystem.jar:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_151]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_151]
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) [jersey-common-2.25.jar:?]
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) [jersey-common-2.25.jar:?]
at org.glassfish.jersey.internal.Errors.process(Errors.java:315) [jersey-common-2.25.jar:?]
at org.glassfish.jersey.internal.Errors.process(Errors.java:297) [jersey-common-2.25.jar:?]
at org.glassfish.jersey.internal.Errors.process(Errors.java:267) [jersey-common-2.25.jar:?]
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) [jersey-common-2.25.jar:?]
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) [jersey-server-2.25.jar:?]
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) [jersey-container-servlet-core-2.25.jar:?]
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) [jersey-container-servlet-core-2.25.jar:?]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) [jersey-container-servlet-core-2.25.jar:?]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) [jersey-container-servlet-core-2.25.jar:?]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) [jersey-container-servlet-core-2.25.jar:?]
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845) [jetty-servlet-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583) [jetty-servlet-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1174) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) [jetty-servlet-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.Server.handle(Server.java:524) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253) [jetty-server-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) [jetty-io-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) [jetty-io-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) [jetty-io-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) [jetty-util-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) [jetty-util-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) [jetty-util-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) [jetty-util-9.3.9.v20160517.jar:9.3.9.v20160517]
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) [jetty-util-9.3.9.v20160517.jar:9.3.9.v20160517]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_151]
Caused by: com.esotericsoftware.kryo.KryoException: Class org.hibernate.MappingException is not annotated or on the whitelist, so cannot be used in serialization
Serialization trace:
cause (rx.exceptions.OnErrorNotImplementedException)
throwable (rx.Notification)
Updated
public class SomeState implements LinearState,QueryableState{
private final UniqueIdentifier uid;
private final Party partyA;
private final Party partyB;
private final List<Address> addresses;
public SomeState(Party partyA, Party partyB, List<Address> addresses) {
super();
this.uid = new UniqueIdentifier();
this.partyA = partyA;
this.partyB = partyB;
this.addresses = addresses;
}
public Party getPartyA() {
return partyA;
}
public Party getPartyB() {
return partyB;
}
public List<Address> getAddresses() {
return addresses;
}
#Override
public List<AbstractParty> getParticipants() {
return Arrays.asList(partyA,partyB);
}
#Override
public PersistentState generateMappedObject(MappedSchema schema) {
if (schema instanceof SomeStateSchema) {
return new SomeStateSchema().new PersistentSomeState(uid.getId(), partyA.getName().toString(), partyB.getName().toString(), addresses);
} else {
throw new IllegalArgumentException("Unrecognised schema $schema");
}
}
#Override
public Iterable<MappedSchema> supportedSchemas() {
return ImmutableList.of(new SomeStateSchema());
}
#Override
public UniqueIdentifier getLinearId() {
return uid;
}
}
public class SomeStateSchema extends MappedSchema {
public SomeStateSchema() {
super(SomeStateSchema.class, 1, ImmutableList.of(PersistentSomeState.class));
}
#Entity
#Table(name = "records")
public class PersistentSomeState extends PersistentState{
#Column(name = "uid")
private final UUID uId;
#Column(name = "partyA")
private final String partyA;
#Column(name = "partyB")
private final String partyB;
#ElementCollection
private final List<Address> addresses;
public PersistentSomeState(UUID uId, String partyA, String partyB, List<Address> addresses) {
super();
this.uId = uId;
this.partyA = partyA;
this.partyB = partyB;
this.addresses = addresses;
}
public UUID getuId() {
return uId;
}
public String getPartyA() {
return partyA;
}
public String getPartyB() {
return partyB;
}
public List<Address> getAddresses() {
return addresses;
}
}
}
#CordaSerializable
public class Address {
public final String street;
public final int pincode;
public Address(String street, int pincode) {
super();
this.street = street;
this.pincode = pincode;
}
public String getStreet() {
return street;
}
public int getPincode() {
return pincode;
}
}
From the controller I call:
#GET
#Path("msas")
#Produces(MediaType.APPLICATION_JSON)
public List<StateAndRef<SomeState>> getMSAs() {
return rpcOps.vaultQuery(SomeState.class).getStates();
}
FLOW is same as in IOU Example.
public SignedTransaction call() throws FlowException {
// Obtain a reference to the notary we want to use.
final Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);
Set<PublicKey> set= getServiceHub().getKeyManagementService().getKeys();
//val ourParties = ourKeys.map { serviceHub.identityService.partyFromKey(it) ?: throw IllegalStateException("Unable to resolve party from key") }
//
List<Party> parties= new ArrayList();
for (Iterator<PublicKey> it = set.iterator(); it.hasNext(); ) {
parties.add(getServiceHub().getIdentityService().partyFromKey(it.next()));
}
progressTracker.setCurrentStep(GENERATING_TRANSACTION);
// Generate an unsigned transaction.
SomeState someState = new SomeState(getServiceHub().getMyInfo().getLegalIdentities().get(0),otherParty,Arrays.asList(new Address("Yes Street",12532)));
final Command<SomeContract.Commands.Create> txCommand = new Command<>(new SomeContract.Commands.Create(),
someState.getParticipants().stream().map(AbstractParty::getOwningKey).collect(Collectors.toList()));
final TransactionBuilder txBuilder = new TransactionBuilder(notary).withItems(new StateAndContract(someState, MSAContract.MSA_CONTRACT_ID), txCommand);
// Stage 2.
progressTracker.setCurrentStep(VERIFYING_TRANSACTION);
// Verify that the transaction is valid.
txBuilder.verify(getServiceHub());
// Stage 3.
progressTracker.setCurrentStep(SIGNING_TRANSACTION);
// Sign the transaction.
final SignedTransaction partSignedTx = getServiceHub().signInitialTransaction(txBuilder);
FlowSession otherPartySession = initiateFlow(otherparty);
// Stage 4.
progressTracker.setCurrentStep(GATHERING_SIGS);
// Send the state to the counterparty, and receive it back with their signature.
final SignedTransaction fullySignedTx = subFlow(
new CollectSignaturesFlow(partSignedTx, Sets.newHashSet(otherPartySession), CollectSignaturesFlow.Companion.tracker()));
// Stage 5.
progressTracker.setCurrentStep(FINALISING_TRANSACTION);
// Notarise and record the transaction in both parties' vaults.
return subFlow(new FinalityFlow(fullySignedTx));
}
I finally found the rootException:
Caused by: org.hibernate.MappingException: Could not determine type for: com.den.managment.state.Address, at table: SomeStateSchema$PersistentSomeState_addresses, for columns: [org.hibernate.mapping.Column(addresses)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:455)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:422)
at org.hibernate.mapping.Collection.validate(Collection.java:310)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:333)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at net.corda.node.services.persistence.HibernateConfiguration.buildSessionFactory(HibernateConfiguration.kt:101)
at net.corda.node.services.persistence.HibernateConfiguration.makeSessionFactoryForSchemas(HibernateConfiguration.kt:74)
at net.corda.node.services.persistence.HibernateConfiguration.access$makeSessionFactoryForSchemas(HibernateConfiguration.kt:27)
at net.corda.node.services.persistence.HibernateConfiguration$sessionFactoryForSchemas$1.apply(HibernateConfiguration.kt:54)
at net.corda.node.services.persistence.HibernateConfiguration$sessionFactoryForSchemas$1.apply(HibernateConfiguration.kt:27)
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(Unknown Source)
at net.corda.node.services.persistence.HibernateConfiguration.sessionFactoryForSchemas(HibernateConfiguration.kt:54)
at net.corda.node.services.persistence.HibernateConfiguration.sessionFactoryForSchema(HibernateConfiguration.kt:48)
at net.corda.node.services.schema.HibernateObserver.persistStateWithSchema(HibernateObserver.kt:41)
at net.corda.node.services.schema.HibernateObserver.persistState(HibernateObserver.kt:37)
at net.corda.node.services.schema.HibernateObserver.persist(HibernateObserver.kt:31)
at net.corda.node.services.schema.HibernateObserver.access$persist(HibernateObserver.kt:20)
at net.corda.node.services.schema.HibernateObserver$1.call(HibernateObserver.kt:27)
at net.corda.node.services.schema.HibernateObserver$1.call(HibernateObserver.kt:20)
at rx.internal.util.ActionSubscriber.onNext(ActionSubscriber.java:39)
at rx.observers.SafeSubscriber.onNext(SafeSubscriber.java:134)
... 42 more
Your flow is throwing various exceptions because of underlying issues with your code. Corda is then trying to serialise these exceptions to send them back to your RPC client via the RPC framework. Since these types are not whitelisted to be sent via RPC, you get a Kryo exception when you try.
In other words, these exceptions are just a symptom (of your underlying code throwijng AnnotationException or MappingException) rather than a root cause.
Can you post the code showing the Person state definition and how you are trying to retrieve it from the vault in the flow?
DetailFragment.java
public void sendPost() {
mAPIService.savePost("O3", 2, "ssfu", "jhsgdhf", 20, "mystring", 1, "UnoiaTech", "hdbjhsdhfjsd").enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()) {
Toast.makeText(getActivity(), "Submited" + response.body(), Toast.LENGTH_SHORT).show();
Log.i(TAG, "post submitted to API." + response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
Toast.makeText(getActivity(), "Error To Post API in DetailFragment", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to submit post to API.");
}
});
}
PlanFragment.java
next_plan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailFragment.sendPost();
}
});
ApiUtils.java
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://192.168.100.14:8080";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
RetroClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiService.java
public interface APIService {
#POST("/deals/deal")
#FormUrlEncoded
Call<Post> savePost(#Field("bookingType") String bookingType,
#Field("dealPrice") int dealPrice,
#Field("description") String description,
#Field("keyword") String keyword,
#Field("originalPrice") int originalPrice,
#Field("plan") String plan,
#Field("shopId") int shopId,
#Field("shopName") String shopName,
#Field("title") String title);
}
Showing error
FATAL EXCEPTION: main
Process: googlemap.arun.com.mywork2, PID: 20969
java.lang.NullPointerException: Attempt to invoke interface method
'retrofit2.Call
googlemap.arun.com.mywork2.data.remote.APIService.savePost(java.lang.String,
int, java.lang.String, java.lang.String, int, java.lang.String, int,
java.lang.String, java.lang.String)' on a null object reference
at
googlemap.arun.com.mywork2.DetailFragment.sendPost(DetailFragment.java:104)
at
googlemap.arun.com.mywork2.PlanFragment$5.onClick(PlanFragment.java:85)
at android.view.View.performClick(View.java:5272)
at android.view.View$PerformClick.run(View.java:21528)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5857)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1026)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:887)
Can't start intent service
I am writing code for synch data for every 10 minute whenapp is in forground,background or sleep . I had write weakfulintentservice for it calling it from Alaramreceiver but AppService doesn't get call.
AppService
public class AppService : WakefulIntentService
{
public AppService() : base("AppService")
{
}
protected override void DoWakefulWork(Intent intent)
{
Toast.MakeText(this, "In service", ToastLength.Short).Show();
Log.Info("AppService", "I'm awake! I'm awake!");
}
}
WeakFulIntentService
abstract public class WakefulIntentService : IntentService
{
abstract protected void DoWakefulWork(Intent intent);
public static string NAME = "com.jondouglas.wakeful.WakefulIntentService";
public static string LAST_ALARM = "lastAlarm";
private static volatile PowerManager.WakeLock lockStatic = null;
[MethodImpl(MethodImplOptions.Synchronized)]
private static PowerManager.WakeLock GetLock(Context context)
{
if (lockStatic == null)
{
PowerManager manager = (PowerManager) context.GetSystemService(Context.PowerService);
lockStatic = manager.NewWakeLock(WakeLockFlags.Partial, NAME);
lockStatic.SetReferenceCounted(true);
}
return (lockStatic);
}
public static void SendWakefulWork(Context context, Intent intent)
{
GetLock(context.ApplicationContext); //Possibly use of acquire here
context.StartService(intent);
}
public static void SendWakefulWork(Context context, Type classService)
{
SendWakefulWork(context, new Intent(context, classService));
}
public static void ScheduleAlarms(IAlarmListener alarmListener, Context context)
{
ScheduleAlarms(alarmListener, context, true);
}
public static void ScheduleAlarms(IAlarmListener alarmListener, Context context, bool force)
{
ISharedPreferences preferences = context.GetSharedPreferences(NAME, 0);
long lastAlarm = preferences.GetLong(LAST_ALARM, 0);
if (lastAlarm == 0 || force ||
(DateTime.Now.Millisecond > lastAlarm &&
DateTime.Now.Millisecond - lastAlarm > alarmListener.GetMaxAge()))
{
AlarmManager manager = (AlarmManager) context.GetSystemService(Context.AlarmService);
Intent intent = new Intent(context, typeof(AlarmReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);
alarmListener.ScheduleAlarms(manager, pendingIntent, context);
}
}
public static void CancelAlarms(Context context)
{
AlarmManager manager = (AlarmManager) context.GetSystemService(Context.AlarmService);
Intent intent = new Intent(context, typeof (AlarmReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);
manager.Cancel(pendingIntent);
context.GetSharedPreferences(NAME, 0).Edit().Remove(LAST_ALARM).Commit();
}
public WakefulIntentService(string name) : base(name)
{
SetIntentRedelivery(true);
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (!lockStatic.IsHeld || (flags & StartCommandFlags.Redelivery) != 0)
{
wakeLock.Acquire();
}
return base.OnStartCommand(intent, flags, startId);
return (StartCommandResult.RedeliverIntent);
}
protected override void OnHandleIntent(Intent intent)
{
try
{
DoWakefulWork(intent);
}
finally
{
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (wakeLock.IsHeld)
{
try
{
wakeLock.Release();
}
catch (Exception ex)
{
Log.Error(Class.SimpleName, "Exception when releasing wakelock", ex);
//Log exception when releasing wakelock
}
}
}
}
public interface IAlarmListener
{
void ScheduleAlarms(AlarmManager manager, PendingIntent pendingIntent, Context context);
void SendWakefulWork(Context context);
long GetMaxAge();
}
CallToAppService
public void SendWakefulWork(Context context)
{
WakefulIntentService.SendWakefulWork(context, typeof(AppService));
}
The call for AppService context.StartService(intent); from weakfulintentservice execute perfectly
but AppService cant start In xamarin.android.
Kindly help me to solve this issue.
The call for AppService context.StartService(intent); from weakfulintentservice execute perfectly but AppService cant start In xamarin.android.
You can refer to Started Services, in your Xamarin.Android code where you want to start your AppService, you can code as simply as this:
StartService (new Intent (this, typeof(AppService)));
If you want to start a service with an intent filter, you can refer to this part.
Also you may refer to the case I answered several days ago: Xamarin Android : Change UI TextView text from Service or Receiver.
I'm wreting a SpringBoot web service use websocket to send message to client and using JPA to save data.
in project I use a thread to create a data ,and then use JPA to save it ,use Websocket to show data. But it doesn't work with a NullPointExecption.
this is my code:
#RestController
#ServerEndpoint("/websocket")
public class CrawlingController {
private final Logger logger = LoggerFactory.getLogger(CrawlingController.class);
#Autowired
private SimulateDataRepository simulateDataRepository;
private static GlobalStatus globalStatus = GlobalStatus.getInstance();
private Session session;
private static CopyOnWriteArraySet<CrawlingController> crawlingControllers =
new CopyOnWriteArraySet<>();
#OnOpen
public void onOpen(Session session) throws Exception {
this.session = session;
crawlingControllers.add(this);
String message = dataCrawling();
}
#OnMessage
public void onMessage(String message, Session session) throws IOException {
for (CrawlingController controller : crawlingControllers)
sendMessage(message);
}
#OnClose
public void onClose() {
crawlingControllers.remove(this);
if (crawlingControllers.size() == 0)
end();
session=null;
end();
}
private void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public void onError(Session session, Throwable error) {
logger.error(error.getMessage());
System.out.println("websocket found something error!");
}
#RequestMapping("/start")
public String dataCrawling() throws Exception {
if (!globalStatus.isDataCrawling) {
Process process = null;
synchronized (globalStatus) {
process = Utils.crawling();
globalStatus.crawlingProcss = process;
globalStatus.isDataCrawling = true;
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
new Thread(() -> {
try {
stuffSimulate(bufferedReader);
} catch (IOException | ParseException e) {
logger.error(e.getMessage());
}
}).start();
return "start Finish!";
} else return "faild";
}
public void stuffSimulate(BufferedReader reader) throws IOException, ParseException {
line = reader.readLine();
while (globalStatus.isDataCrawling) {
SimulateData simulateData = new SimulateData();
.... ...
simulateData.setData(data.toString());
this.saveAndShow(simulateData);
}
}
}
}
private void saveAndShow(SimulateData simulateData) throws IOException {
simulateData = simulateDataRepository.saveAndFlush(simulateData);
SummaryData summaryData = SimulateService.obtainSummary(simulateData);
onMessage(summaryData.printSummary(),this.session);
summaryData.sout();
}
}
simulateDataRepository can be work when i use http://localhost:8080/start.
the mysql can get data.
But it cna't be work when i use websocket!!!
The error meaasge said that:
Exception in thread "Thread-5" java.lang.NullPointerException
at cn.linhos.controller.CrawlingController.saveAndShow(CrawlingController.java:293)
at cn.linhos.controller.CrawlingController.stuffSimulate(CrawlingController.java:172)
at cn.linhos.controller.CrawlingController.lambda$dataCrawling$0(CrawlingController.java:104)
at java.lang.Thread.run(Thread.java:748)
why simulateDataRepository can't saveAndFlush when websocket but can do it when i use "/start"?
how should i do to make websocket work ?