[英]How to display json data in attribut
我正在嘗試將json數據放到listview屬性中,但數據不會顯示在屬性中。 數據顯示在RUN窗口中。 如何將數據放入屬性? 我使用片段顯示列表視圖在此處輸入圖像描述
我的主要片段:
api = retrofitClient.getClient("http://10.8.0.2:5000/").create(Api.class);
String encoding = Base64Encoder.encode(UtilsApi.username + ":" + UtilsApi.password);
Log.d(TAG, "listsensor: "+api.listSensor(UtilsApi.username,UtilsApi.password,"Basic "+encoding));
api.listSensor(UtilsApi.username, UtilsApi.password, "Basic " + encoding)
.enqueue(new Callback<List<Sensor>>() {
@Override
public void onResponse(Call<List<Sensor>> call, Response<List<Sensor>> response) {
if (response.isSuccessful()) {
try {
Toast.makeText(getActivity().getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
JSONObject jsonRESULTS = new JSONObject(response.body().toString());
sensors = (List<Sensor>) response.body();
listView.setAdapter(new SensorListAdapter(getActivity().getApplicationContext(), sensors));
}catch (JSONException e){
e.printStackTrace();
}
}else {
Toast.makeText(getActivity().getApplicationContext(), "Sensor Failed", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<List<Sensor>> call, Throwable t) {
Toast.makeText(getActivity().getApplicationContext(), "Sensor Failed", Toast.LENGTH_LONG).show();
Log.d(TAG, "INI: " + sensors);
}
});
}
SensorListAdapter:
private Context context;
private List<Sensor> sensors;
public SensorListAdapter(Context context, List<Sensor> sensors){
super(context, R.layout.list_sensor_item, sensors);
this.context = context;
this.sensors = sensors;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.list_sensor_item,parent,false);
Sensor sensor = sensors.get(position);
return convertView;
接口:
@FormUrlEncoded // List Sensor
@POST("/api/sensors/v1.0/listsensors")
Call<List<Sensor>> listSensor(
@Field("username") String username,
@Field("password") String password,
@Header("Authorization") String authtoken);
改造客戶
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
if (retrofit==null){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
根據Json結構,List本身是外部Json Object的一部分。 假設SensorsObject,因此使用SensorsObject作為響應,並且List將是此類的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.