How to pass two parameters in AsyncTask? - java

I am using MVVM structure and my query in Dao looks like:
#Query("SELECT * FROM Sorted WHERE date LIKE :date AND categoryChart = :category")
LiveData<List<Sorted>> getSortedDiagramData(String date, String category);
In Repository I need to execute this method in AsyncTask, but I don't understand how to do it.
What I've tried:
public LiveData<List<Sorted>> getSortedDiagramData(String date, String category){
String[] array = new String[2];
array[0] = date;
array[1] = category;
return new GetSortedDiagramDataAsyncTask(sortedDao).execute(array);
}
And then:
private static class GetSortedDiagramDataAsyncTask extends AsyncTask<String[], Void, LiveData<List<Sorted>>> {
private SortedDao sortedDao;
private GetSortedDiagramDataAsyncTask(SortedDao sortedDao){
this.sortedDao = sortedDao;
}
#Override
protected LiveData<List<Sorted>> doInBackground(String[] ... strings) {
String date1 = String.valueOf(strings[0]);
String category1 = String.valueOf(strings[1]);
LiveData<List<Sorted>> list = sortedDao.getSortedDiagramData(date1, category1);
return list;
}
}
But when I pass "array" to execute() there is an error "Incompatible types".
Could you please suggest how I can solve this problem? Thanks for any help.

You can pass it in the constructor:
private String date, category;
private SortedDao sortedDao;
public GetSortedDiagramDataAsyncTask(SortedDao sortedDao, String date, String category) {
this.date = date;
this.category = category;
this.sortedDao = sortedDao;
}
#Override
protected LiveData<List<Sorted>> doInBackground(String[]... strings) {
LiveData<List<Sorted>> list = sortedDao.getSortedDiagramData(date, category);
return list;
}
Call it as:
new GetSortedDiagramDataAsyncTask(sortedDao, "date", "category").execute();

Another way would be to use this:
GetSortedDiagramDataAsyncTask(sortedDao).execute(date,category);

Related

List All Data Using Retrofit/OkHttp With Response List

I have some codes that fetch some data from my API. My question is how can I list all the objects that I fetched before without using this jsonData.get(0), I expect something like jsonData.get(i), so I assume using something like below, but I can't use it, so how can I do that? Thanks.
for (int i=0;i<jsonData.length();i++){
MainActivity.java
List<Promo> jsonData = response.body();
Log.i("TESTER",""+jsonData);
String promoID = jsonData.get(0).getId_promo();
String promoTipe = jsonData.get(0).getPromo_type();
String promoValue = jsonData.get(0).getValue_based();
String promoName = jsonData.get(0).getPromo_name();
With POJO class that looks like this
Promo.java
public class Promo {
#SerializedName("id_promo")
private String id_promo;
#SerializedName("promo_name")
private String promo_name;
#SerializedName("promo_type")
private String promo_type;
#SerializedName("value_based")
private String value_based;
#SerializedName("quota")
private String quota;
#SerializedName("id_event")
private String id_event;
#SerializedName("description")
private String description;
public String getId_promo() {
return id_promo;
}
public void setId_promo(String id_promo) {
this.id_promo = id_promo;
}
public String getPromo_name() {
return promo_name;
}
}
ApiUrl.java
#FormUrlEncoded
#POST("promopublic")
Call<List<Promo>> getPromo(
#Field("id_event") String id_event,
#Field("total_buyer") String totalBuyer,
#Field("id_user") String id_user,
#Field("id_ticket") String id_ticket);
Using for loop like below solved my problem
for (int i=0;i<jsonData.size();i++){}

How to pass a list variable into a constructor/method

I'm new to Java. I'm having issues passing a List variable that is part of a constructor definition when I created an object of the class
public class Patient {
private String patientfirstName;
private String patientLastName;
private List<String> allergyList;
public Patient(String patientfirstName, String patientLastName,
List<String> allergyList) {
this.patientfirstName = patientfirstName;
this.patientLastName = patientLastName;
this.allergyList = allergyList;
}
Patient patientobj = new Patient("sean","john","allegry1");
gives an error: "constructor "Str,str,str" not defined."
I need help on how to pass the allergy
Your need a List<String> instead of a single String, Arrays.asList(T...) is probably the easiest solution:
Patient patientobj = new Patient("sean", "john", Arrays.asList("allergy1"));
And if you have more allergies
Patient patientobj = new Patient("sean", "john",
Arrays.asList("allergy1", "allergy2"));
public class Patient {
private String patientfirstName;
private String patientLastName;
private List<String> allergyList;
public Patient(String patientfirstName, String patientLastName,
List<String> allergyList) {
this.patientfirstName = patientfirstName;
this.patientLastName = patientLastName;
this.allergyList = allergyList;
}
*Patient patientobj = new Patient("sean","john","allegry1");*// this is wrong you have to pass a list not the string. you should do something like this:
// first create a list and add the value to it
List<String> list = new ArrayList<>();
list.add("allergy1");
// now create a object and pass the list along with other variables
Patient patientobj = new Patient("sean","john",list);
You also has a solutionis just add one constructor of the class Patient.
public Patient (String patientfirstName,String patientLastName,String allergeyList){
this.patientfirstName = patientfirstName;
this.patientLastName = patientLastName;\
this.allergeyList = new ArrayList<>( Arrays.asList(allergeyList));
}
In my opinion, you could use Varargs.
Thanks to varargs you can put into the parameters how many arguments do you want
public class Patient {
public String patientfirstName;
public String patientLastName;
public List<String> allergyList;
public Patient(String fName,String lName,String...aList) {
this.patientfirstName = fName;
this.patientLastName = lName;
this.allergyList = Arrays.asList(aList);
}
public static void main(String[] args) {
Patient firstPatient = new Patient("Foo", "Bar", "First Allergy","Second Allergy");
Patient secondPatient = new Patient("Foo", "Baz", "First Allergy","Second Allergy","Third Allergy","Fourth Allergy");
Patient ThirdPatient = new Patient("Foo", "Foo", "First Allergy");
}
The parameter "aList" is like an array because varargs is like an array with no specific lenght,the length you choose when you enter the parameters, as you can see
The type of allergyList is by choice.. you can also do this:
In "Patient" attributes:
public String[] allergyList;
In the costructor:
public Patient(String fName,String lName,String...aList) {
this.patientfirstName = fName;
this.patientLastName = lName;
this.allergyList = allergyList;
}

Time is not returned as dynamic because of static issue

I need to show the latest timestamp through my service class:
#Service
public class UserServiceImpl implements UserService {
private static final AtomicInteger counter = new AtomicInteger();
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
static Timestamp timestamp = new Timestamp(System.currentTimeMillis());
static List<User> users = new ArrayList<User>(
Arrays.asList(
new User("123","abc","A1234567", "a529794b3ea9c05d8f0b5f354dac25e5", "Role-A","Screen A","Execute",sdf.format(timestamp) )));
#Override
public List<User> getAll(int offset, int count) {
return users;
}
The output looks as follows:
[{"hkid":"123","username":"abc","passportNo":"A1234567","tokenId":"a529794b3ea9c05d8f0b5f354dac25e5","role":"Role-A","permission":"Execute","timestamp":"2018.04.02.12.16.19","screen":"Screen A"}]
Now the issue is that timestamp is not returned as current one as my timestamp filed is static. What necessary changes do I need to make to always get the current timestamp. I have to work with the static object.
Just to add: In pojo I have taken a timestamp as a string
public class User implements Serializable {
private String id;
private String username;
private String passportNo;
private String tokenId;
private String role;
private String Screen ;
private String permission;
private String timestamp ;
You could dynamically update it every time getAll is called:
#Override
public List<User> getAll(int offset, int count) {
String ts = sdf.format(new Timestamp(System.currentTimeMillis()));
users.forEach(u -> u.setTimestamp(ts));
return users;
}
Put
Arrays.asList(
new User("123","abc","A1234567", "a529794b3ea9c05d8f0b5f354dac25e5", "Role-A","Screen A","Execute",sdf.format(timestamp) )))
inside your method. In Spring framework beans are loaded as Singletons, so it's a bad practice to use the class variable. Only use method variables.
Member variables that are declared static are only initialized once during construction.
In your case the timestamp and the array of User objects both require dynamic creation (or you need to add a setter method for the timestamp to the User object and call it during).
So in your getAll method you need to create the array of users and along with it the timestamp which is then formatted into the response.
#Override
public List<User> getAll(int offset, int count) {
List<User> response = new ArrayList<User>();
Timestamp ts = new Timestamp(System.currentTimeMillis());
response.add(new User("123","abc","A1234567", "a529794b3ea9c05d8f0b5f354dac25e5", "Role-A","Screen A","Execute",sdf.format(ts) ));
return response;
}
Variation with setter:
#Override
public List<User> getAll(int offset, int count) {
Timestamp ts = new Timestamp(System.currentTimeMillis());
for(User user : users)
{
user.setTimestamp(sdf.format(ts));
}
return users;
}

java ArrayList with two columns

I have to update a table with two columns and I have created a class
public class Country {
private String url;
private String search;
public Country(String url, String search) {
this.url = url;
this.search = search;
}
// ...
}
List<Country> countries = new ArrayList<Country>();
countries.add(new Country(urls, txt));
...
Countries has a data {java.com.main#yfxse34567}
Could be {www.google.com, main string...}
How can I put a proper data into countries list
Override the toString() method
Example
List<Country> countries = new ArrayList<Country>() {
#Override
public String toString() {
String result = "{";
for (int index= 0; index < size(); index++){
result = result.concat(this.get(index).url);
if (index != size()-1) {
result = result.concat(", ");
}
}
result = result.concat("}");
return result;
}
};
For me your solution should work, however try to instantiate the parent first and then add the instance ... Something like
Country instanceCountry = new Country();
instanceCountry.setUrl("www.google.com");
instanceCountry.setSearch("xpto");
countries.add(instanceCountry);
Do not forget to generate the Getters and Setters

Cannot add list of objects to my collection

In my main activity I have two lists:
private List<Feed> feedItems;
private ArrayList<Object> adItems() {
ArrayList<Object> adItems = new ArrayList<>();
adItems.add("image");
adItems.add("image");
adItems.add("image");
return adItems;
}
The first list represents my feedItems, which are taken from my network model. The second list is simply a list of static images. I'm trying to set up native advertisements but I'm taking it a step back and simply supplying my feed with images to prove that overriding my RecyclerAdapter to produce multiple views works.
feedRecyclerAdapter = new FeedRecyclerAdapter(this, feedItems, new ImageLoader(new FeedItemFileCache(this)), adItems());
Here I pass my adItems() list of objects in the my FeedRecyclerAdapter as the last paramater, and in the adapter class itself I call it in the constructor:
public FeedRecyclerAdapter(Context context, List<Feed> feedItems, ImageLoader feedItemImageLoader, List<Object> adItems) {
this.context = context;
this.feedItems = feedItems;
this.feedItemImageLoader = feedItemImageLoader;
feedItems.addAll(adItems);
}
This last line feedItems.addAll(adItems); is where I get the following error message:
Error:(43, 18) error: no suitable method found for addAll(List<Object>)
method Collection.addAll(Collection<? extends Feed>) is not applicable
(argument mismatch; List<Object> cannot be converted to Collection<? extends Feed>)
method List.addAll(Collection<? extends Feed>) is not applicable
(argument mismatch; List<Object> cannot be converted to Collection<? extends Feed>)
My Feed object looks like this:
public class Feed {
public static final String CLASS_NAME = "Feed";
public static final String MARKET_CLASS_NAME = "MarketFeed";
private String objectId;
private String createdAt;
/**
* Can be a ParsePointer but we are using a relational include query to get the whole object
*/
private Design designId;
// Not part of the model, calculated at run time.
private String timestampText;
private boolean isInPersonalGallery;
private boolean isLiked;
private List<Comment> comments;
// Related to Market Feed Items
private DisplayedSide displayedSide = DisplayedSide.FRONT;
public enum DisplayedSide {
FRONT,
BACK
}
public String getObjectId() {
return objectId;
}
public Design getDesign() {
return designId;
}
public Date getCreatedAt() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
Date date = null;
try {
date = dateFormat.parse(createdAt);
} catch (ParseException e) {
e.printStackTrace();
Log.d("Feed", "Couldn't parse createdAt date when requested " + createdAt);
}
return date;
}
public String getTimestampText() {
return timestampText;
}
public void setTimestampText(String timestampText) {
this.timestampText = timestampText;
}
public boolean isInPersonalGallery() {
return isInPersonalGallery;
}
public void setInPersonalGallery(boolean inPersonalGallery) {
isInPersonalGallery = inPersonalGallery;
}
public boolean isLiked() {
return isLiked;
}
public void setLiked(boolean liked) {
isLiked = liked;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public DisplayedSide getDisplayedSide() {
return displayedSide;
}
public void setDisplayedSide(DisplayedSide displayedSide) {
this.displayedSide = displayedSide;
}
}
In summary, I'm trying to sprinkle some images, or adItems, between the main objects in my Collection, feedItems. Why can't I simply attach them to my main list? And what can I do instead?
you are set in wrong array
feedItems.addAll(adItems);//you are set adItems in wrong arraylist (feedItems is a feetItem array list not a adItem list)
public FeedRecyclerAdapter(Context context, List<Feed> feedItems, ImageLoader feedItemImageLoader, List<Object> adItems) {
this.context = context;
this.feedItems = feedItems;
this.feedItemImageLoader = feedItemImageLoader;
feedItems.addAll(adItems);
}`
In the onCreate method of my main activity I set adItems to be a Feed list, then passed it to my RecyclerAdapter constructor:
List<Feed> adItems = new ArrayList<>();
feedRecyclerAdapter = new FeedRecyclerAdapter(this, feedItems, new ImageLoader(new FeedItemFileCache(this)), adItems);
In my RecyclerAdapter class I added all adItems to the feedItems list so that I could operate over a single list:
public FeedRecyclerAdapter(Context context, List<Feed> feedItems, ImageLoader feedItemImageLoader, List<Feed> adItems) {
this.context = context;
this.feedItems = feedItems;
this.feedItemImageLoader = feedItemImageLoader;
feedItems.addAll(adItems);
}

Categories