【发布时间】:2018-04-13 12:09:57
【问题描述】:
我正在尝试学习改造,尽管从数据库中检索文本相当容易。我在向数据库提交数据时有点麻烦。
我提交的数据进入数据库,但每次我提交数据时都会显示此错误。toast 显示 - 预期为 BEGIN_OBJECT 但在第 1 行第 2 列路径 $
这是我的 RegisterAPI 活动:
公共接口 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;
}
}
这是我的插入活动:
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();
}
});
}
检索文本
[{"name":"Gionne","age":"12"},
{"name":"Harley","age":"25"},
{"name":"Gamboa","age":"30"},
{"name":"Lapuz","age":"35"}]
回答以下问题
好吧,我想回答我自己的问题,但我无法在下面回答,因为我被标记为重复。无论如何,问题是两件事,我的 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;
}
【问题讨论】:
-
@NabinBhandari 所以从我读到的,因为它是一个字符串,我将首先将数据转换为 JSON,然后提交数据先生?
-
使用Gson进行改造时,接收到的数据必须是有效的JSON格式。否则你会得到异常。
-
显示你的 json 输出。
-
@ved 嘿先生,我已经添加了我的 json :D
-
您的输出是 JSONArray 而不是 JSONObject。将您的调用对象更改为
Call<List<Person>> call并根据此更改您的方法。
标签: android retrofit retrofit2