In my android app, with retrofit, I want to send an array of objects to my php script with:
#FormUrlEncoded
#POST(Consts.BACKUP_SCRIPT_UP)
Call<Integer> backupUpload(
#Field("deviceName") String deviceName,
#Field("articles[]") List<backupArticle> articles
);
But, I don't find the way to retrieve my datas.
I get deviceName as attended but how to retrieve datas in the array $_REQUEST["articles"] please?
Dump gives something like:
Array (
[deviceName] => 7cdb101d51bb89ca
[articles] => Array
(
[0] => myapp.backupArticle#f3ee606
[1] => myapp.backupArticle#681f4c7
[2] => myapp.backupArticle#6d40af4
[3] => myapp.backupArticle#57321d
[4] => myapp.backupArticle#5d35c92
...
)
)
But I don't really know if my problem is about java/android or php. I'd like to be sure what I send is really what I want to send, but how to test it if I can't retrieve information in php?
I also tried with:
#POST(Consts.BACKUP_SCRIPT_UP)
Call<Integer> backupUpload(
#Body List<backupArticle> articles
);
but I get empty array in php.
java object Class:
public class backupArticle {
#SerializedName("deviceName") #Expose private String deviceName;
#SerializedName("clistName") #Expose private String clistName;
#SerializedName("name") #Expose private String name;
#SerializedName("ord") #Expose private long ord;
#SerializedName("categName") #Expose private String categName;
#SerializedName("categOrd") #Expose private long categOrd;
#SerializedName("qty") #Expose private int qty;
#SerializedName("selected") #Expose private int selected;
public backupArticle(String deviceName, String clistName, String name, long ord, String categName, long categOrd, int qty, int selected) {
this.deviceName = deviceName;
this.clistName = clistName;
this.name = name;
this.ord = ord;
this.categName = categName;
this.categOrd = categOrd;
this.qty = qty;
this.selected = selected;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getClistName() {
return clistName;
}
public void setClistName(String clistName) {
this.clistName = clistName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getOrd() {
return ord;
}
public void setOrd(long ord) {
this.ord = ord;
}
public String getCategName() {
return categName;
}
public void setCategName(String categName) {
this.categName = categName;
}
public long getCategOrd() {
return categOrd;
}
public void setCategOrd(long categOrd) {
this.categOrd = categOrd;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
}
In fact, it seems that the right way is to NOT use $_REQUEST (or $_POST) but (php):
$articles = json_decode(file_get_contents('php://input'));
$deviceName = $articles[0]->deviceName;
with (java/retrofit):
#POST(Consts.BACKUP_SCRIPT_UP)
Call<Integer> backupUpload(
#Body List<backupArticle> articles
);
Related
I know there are a few questions on stackoverflow regarding this problem. But I have have been spending hours trying to resolve this error without any success.
I am using the mysql database to store the values.
I keep on getting the error message from the
com.example.springboot.Recipe file.
This is springboot recipe file
package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
#Entity // This tells Hibernate to make a table out of this class
public class Recipe {
public Recipe(){
}
public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
this.id = id;
this.name = name;
this.description = description;
this.type = type;
this.preptime = preptimee;
this.cooktime = cooktime;
this.content = content;
this.difficulty = difficulty;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String description;
private String type;
private Integer preptime;
private Integer cooktime;
#Column(columnDefinition = "TEXT")
private String content;
private Integer difficulty;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Integer getCookingtime() {
return cooktime;
}
public void setCookingtimeime(Integer cooktime) {
this.cooktime = cooktime;
}
public Integer getPreparationtime() {
return preptime;
}
public void setPreparationtime(Integer preptime) {
this.preptime = preptime;
}
}
Main Controller:
#PutMapping("/recipes/edit/{id}")
void updateRecipe2(#PathVariable int id, #RequestBody Recipe recipe ) {
Recipe recipe_ = recipeRepository.findById(id).get();
recipe_.setTitle(recipe.getTitle());
System.out.println("sss " + recipe.getname());
System.out.println("change");
recipeRepository.save(recipe_);
}
service.ts:
updateRecipe2 (id: number, recipe: any): Observable<any > {
const url = `${this.usersUrl}/edit/${id}`;
return this.http.put(url ,recipe);
}
where the updateRecipe2 gets called:
save(): void {
const id = +this.route.snapshot.paramMap.get('name');
this.recipeService.updateRecipe2(id, this.recipes)
.subscribe(() => this.gotoUserList());
}
as soon as the user clicks save this functions saves the changes made.
I hope the code snippets that I provided are enough to help solve the problem.
Thank you in advance.
I am building a rest api with spring boot and I am using angularjs as it's frontend. I am pretty new to web-development.
You are sending a list of recipes to an api endpoint that expects a single recipe object.
Your options are:
Send only one recipe object at a time, for example:
this.recipeService.updateRecipe2(id, this.recipes[0])
OR: create a new API endpoint to accept a list of recipes, to edit them in "batch"
#PutMapping("/recipes/edit")
void updateRecipes(#RequestBody List<Recipe> recipe ) {
my Example:
Use:
#PostMapping
Code:
public void setTransacciones(List<Transacciones> transacciones) {
this.transacciones = transacciones;
}
CodeBean:
public class Transacciones {
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String text;
}
Post(raw):
{
"transacciones" : [ {"text" : "1"}, {"text" : "2"} ]
}
Result:
{
"transacciones": [
{
"transaccionId": 2,
"text": "1"
},
{
"transaccionId": 3,
"text": "2"
}
]
}
BINGO!!
While producing a list of my Entity I can't convert this to a String.
This is my Team code:
public class Teams {
#SerializedName("teamName")
#Expose
private String teamName;
#SerializedName("matches")
#Expose
private Object matches;
#SerializedName("players")
#Expose
private Object players;
#SerializedName("id")
#Expose
private Integer id;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public Object getMatches() {
return matches;
}
public void setMatches(Object matches) {
this.matches = matches;
}
public Object getPlayers() {
return players;
}
public void setPlayers(Object players) {
this.players = players;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
I'm using the following get:
public interface SoccerStatsApi {
String jsonUrl = "https://soccerstatsapp.azurewebsites.net/api/";
#GET("teams")
Call<List<Teams>> getTeams();`
And this is where I want to convert it to a complete string:
Call<List<Teams>> call = soccerStatsApi.getTeams();
call.enqueue(new Callback<List<Teams>>() {
#Override
public void onResponse(Call<List<Teams>> call, Response<List<Teams>> response) { }
Response().body().toString() only returns the initial string, not the actual object values in the List/response. I've checked everywhere, but so far no answer I can actually work with.
cast Response.body() to List.
for example:
'''List teams = (List)response.body() ;'''
hope you have configured retrofit to use Gson as default json parser
I am trying to get some the array of actors from Jira. The code for the wrapper is used in a Gson.fromJson call. I had used something similar with a json string that did not have an array in it that had the information I needed and it worked fine, so the issue seems to do with the array, but I am not 100% sure:
import com.google.gson.annotations.SerializedName;
public class JiraRoleJsonWrapper {
#SerializedName("self")
private String self;
#SerializedName("name")
private String name;
#SerializedName("id")
private int id;
#SerializedName("description")
private String description;
#SerializedName("actors")
private JiraActors[] actors;
public JiraActors[] getActors() {
return actors;
}
public void setActors(JiraActors[] actors) {
this.actors = actors;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String key) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
public String[] getAvatarUrls() {
return avatarUrls;
}
public void setAvatarUrls(String[] avatarUrls) {
this.avatarUrls = avatarUrls;
}
*/
}
class JiraActors {
#SerializedName("id")
private int id;
#SerializedName("displayNme")
private String displayName;
#SerializedName("type")
private String type;
#SerializedName("name")
private String name;
//#SerializedName("avatarUrl")
//private String avatarUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The json it would receive:
{
"self":"http://someserver.com:8080/apps/jira/rest/api/2/project/10741/role/10002",
"name":"Administrators",
"id":10002,
"description":"A project role",
"actors":[
{
"id":12432,
"displayName":"Joe Smith",
"type":"atlassian-user-role-actor",
"name":"joesmi",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=dawsmi&avatarId=12245"
},
{
"id":12612,
"displayName":"Smurfette Desdemona",
"type":"atlassian-user-role-actor",
"name":"smudes",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=lamade&avatarId=10100"
},
This shows two actors and the format of the json. Please note I did not put a complete json response. It just shows two actors.
In my code, I tried the following to retrieve the actors:
InputStream is = response.getEntityInputStream();
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
JiraRoleJsonWrapper[] jiraRoleJsonWrapper = gson.fromJson(reader, JiraRoleJsonWrapper[].class);
for (JiraRoleJsonWrapper w : jiraRoleJsonWrapper) {
JiraActors[] a = w.getActors();
String name = a.getName();
It does not find getName for some reason. I am not sure why.
I figured it out.
I change the setActors to
public void setActors(ArrayList<JiraActors> actors) {
this.actors = actors;
}
Then I was able to get the array list and get access to the getName() method of JiraActors.
The problem is that I have a table product and my update script doesn't work aparently. It allwas return false.
Product.class
#DatabaseTable(tableName = "Product")
public class Product {
#DatabaseField(index = true, generatedId = true)
private int productId;
#DatabaseField
private String name;
#DatabaseField
private int quantity;
//#DatabaseField(canBeNull = true)
//private Integer categorie;
//http://logic-explained.blogspot.com.ar/2011/12/using-ormlite-in-android-projects.html
#DatabaseField
private int categorie;
//#ForeignCollectionField
//private ForeignCollection<Categorie> itemsCategorie;
#DatabaseField
private String description;
#DatabaseField
private String photo;
Product() {
}
public Product(int productId, String name, int quantity, int categorie, String description, String photo) {
super();
this.productId = productId;
this.name = name;
this.quantity = quantity;
this.categorie = categorie;
this.description = description;
this.photo = photo;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return description;
}
public void setAddress(String address) {
this.description = address;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCategorie() {
return categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public CharSequence getDesc() {
return null;
}
}
my script updateProduct
public boolean updateProduct(Product p) {
boolean ret = false;
if (productDao != null) {
try {
productDao = getDao(Product.class);
UpdateBuilder<Product, Integer> updateBuilder = productDao
.updateBuilder();
updateBuilder.updateColumnValue("name", p.getName());
updateBuilder.updateColumnValue("quantity", p.getQuantity());
updateBuilder.updateColumnValue("categorie", p.getCategorie());
updateBuilder.updateColumnValue("description", p.getDesc());
updateBuilder.updateColumnValue("photo", p.getPhoto());
// but only update the rows where the description is some value
updateBuilder.where().eq("productId", p.getProductId());
// actually perform the update
String str = updateBuilder.prepareStatementString();
// UPDATE `Product` SET `name` = 'gcd' ,`quantity` = 1
// ,`categorie` = 1 ,`description` = ? ,`photo` = '' WHERE
// `productId` = 0
if (productDao.update(updateBuilder.prepare()) != 1) {
ret = false;
} else {
productDao.refresh(p);
ret = true;
}
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
then I call it with a function like this, but allways return false :(
public boolean updateProduct(Product p) {
boolean ret = false;
try {
ret = getHelper().updateProduct(p);
} catch (Exception e) {
e.printStackTrace();
ret =false;
}
return ret;
}
I can create and delete but I can not update . I tried everything.
If you please take a moment to answer my question I will appreciate.
for other developers, if you come face to face with a problem like this you should ensure the table must have an identity key.
#DatabaseTable(tableName = "User")
public class User {
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
public String ServiceUserId;
#DatabaseField
public boolean IsActive;
#DatabaseField
public String FirstName;
#DatabaseField
public String LastName;
#DatabaseField
public String Key;
#DatabaseField
public String Email;
}
The solution was
Simply get the Instance of the object Product from the DB then modify to finaly send to the updateProduct method.
for example first I need to create any method first to get an objet by ID
// get the Instance calling to the getProductByID
Product p = getHelper().getProductByID(p.getId())
//modify any value of the product
p.setFirstName("asd");
//call the update
ret = getHelper().updateProduct(p);
then my objects is Updated.
Put attention for the object Id(should be the same) and use the natif function update(Product);
In your case, you must override equals and hashCode.
I'm trying to figure out a way to transform this JSON String into a Java object graph but I'm unable to do so. Below, I've inserted my JSON String, and my two classes. I've verified that its a valid json structure. I've been trying googles api (http://sites.google.com/site/gson/gson-user-guide) but it doesn't map the nested Photo Collection. Any ideas or alternate libraries?
{"photos":{"page":1,"pages":73514,"perpage":50,"total":"3675674","photo":[{"id":"5516612975","owner":"23723942#N07","secret":"b8fb1fda57","server":"5213","farm":6,"title":"P3100006.JPG","ispublic":1,"isfriend":0,"isfamily":0},{"id":"5516449299","owner":"81031835#N00","secret":"67b56722da","server":"5171","farm":6,"title":"Kaiser Boys Volleyball","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"}
Photos.java
public class Photos {
private int pages;
private int perpage;
private String total;
private List<Photo> photo;
private String stat;
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getPerpage() {
return perpage;
}
public void setPerpage(int perpage) {
this.perpage = perpage;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public List<Photo> getPhoto() {
return photo;
}
public void setPhoto(List<Photo> photo) {
this.photo = photo;
}
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
}
Photo.java:
public class Photo {
private String id;
private String owner;
private String secret;
private String server;
private String farm;
private String title;
private int isPublic;
private int isFriend;
private int isFamily;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getFarm() {
return farm;
}
public void setFarm(String farm) {
this.farm = farm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIsPublic() {
return isPublic;
}
public void setIsPublic(int isPublic) {
this.isPublic = isPublic;
}
public int getIsFriend() {
return isFriend;
}
public void setIsFriend(int isFriend) {
this.isFriend = isFriend;
}
public int getIsFamily() {
return isFamily;
}
public void setIsFamily(int isFamily) {
this.isFamily = isFamily;
}
}
Use Jackson. It'll take care of converting to and from JSON. It provides multiple ways of approaching conversion, and is well-integrated with frameworks like Spring. Definitely one to know.