我正在尝试学习改造,尽管从数据库中检索文本相当容易。我在向数据库提交数据时遇到了麻烦。
我提交的数据会进入数据库,但每次提交数据时都会显示此错误。吐司说 - 预计BEGIN_OBJECT但是STRING在第1行第2列路径$
这是我的RegisterAPI活动:
public interface RegisterAPI {
@FormUrlEncoded
@POST("/insertText.php")
Call<Result> createUser(
@Field("name") String name,
@Field("age") String age);
}
这是我的Person类:
public class Person {
@SerializedName("name")
private String name;
@SerializedName("age")
private String age;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
这是我的insertActivity:
public static String ROOT_URL = "https://MYURL/";
public void insertUser(){
String name = editTextName.getText().toString().trim();
String age = editTextAge.getText().toString().trim();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RegisterAPI api = retrofit.create(RegisterAPI.class);
Person user = new Person(name, age);
Call<Person> call = api.createUser(user.getName(),user.getAge());
call.enqueue(new Callback<Person>() {
@Override
public void onResponse(Call<Person> call, Response<Person> response) {
Toast.makeText(insertActivity.this, "SUCCESS", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Person> call, Throwable t) {
Toast.makeText(insertActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
RetrieveText
[{"name":"Gionne","age":"12"},
{"name":"Harley","age":"25"},
{"name":"Gamboa","age":"30"},
{"name":"Lapuz","age":"35"}]
回答以下问题
我想回答我自己的问题,但我无法回答,因为我被标记为DUPLICATE。无论如何,问题是两件事,我的PHP insertText.php 文件和我的Objects类。
这是我的insertText.php文件:
<?php
require_once('dbConnect.php');
$name = $_POST['name'];
$age = $_POST['age'];
$sql = "INSERT INTO javaScriptTesting
(name,age)
VALUES
('$name','$age')";
if(mysqli_query($con,$sql)) {
//ADDED THIS LINE
$response["message"] = "DATA INSERTED";
echo json_encode($response);
} else {
//ADDED THIS LINE
$response["message"] = "UNSUCCESSFUL";
echo json_encode($response);
}
mysqli_close($con);
然后这是我的Objects类:
public class Person {
@SerializedName("name")
private String name;
@SerializedName("age")
private String age;
//ADDED THIS LINE
private String message;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
//ADDED THIS LINE
public String getMessage() {
return message;
}
答案 0 :(得分:1)
在改造2.0中执行上述POST请求时,您应该像这样使用RequestBody类型作为参数。
@Multipart
@POST("XXXX")
Call<PlanResponse> myPlans(@Part(Constants.ACTION_ID) RequestBody actionId, @Part(Constants.OFFER_CODE) RequestBody offerCode);
这里是如何从String获取requestBody。
String somevalue = "somevalue";
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), somevalue);