GsonRequest class is a List - java

I am currently making a GsonRequest as follows:
final GsonRequest gsonRequest =
new GsonRequest(url, People.class, null, new Response.Listener<People>() { ... }
But my People class has only one member object: List of Person(s).
public class People {
private List<Person> people;
}
I did it like because the argument for the GsonRequest called for a class (i.e., People.class). To me it seems strange and silly to make a class that only has one member object which is just a list of another objects. But the request I am making will return multiple Person(s). So, is there a better way? Can I pass a List of objects instead of a made up class like I did? My way is working, but I can't help but think there is a better way???

You can define it like this:
public class People extends List<Person> {
}
And that will work, at least you aren't defining a one-member class (you also need to make API change to match).
If you want to avoid the class completely, you can also use TypeToken<E>:
new TypeToken<List<Person>>(){}.getType()
However your GsonRequest class must be able to accept a Type instead of a class parameter.

Related

Access public final static field from tml page

I have a grid where I would like to load the data from method. This method is taking String as a parameter and produce necessary List as output.
For example, it can look like this:
public List<SomeObject> getContactBasedOnType(final String type)
{
final List<SomeObject> returnList = new ArrayList<>();
...//based on "type" list will be populated by different data
return returnList;
}
and then in my tml page I will use it as follows:
<t:grid t:source="getSomeData('STRING')"...
>...</t:grid>
Now, I would like to replace 'STRING' with a public static String field from a class other than component class, for example:
<t:grid t:source="getSomeData(com.example.Class.STATIC_FINAL_FIELD)"...
>...</t:grid>
Is there any way I can do that directly? So without using any additional methods in a component class or annotated fields?
There is a way to achieve what you asked, but it's an awful hack.
<t:grid
t:source="getSomeData(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').get(getClass().getClassLoader().loadClass('com.example.Class').getField('STATIC_FINAL_FIELD').getType().newInstance()))">
...
</t:grid>
Note that, in your question, the method in the component class is named getContactBasedOnType while in your tmls you are referencing getSomeData. The method names must match, of course.
Again, the above is a terrible hack, but the only solution I got to work under the constraint that the component class may not be touched.
Making the list a property of the component class and populating it in the setupRender() method would be a much better design.

Android class with nested asynctask

I am relatively new (ish) to Java..
I am writing an Android app, and now I am going back over my code and tidying up and adhering my coding structure to a more best practice style.
I am building methods and classes as I see fit to avoid the numerous amounts of duplicate code that I have produced. I have found myself trying to create a class (e.g. HeavyStuff.java) that contains several AsyncTask methods inside it (e.g. MyTask1 and MyTask2). When calling the class from an activity, I'd like to execute MyTask1 at some point, and at some point elsewhere I'd like to execute MyTask2. I am trying to use the following respectively:
HeavyStuff.MyTask1 myTask1 = new HeavyStuff.MyTask1();
myTask1.execute();
And
HeavyStuff.MyTask2 myTask2 = new HeavyStuff.MyTask2();
myTask2.execute();
The problem is, I get an error saying that "HeavyTest is not an enclosing class". My class looks like this:
package com.wizzkidd.myapp;
import android.os.AsyncTask;
public class HeavyStuff {
public class MyTask1 extends AsyncTask<String, String, String> {
//...
//...
}
public class MyTask2 extends AsyncTask<String, String, String> {
//...
//...
}
}
The class can also be seen here in full: http://hastebin.com/yahihokupu
What am I missing that is required to make the class an "enclosing class".
-----EDIT-----
I've looked at the answer that was given as a possible duplicate to my question and it does not work. The answer given recommends using static for my inner class, but this doesn't work for me.
I have however found that I can do this:
HeavyStuff.MyTask1 myTask1 = new HeavyStuff().new MyTask1();
myTask1.execute();
It works, but what are the implications (if any) when doing it like this? Is it bad practice?
I understand that you put both MyTask1 and MyTask2 into the same class because they are similar, however in general this is not ideal.
If you plan on creating new instances of MyTask1 and also new instances of MyTask2 throughout your code base, then they should be in their own completely separate classes (i.e. MyTask1.java containing only class MyTask1).
You can still keep them "together" by putting them within the same java package, for example:
package.heavystuff
.
I have found an answer to my question. I originally posted what I believe is a solution as an edit, but to clarify, this is my working answer:
HeavyStuff.MyTask1 myTask1 = new HeavyStuff().new MyTask1();
myTask1.execute();

Can I wrap a non-serializeable class in a local nested serializeable class?

I was wondering, if I can cheat serialization by wrapping them in local nested classes, something like this:
I have a service which I need to pass around, but it internally has some very complex data.
interface ComplexService {
IncredibleComplexObject getData();
}
So I thinking about wrapping it in another class that is serializeable via decorator pattern.
public final class Utils {
public static Serializable wrap(final ComplexService service) {
class WrapperService implements ComplexService, Serializeable {
#Override
public IncredibleComplexData getData() {
return service.getData();
}
};
return new WrapperService();
}
}
I actually don't believe that I can cheat serialization like that, because it would be a little bit too much magic if Java could actually recreate my class that is dependent on my final ComplexService-parameter. But I am wondering, why exactly this fails and what exception would be thrown, where and why.
(just for clarification why I would want to do this: I am on android and I need to pass this service to a Fragment, which naturally can only save serializeable objects).
Yes, you can wrap your non-serializable object in a serializable wrapper. No, it won't magically make the wrapped object serializable. You'll get a NotSerializableException if you attempt to serialize the wrapper class (without making that field transient).

Best way to pass arguments in constructor

I have a class that create rows in table layout. The row creation depend upon data and metadata. As metadata is same for each row like show/hide visibility properties etc. so I have created metadata property as a static and initialize once using initWidget of RowWidget.
just example:
class RowWidget extends FlexTable{
public static void initWidget(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment)
{
// ...
}
}
Then I called below constructor for each record data.
public RowWidget(DataRawType dataRawType, Data data, Data parentData) {
// ...
}
As I thought this is not right approach. because as pattern when anyone see this class then understand it will create one row. I don't want to call initially initWidget. I want to pass each required parameter in constructor only like
public RowWidget(DataRawType dataRawType,
Data data,
Data parentData,
Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) {
// ...
}
But due to this, constructor have no of arguments. and I think it's also bad pattern to have 5+ parameter in constructor.
Is Anyone suggest me:
How to construct class which have same property required in another
instance?
Note:I know this is possible through static only but don't want to use static.
What is best way to construct class with having some default fix
property for all instances?
Note: I don't want to create another class to achieve it. or any getter/setter method.
Thanks In advance.
I would suggest builder pattern. You would need one extra class to create RowWidget objects. So the call would look like that:
RowWidget widget = new RowWidget.Builder().withData(data).withParentData(parentData).withDataRawType(dataRawType).build();
Here is neat explanation of the pattern:https://stackoverflow.com/a/1953567/991164
Why not create method which will accept the newValues for the properties you want to change & return a new instance of the classes with all other properties copied from the instance on which you invoked this method.
You could separate/extract the parameters from the RowWidget-class fro example in a RowWidgetConfig-class.
class RowWidgetConfig {
// put here all your parameters that you need to initialize only once
// init using setters
}
Now create once instance of that class and pass it among the other parameters to RowWidget constructor.
Another alternative would be to have factory for creating RowWidget instances. The factory would also contain all the parameters you need for a row instance plus a factory method createNewRowWidget witch creates an instance base on the parameters contained in the factory.
class RowWidgetFactory {
// put here all your parameters that you need to initialize only once
// init using setters
public RowWidget createNewRowWidget() {
// create
return ...
}
}
How to construct class which have same property required in another instance?
To achive this you can have a super class with all the properties you want. So any class extending this super class will be have these properties. This way you don't need to use static keyword.
What is best way to construct class with having some default fix property for all instances?
For this one you can have an interface with some constant properties. This way any class implementing this interface will be having the fixed properties.
The static initWidget() thing just doesn't seem right for me. Though probably now you will only have one set of RowWidgets which share some properties, it is also reasonable to have 2 sets of RowWidgets, each set will have its own "shared" properties. Things will be much more fluent and you have much more choices in building more reasonable APIs if you refactor your code to make a more reasonable design
Assume now I introduce something like a RowGroup (which kind of represents the "shared" thing you mentioned)
(Honestly I don't quite get the meaning for your design, I am just making it up base on your code);
public class RowGroup {
public RowGroup(Form form,
HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
GridMode gridMode,
boolean isApplied,
boolean isChildExist,
boolean isChildAttachment) { .... }
public void addRow(DataRawType dataRawType, Data data, Data parentData) {...}
}
When people use, it looks something like:
RowGroup rowGroup = new RowGroup(form, permissionMap, gridMode, isApplied, isChildExist, isChildAttach);
rowGroup.addRow(DataRawType.A, dataA, parentA);
rowGroup.addRow(DataRawType.B, dataB, parentB);
You may even provide builder-like syntax or a lot other choices.
RowGroup rowGroup
= new RowGroup(.....)
.addRow(DataRawType.A, dataA, parentA)
.addRow(DataRawType.B, dataB, parentB);
Even more important, the design now make more sense to me.
If you did not want to create another class, I'd suggest what A4L suggested.
Without creating another class, I would create constructor that takes all parameters and factory method that uses current instance as template and pass its own parameters to constructor parameter.
example (with obvious parts ommited)
class A{
public A(int p1, int p2){...}
public A create(int p2) {
return new A(this.p1,p2);
}

How to cast a complete list without iterating through it in Java

Say I have this class :
public class BaseJob{
String name;
public void setName(String name){
this.name=name;
}
public String getName()
{
return name;
}
}
and another class that extends it :
public class DetailedJob extends BaseJob{
public void doThing();
}
Furthermore, I have this method in another class :
List<BaseJob> getSomeJobs()
Now, my problem is :
is it possible to avoid to cast each item sequentially in the returned list of getSomeJobs, if I know for sure that every BaseJob returned is indeed a DetailedJob ?
Put differently, is there another solution than the following to cast all items in the list :
List<BaseJob> baseJobList = getSomeJobs();
List<DetailedJob> detailedJobList = new ArrayList<DetailedJob>();
for (BaseJob baseJob : baseJobList)
detailedJobList.add((DetailedJob) baseJob);
Probably what you want to do is parameterising the class that defines getSomeJobs.
public final class JobHolder<T extends BaseJob> {
public List<T> getSomeJobs() {
...
Generally unchecked casts indicate a design problem. They are unavoidable in certain situations such as low-level implementations and when dealing with serialisation.
If you know that all of the jobs are going to be detailed jobs, why would you put them in an arraylist of basejobs? There's no reason to, and that method would eliminate many possible errors and exceptions.
Well, there's:
List<BaseJob> baseJobList = getSomeJobs();
#SuppressWarnings("unchecked")
List<DetailedJob> detailedJobList = (List) baseJobList;
The downside of this is that if any of the jobs in the list aren't detailed jobs, the exception will only be thrown when someone tries to fetch it. Also, if a new non-detailed job is added to baseJobList afterwards, that could screw up anyone using detailedJobList. Basically you've lost a lot of type safety. In some cases you may not care, but it's not something you should do lightly.
You could create a parameterized getSomeJobs method to take in an argument saying that you know everything is a DetailedJob, meaning that it would return a DetailedJob list rather than the base class.
If you use instanceof, you wouldn't even need to cast, you could just ask if each element is an instance of a DetailedJob and proceed for there. This is almost no better than looping through each object and casting, however.
While it doesn't directly solve your casting problem I'd be temped to use two methods on the 'other class':
List<BaseJob> getAllJobs();
and
List<DetailedJob> getDetailedJobs();
This makes your code more readable to anyone using the 'other class' and will hopefully prevent mistakes.
Either that or I'd genericise the 'other class' like #Tom Hawtin suggests.
Your other class that provides the getSomeJobs method should implement an interface (to help with your unit testing, among other things). Let's call it JobProvider. You can declare the interface such that it will always produce a list of something that extends a base job, and in subclasses where you know your job is always going to be of a certain sub-type, you can narrow the type definition there.
interface JobProvider {
List<? extends BaseJob> getSomeJobs();
}
class JobProviderImpl implements JobProvider {
public List<DetailedJob> getSomeJobs() {
// do stuff and return
}
}
Now, in other code, if you know you're dealing with a JobProviderImpl, you can case it and know that the list will contain only DetailedJobs.
if (provider instanceof JobProviderImpl) {
List<DetailedJob> detailedJobs = ((JobProviderImpl) provider).getSomeJobs();
}
Make getSomeJobs() or write another function getSomeDetailedJobs() that returns
List < DetailedJob> instead of List < BaseJob>. I dont know how else we can be "sure" about all elements being of type DetailedJobs.

Categories

Resources