我是ANdroid的新手,这是我对Retrofit的第一次测试。我使用Retofit来调用API,如下所示。 我的问题是,当我运行应用程序时,我得到空白屏幕。我想在列表中显示音频文件,然后播放选定的音频。我的api看起来像这样:
我正在使用Retrofit来调用这个Api。这就是Restclient和RestInterface我使用`
public class RestClient {
private static RestInterface mInterface;
public static RestInterface getClient() {
if (mInterface == null) {
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverter(String.class, new ToStringConverter())
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
mInterface = client.create(RestInterface.class);
}
return mInterface;
}
public interface RestInterface {
@GET("/bins/15oqx")
Call<AudioReturn> audioReturn();
}
使用的适配器就像这个`
public class AudioAdapter extends
RecyclerView.Adapter<AudioAdapter.AudioViewHolder> {
Context mContext;
private ArrayList<AudioReturn.data> mAudioReturn = new ArrayList<>();
public AudioAdapter(Context context, ArrayList<AudioReturn.data> list) {
mContext = context;
mAudioReturn = list;
}
@Override
public int getItemCount() {
return mAudioReturn.size();
}
@Override
public void onBindViewHolder(AudioViewHolder holder, int position) {
AudioReturn.data current = mAudioReturn.get(position);
holder.track.setText(current.getTrack());
holder.trackname.setText(mAudioReturn.get(position).getTrackname());
}
@Override
public AudioAdapter.AudioViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.view_audio_files, viewGroup, false);
return new AudioAdapter.AudioViewHolder(itemView);
}
public void updateData(ArrayList<AudioReturn.data> datas) {
this.mAudioReturn = datas;
notifyDataSetChanged();
}
public class AudioViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.view_audio_file_Track_Number)
TextView track;
@Bind(R.id.view_audio_file_Audio_Name)
TextView trackname;
public AudioViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
和Pojo是`public class AudioReturn { ArrayList dataList = new ArrayList&lt;&gt;();
public class data {
String track, trackname;
public data(String track, String trackname) {
this.track = track;
this.trackname = trackname;
}
public String getTrack() {
return track;
}
public String getTrackname() {
return trackname;
}
}
public AudioReturn(ArrayList<data> dataList) {
this.dataList = dataList;
}
public ArrayList<data> getDataList() {
return dataList;
}
我得到的结果是空白的。我打电话来自ACtivity:
AudioAdapter mAudioAdapter = new AudioAdapter(this, datas);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAudioAdapter);
RestClient.RestInterface restInterface = RestClient.getClient();
Call<AudioReturn> audioReturnCall = restInterface.audioReturn();
audioReturnCall.enqueue(new Callback<AudioReturn>() {
@Override
public void onResponse(Response<AudioReturn> response) {
datas = response.body().getDataList();
mAudioAdapter.updateData(datas);
Toast.makeText(AudioActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(AudioActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
}`
答案 0 :(得分:0)
在你的json中,曲目列表被称为data
。
但是在您的班级AudioReturn
中,您将其称为dataList
,将其更改为data
,它应该有效。
修改强>
将您的数据类替换为:
public class Data {
// The fields names should be exactly equal to the one of the json
private String track;
private String trackName;
// Retrofit needs a default constructor
public Data() {
}
public Data(String track, String trackName) {
this.track = track;
this.trackName = trackName;
}
// Retrofit needs getters and setters for each field
public String getTrack() {
return track;
}
public void setTrack(String track) {
this.track = track;
}
public String getTrackName() {
return trackName;
}
public void setTrackName(String trackName) {
this.trackName = trackName;
}
}
您的AudioReturn课程:
public class AudioReturn {
// The fields names should be exactly equal to the one of the json
private List<Data> data;
// Retrofit needs a default constructor
public AudioReturn() {
}
public AudioReturn(List<Data> data) {
this.data = data;
}
// Retrofit needs getters and setters for each field
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
}
答案 1 :(得分:0)
**Retrofit to calling api**
*****ApiInterface*****
public interface ApiInterface
{
// add
@FormUrlEncoded
@POST("/login.php")
void login(
@Field("email_address") String email_address,
@Field("password") String password,
Callback<Response> user);
//get
@FormUrlEncoded
@POST("/get_followers_following_list.php")
void getfollowingList(
@Field("user_id") String user_id,
@Field("type") String type,
Callback<Response> user);
}
*RestClient*
public class RestClient extends Activity
{
private static ApiInterface REST_CLIENT;
static {
setupRestClient();
}
private RestClient()
{
}
private static void setupRestClient()
{
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ItemTypeAdapterFactory()) // This is the important line ;)
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
REST_CLIENT = buildAdapter(Constant.URL, gson).create(ApiInterface.class);
}
private static RestAdapter buildAdapter(String endPoint, Gson gson)
{
return new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(endPoint)
.setConverter(new GsonConverter(gson))
.build();
}
public static ApiInterface getDemo() {
return REST_CLIENT;
}
}
**// Add login**
login(edit_email.getText().toString(), edit_password.getText().toString());
private void login(String email, String password) {
if (Util.isOnline(LoginActivity.this)) {
loginCallApi(email, password);
} else {
Toast.makeText(LoginActivity.this, R.string.no_internet_fount, Toast.LENGTH_SHORT).show();
}
}
private void loginCallApi(String email, String password) {
ShowProgress();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("email_address", edit_email.getText().toString());
params.put("password", edit_password.getText().toString());
client.post(this, Constant.URL + "login.php?", params, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
}
@Override
public void onFinish() {
super.onFinish();
}
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
LoginResponse model = new Gson().fromJson(new String(String.valueOf(response)), LoginResponse.class);
Hideprogress();
if (model.getStatus().equalsIgnoreCase("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(LoginActivity.this, "User Login Successfully", Toast.LENGTH_SHORT).show();
Utils.WriteSharePrefrence(LoginActivity.this, Constant.USERID, model.getData().getId());
String Userid = Utils.ReadSharePrefrence(LoginActivity.this, Constant.USERID);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(LoginActivity.this, model.getMsg().toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e(TAG, throwable.getMessage());
Hideprogress();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
}
**// get**
if (Util.isOnline(FollowersActivity.this)) {
getFollowersList();
} else {
Toast.makeText(FollowersActivity.this, R.string.no_internet_fount, Toast.LENGTH_SHORT).show();
}
private void getFollowersList() {
followLists = new ArrayList<>();
progress = new ACProgressFlower.Builder(FollowersActivity.this)
.direction(ACProgressConstant.DIRECT_CLOCKWISE)
.themeColor(Color.WHITE)
.fadeColor(Color.DKGRAY).build();
progress.setCanceledOnTouchOutside(false);
progress.show();
RestClient.getDemo().getfollowingList(Utils.ReadSharePrefrence(FollowersActivity.this, Constant.SONG_POST_ID),
"followers",
new Callback<Response>() {
@Override
public void success(Response response, Response response2) {
progress.dismiss();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(Util.getString(response.getBody().in()));
Gson gson = new Gson();
if (jsonObject.getString("status").equals("true")) {
GetFollowList data = gson.fromJson(jsonObject.toString(), GetFollowList.class);
followLists = data.getFollowers();
peopleLikeAdapter = new FollowersAdapter(FollowersActivity.this, followLists);
item_peoplelike_list.setLayoutManager(new LinearLayoutManager(FollowersActivity.this, LinearLayoutManager.VERTICAL, false));
item_peoplelike_list.setAdapter(peopleLikeAdapter);
} else {
progress.dismiss();
Toast.makeText(FollowersActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failure(RetrofitError error) {
progress.dismiss();
Toast.makeText(FollowersActivity.this, "Something went wrong, please try again.", Toast.LENGTH_SHORT).show();
}
});
}