Hi after countless hours, I figured out what I really what my problem is but still cannot find an answer.
#Override
public void onStampResult(StampResult result) {
}
onStampResult returns a Class StampResult with the follwowing parameters:
public class StampResult implements Serializable {
public SnowShoeError error;
public SnowShoeStamp stamp;
public boolean secure;
public String receipt;
public Date created;
}
SnowShoeStamp Class is:
public class SnowShoeStamp implements Serializable {
public String serial;
}
And SnowShoeError Class is:
public class SnowShoeError implements Serializable {
public int code;
public String message;
}
In onStampResult I can write down logic depending on the output of result.
On Success ´stamp´ gets initialized and ´error´ does not exist.
On Error, stamp does not exist and error gets initialized.
The result gets parsed to from JSON to the Class in the following way:
try {
stampResult = gson.fromJson(result, StampResult.class);
} catch (JsonSyntaxException jsonException) {
stampResult = new StampResult();
stampResult.error = new SnowShoeError();
stampResult.error.message = result;
}
mOnStampListener.onStampResult(stampResult);
mStampBeingChecked = false;
}
How do I test if either error or stamp exists without getting a NullPointerExeption?
Unless I misunderstood your question, you simply need to check for null.
In order to handle the different cases, you could do the following:
#Override
public void onStampResult(StampResult result) {
if (result.error == null){
SnowShoeStamp stamp = result.stamp;
// Process stamp
} else {
SnowShoeError error = stampResult.error;
// Process error
}
}
Related
I am new to android programming and can anyone help me or point out why its giving me this error
I want to fetch some data from the server such as under the Hardware json and get the names and status, but when i call api its shows me this.
Change the line
public void onResponse(Call<List<ObjectList>> call, Response<List<ObjectList>> response) {
to
public void onResponse(Call<List<ObjectList>> call, Response<ObjectList> response) {
As per your code, you are expecting response as List. But Actual response is object. So, you need to generate model class based on your response and set in code for output.
Your Model should be like :
public class Application {
ArrayList<Object> hardware = new ArrayList<Object>();
Header HeaderObject;
ArrayList<Object> software = new ArrayList<Object>();
// Getter Methods
public Header getHeader() {
return HeaderObject;
}
// Setter Methods
public void setHeader( Header headerObject ) {
this.HeaderObject = headerObject;
}
}
public class Header {
Stamp StampObject;
private String frame_id;
private float seq;
// Getter Methods
public Stamp getStamp() {
return StampObject;
}
public String getFrame_id() {
return frame_id;
}
public float getSeq() {
return seq;
}
// Setter Methods
public void setStamp( Stamp stampObject ) {
this.StampObject = stampObject;
}
public void setFrame_id( String frame_id ) {
this.frame_id = frame_id;
}
public void setSeq( float seq ) {
this.seq = seq;
}
}
public class Stamp {
private float secs;
private float nsecs;
// Getter Methods
public float getSecs() {
return secs;
}
public float getNsecs() {
return nsecs;
}
// Setter Methods
public void setSecs( float secs ) {
this.secs = secs;
}
public void setNsecs( float nsecs ) {
this.nsecs = nsecs;
}
}
Then change below line :
public void onResponse(Call<List<ObjectList>> call, Response<Application> response) {
Change this:
#GET("system_monitor")
Call<List<ObjectList>> getHardware();
to
#GET("system_monitor")
Call<ObjectList> getHardware();
Your response return an object instead of array.
Instead of
#GET("system_monitor")
Call<List<ObjectList>> getHardware();
use
#GET("system_monitor")
Call<ObjectList> getHardware();
And then use it like below:
Call<ObjectList> call = webRequestAPI.getHardware();
call.enqueue(new Callback<ObjectList>() {
#Override
public void onResponse(Call<ObjectList> call, Response<ObjectList> response) {
if (!response.isSuccessful()) {
textViewHardwareName.setText("Code: " + response.code());
return;
}
ObjectList system_monitor = response.body();
...
}
#Override
public void onFailure(Call<ObjectList> call, Throwable t) {
textViewHardwareName.setText(t.getMessage());
}
});
The best thing for your scenario hardware and Software are as objects , which have two property
1.Name 2. Object status.
So I recommend you to create a class name as System and put there these two variables so finally your class looks like :
Class System
{
String object_name;
boolean object_status;
}
and your getter setter .
And update your model class like this
#SerializedName("hardware")
#Expose
public List<System> hardware;
#SerializedName("software")
#Expose
public List<System> software;
and change your retrofit response holder as.
public void onResponse(Call<List<ObjectList>> call, Response<ObjectList>
response) {
I am using a Item with the inferface ResourceAware implemented to get the current resource filename. I get it in the ItemProcessor and this is working fine to log a complete information about the error.
Anyway, I want get the fileName if the moment of the FieldSetMapper throw an Exception, to register the line content, the line number and the file name but I don't found the correct way.
This is my current code:
public class MyCustomLineMapper<T> implements LineMapper<BaseDTO>, InitializingBean {
private LineTokenizer tokenizer;
private BeanWrapperFieldSetMapper<BaseDTO> fieldSetMapper;
public BaseDTO mapLine(String line, int lineNumber) throws Exception {
try {
BaseDTO r = fieldSetMapper.mapFieldSet(tokenizer.tokenize(line));
r.setLineNumber(lineNumber);
r.setLineContent(line);
return r;
} catch(Exception ex){
BaseDTO r = new BaseDTO();
r.setError(String.format(Keys.LINE_PARSE_ERROR, lineNumber, "FILE_NAME", line));
return r;
/// I want use the current filename in this moment.
}
}
public void setLineTokenizer(LineTokenizer tokenizer) {
this.tokenizer = tokenizer;
}
public void setFieldSetMapper(BeanWrapperFieldSetMapper<BaseDTO> fieldSetMapper) {
this.fieldSetMapper = fieldSetMapper;
}
public void afterPropertiesSet() {
Assert.notNull(tokenizer, "The LineTokenizer must be set");
Assert.notNull(fieldSetMapper, "The FieldSetMapper must be set");
}
}
In my item "BaseDTO" I implemented ResourceAware like this:
public class BaseDTO implements ResourceAware {
protected String itemClassifier;
protected String error;
protected int lineNumber;
protected String lineContent;
protected Resource res;
protected String fileName;
#Override
public void setResource(Resource res) {
this.res = res;
this.fileName = res.getFilename();
}
But in case of an exception reading a file (IncorrecNumberOfTokens by Example) I need get my item from FieldSetMapper with this field filled but the exception stop this. How can I achieve this?
Sorry for my english. Thanks in advance for all the help.
I'm trying to store a list in the Application class instance as a global variable in one of my Android applications. Below is my Application class code:
public class DefectsApplication extends Application{
private NormalUser normalUser;
private ArrayList<Complaint> complaintList;
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
private String testString;
public NormalUser getNormalUser() {
return normalUser;
}
public void setNormalUser(NormalUser normalUser) {
this.normalUser = normalUser;
}
public ArrayList<Complaint> getComplaintList() {
return complaintList;
}
public void setComplaintList(ArrayList<Complaint> m_complaints) {
this.complaintList = complaintList;
}
}
Below is my code which is trying to access the fields from the Application class instance:
DefectsApplication defectsApplication = ((DefectsApplication)getApplicationContext());
defectsApplication.setComplaintList(m_complaints);
defectsApplication.setTestString("urghhhhhhhhh");
ArrayList<Complaint> complaintList = defectsApplication.getComplaintList();
String s = defectsApplication.getTestString();
In the above code, m_complaints is a list of objects. When I try to store a String, it works. But for a list, it doesn't. Please, help me to resolve this issue.
Probably, a typo is taking place:
public void setComplaintList(ArrayList<Complaint> m_complaints) {
this.complaintList = complaintList;
}
You're setting this.complaintList to itself which is initially null. Try
public void setComplaintList(ArrayList<Complaint> m_complaints) {
this.complaintList = m_complaints;
}
I am using gwt with gwt-platform and making a server call with the dispatch async. The issue I am running into is that the Action that I am using is not being marked as serializable or being added to the *.gwt.rpc file. When my code run I get a
com.google.gwt.user.client.rpc.SerializationException
at com.google.gwt.user.client.rpc.impl.SerializerBase.getTypeHandler(SerializerBase.java:153)
at com.google.gwt.user.client.rpc.impl.SerializerBase.serialize(SerializerBase.java:125)
at com.google.gwt.user.client.rpc.impl.ClientSerializationStreamWriter.serialize(ClientSerializationStreamWriter.java:183)
at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126)
at com.gwtplatform.dispatch.shared.DispatchService_Proxy.execute(DispatchService_Proxy.java:33)
at com.gwtplatform.dispatch.client.DefaultDispatchAsync.serviceExecute(DefaultDispatchAsync.java:126)
at com.gwtplatform.dispatch.client.DefaultDispatchAsync.execute(DefaultDispatchAsync.java:...
The Action:
public class FindCallsWithFilterAction extends UnsecuredActionImpl<FindCallsWithFilterResult> {
public FindCallsWithFilterAction() {
}
public Date getAfter() {
return after;
}
public Date getBefore() {
return before;
}
public Long getReferenceNumber() {
return referenceNumber;
}
public String getUser() {
return user;
}
public void setAfter(Date after) {
this.after = after;
}
public void setBefore(Date before) {
this.before = before;
}
public void setReferenceNumber(Long referenceNumber) {
this.referenceNumber = referenceNumber;
}
public void setUser(String user) {
this.user = user;
}
public boolean hasAfter(){
return null != after;
}
public boolean hasBefore(){
return null != before;
}
public boolean hasReferenceNumber(){
return null != referenceNumber;
}
public boolean hasUser(){
return null != user;
}
private Date after = null;
private Date before = null;
private Long referenceNumber = null;
private String user = null;
}
The Action has result and a Handler and the handler is bound in my server module. When I debug the code and look at the Serialization map that gwt generates this action and its result aren't there event though this implements the isSerializable interface (in the super class, it still doesn't work if I use Serializable or isSerializable at this level either). Also when I look into my *.gwt.rpc file the class is not in there either. I'm just stuck and was hoping some one would know what to do or what was wrong.
Update: I don't know if it is relevant but I am using spring on the server.
I found my problem. I had forgotten a no-arg constructor in my Result object, also I was using a Builder to create my action and for some reason that was causing the serialization issue once I stopped using the Builder pattern everything ran smoothly.
I am trying to create a ValueProxy which holds some basic information about a search a user is performing. For some reason GWT wants it to be an EntityProxy but I dont see why (nor does it make sense for this class to be an EntityProxy).
// FilterProxy extends ValueProxy
#ProxyFor(DayFilter.class)
public interface DayFilterProxy extends FilterProxy {
void setFilterValue(Date day);
Date getFilterValue();
}
public class DayFilter extends Filter {
public DayFilter() {
setOperator(FilterOperator.GREATER_THAN_OR_EQUAL);
setField("dateRequested");
}
public void setFilterValue(Date date) {
this.value = date;
}
public Date getFilterValue() {
return value;
}
}
public interface PaginationRequest<T> extends RequestContext {
Request<List<T>> paginate(int offset, int limit, String sortColumn,
boolean isSortAscending, List<FilterProxy> filters);
Request<Integer> count(List<FilterProxy> filters);
}
#Service(value=TripService.class, locator=SchedgyServiceLocator.class)
public interface TripRequest extends PaginationRequest<TripProxy> {
Request<TripProxy> save(TripProxy trip);
}
Within the activity that is sending this back to the server:
// Request is a TripRequest
DayFilterProxy filter = request.create(DayFilterProxy.class);
This results in:
java.lang.AssertionError: com.schedgy.trip.dao.filter.trip.proxy.DayFilterProxy is not an EntityProxy type
at com.google.web.bindery.requestfactory.shared.impl.IdFactory.asEntityProxy(IdFactory.java:66)
at com.google.web.bindery.requestfactory.shared.impl.IdFactory.createId(IdFactory.java:229)
at com.google.web.bindery.requestfactory.shared.impl.IdFactory.allocateId(IdFactory.java:41)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext.create(AbstractRequestContext.java:478)
at com.schedgy.trip.client.activity.TripsActivity.getFilters(TripsActivity.java:56)
Any ideas? Its got to be something obvious that I am just overlooking as I have ValueProxies working elsewhere in the code.
Could it be that your DayFilterProxy is not referenced at all from the RequestContext?