【发布时间】:2019-01-02 12:00:46
【问题描述】:
我正在尝试从 android studio textview php 中的数据库中获取值以进行数据库连接。我正在使用 Retrofit 库。下面是我为获取值而编写的代码......我收到了这个错误 "使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 接受格式错误的 JSON"
public class MainActivity extends AppCompatActivity {
TextView nametxt, agetxt, phonetxt, emailtxt;
Button retrieveBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nametxt = (TextView) findViewById(R.id.nametxt);
agetxt = (TextView) findViewById(R.id.agetxt);
phonetxt = (TextView) findViewById(R.id.phonetxt);
emailtxt = (TextView) findViewById(R.id.emailtxt);
retrieveBtn = (Button) findViewById(R.id.retrieveBtn);
retrieveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchData();
}
});}
private void fetchData() {
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080/demo/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<List<Details_Pojo>> call = api.getstatus();
call.enqueue(new Callback<List<Details_Pojo>>() {
@Override
public void onResponse(Call<List<Details_Pojo>> call, Response<List<Details_Pojo>> response) {
List<Details_Pojo> adslist = response.body();
String name = adslist.get(0).getName();
String age = adslist.get(0).getAge();
String phone = adslist.get(0).getPhone();
String email = adslist.get(0).getEmail();
nametxt.setText(name);
agetxt.setText(age);
phonetxt.setText(phone);
emailtxt.setText(email);
}
@Override
public void onFailure(Call<List<Details_Pojo>> call, Throwable t) {
Toast.makeText(MainActivity.this, ""+t.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
}}
我已经创建了 API.java 接口文件
公共接口 API {
String BASE_URL = "http://10.0.2.2:8080/demo/";
@GET("fetch_data.php")
Call<List<Details_Pojo>> getstatus();
}
【问题讨论】:
-
您想使用您的应用程序从 REST Api 检索数据?您应该研究改造之类的工具。
-
我添加了改造库,但出现此错误“使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 接受格式错误的 JSON”
-
似乎没有使用
gson对象。要使用它来解析传入的 JSON 数据,请使用.addConverterFactory(GsonConverterFactory.create(gson))。但是,您收到的数据似乎与有效的 JSON 语法不匹配,使用 thisGson对象无法解决此问题。要么修复服务器的响应,要么以不同的方式处理接收到的数据。