第一次使用后,RetroFit Call失败

时间:2018-06-03 11:37:36

标签: android json android-recyclerview nullpointerexception retrofit2

我的RetroFit调用获取了一个包含两个字符串和两个对象的列表,这是第一次成功,但每次之后响应由于某种原因得到一个空体。 这是它的适配器:

public class AssistsAdapter extends RecyclerView.Adapter<AssistsAdapter.AssistsViewHolder> {
private List<TopAssists> mTopAssistsList;
private int mRowLayout;
private Context mContext;
public class AssistsViewHolder extends RecyclerView.ViewHolder{
    LinearLayout assistsLayout;
    TextView playerRank, playerAssists, playerName, playerTeam;

    public AssistsViewHolder(View itemView) {
        super(itemView);
        assistsLayout = itemView.findViewById(R.id.assists_layout);
        playerRank = itemView.findViewById(R.id.assists_rank);
        playerAssists = itemView.findViewById(R.id.assists_assists);
        playerName = itemView.findViewById(R.id.assists_player);
        playerTeam = itemView.findViewById(R.id.assists_team);
    }
}

public AssistsAdapter(List<TopAssists> topAssistsList, int rowLayout, Context context){
    mTopAssistsList = topAssistsList;
    mRowLayout = rowLayout;
    mContext = context;
}

@NonNull
@Override
public AssistsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(mRowLayout, parent, false);
    AssistsViewHolder holder = new AssistsViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(AssistsViewHolder holder, int position) {
    holder.playerRank.setText(String.valueOf(mTopAssistsList.get(position).getRank()));
    holder.playerAssists.setText(String.valueOf(mTopAssistsList.get(position).getAssists()));
    holder.playerName.setText(mTopAssistsList.get(position).getPlayer().getName());
    holder.playerTeam.setText(mTopAssistsList.get(position).getTeam().getName());
}

@Override
public int getItemCount() {
    return this.mTopAssistsList.size();
}

这是启动RetroFit调用的片段:

public class TournamentsInfoFragment extends Fragment {
private final static String TAG = "Call Failed";
private StandingsAdapter mStandingsAdapter;
private RecyclerView mRecyclerView;
private ProgressBar mProgressBar;
private String mTournamentId;
private String mRegion;
private String mKey;
private GoalsAdapter mGoalsAdapter;
private AssistsAdapter mAssistsAdapter;
private TextView mFailedMessage;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_standings, container, false);
    // Initializing the failure message in case of an error
    mFailedMessage = view.findViewById(R.id.standings_failed);
    // Getting the arguments from the previous fragment
    Bundle bundle = getArguments();
    mTournamentId = bundle.getString("tournament_id");
    mRegion = bundle.getString("region");
    mKey = bundle.getString("key");
    // Showing the Progressbar
    mProgressBar = view.findViewById(R.id.standings_progress_bar);
    // Creating an instance of the ApiInterface
    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
    // Calling to get the standings from the API
    Call<StandingsResponse> call = apiService.getStandings(mRegion, mTournamentId, mKey);
    // Logging the URL Call
    Log.wtf("URL Called", call.request().url() + "");
    call.enqueue(new Callback<StandingsResponse>() {
        @Override
        public void onResponse(Call<StandingsResponse> call, Response<StandingsResponse> response) {
            // Checking the response code to act accordingly
            if(response.code() == 404){
                mFailedMessage.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.GONE);
            }
            else{
                if (response.body() == null){
                    Toast.makeText(getActivity().getApplicationContext(),
                           R.string.standings_problem, Toast.LENGTH_LONG).show();
                    mProgressBar.setVisibility(View.GONE);
                }
                else {
                    generateStandings(response.body().getStandings());
                    mStandingsAdapter.notifyDataSetChanged();
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        }
        @Override
        public void onFailure(Call<StandingsResponse> call, Throwable t) {
            Log.e(TAG, t.toString());
            Toast.makeText(getActivity(), R.string.enqueue_failure, Toast.LENGTH_LONG).show();
            mProgressBar.setVisibility(View.GONE);
        }
    });
    // Calling to get the Goals and assists leaders from the API
    Call<LeadersResponse> leadersCall = apiService.getLeaders(mRegion,mTournamentId,mKey);
    // Logging the URL Call
    Log.wtf("Leaders URL Called", leadersCall.request().url() + "");
    leadersCall.enqueue(new Callback<LeadersResponse>() {
        @Override
        public void onResponse(Call<LeadersResponse> call, Response<LeadersResponse> response) {
            // Checking the response code and acting accordingly
            if(response.code() == 404){
                mFailedMessage.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.GONE);
            }
            else{
                if (response.body() == null){
                    Toast.makeText(getActivity().getApplicationContext(),
                            R.string.leaders_problem, Toast.LENGTH_LONG).show();
                    mProgressBar.setVisibility(View.GONE);
                }
                else {
                    generateGoals(response.body().getTopGoalsList());
                    generateAssists(response.body().getTopAssists());
                    mGoalsAdapter.notifyDataSetChanged();
                    mAssistsAdapter.notifyDataSetChanged();
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        }
        @Override
        public void onFailure(Call<LeadersResponse> call, Throwable t) {
            Log.e(TAG, t.toString());
            Toast.makeText(getActivity(), R.string.enqueue_failure, Toast.LENGTH_LONG).show();
            mProgressBar.setVisibility(View.GONE);
        }
    });
    return view;
}

/**
 * Method to generate List of standings using RecyclerView with custom adapter
 */
private void generateStandings(final List<Standings> empDataList) {
    mRecyclerView = getView().findViewById(R.id.standings_rv);
    mStandingsAdapter = new StandingsAdapter(empDataList, R.layout.item_standings, getActivity());
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.setAdapter(mStandingsAdapter);
}

/**
 * Method to generate List of Goal leaders using RecyclerView with Custom adapter
 */
private void generateGoals(List<TopGoals> topGoals) {
    mRecyclerView = getView().findViewById(R.id.goals_rv);
    mGoalsAdapter = new GoalsAdapter(topGoals, R.layout.item_goals, getActivity());
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.setAdapter(mGoalsAdapter);
}

/**
 * Method to generate List of assists leaders using RecyclerView with Custom adapter
 */
private void generateAssists(List<TopAssists> topAssists) {
    mRecyclerView = getView().findViewById(R.id.assists_rv);
    mAssistsAdapter = new AssistsAdapter(topAssists, R.layout.item_assists, getActivity());
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.setAdapter(mAssistsAdapter);
}

它首次显示了RecyclerView,但每次响应体都为空并导致NullPointerException之后,我必须创建一个if语句和Toast,以防止应用程序崩溃。 错误日志:

6-03 21:55:51.241 6034-6034/com.mad.footstats E/URL Called: https://api.sportradar.us/soccer-t3/eu/en/tournaments/sr:tournament:17/standings.json?api_key=w7c74newrykj8m57rda6xwrk 06-03 21:55:51.253 6034-6034/com.mad.footstats E/Leaders URL Called: https://api.sportradar.us/soccer-t3/eu/en/tournaments/sr:tournament:17/leaders.json?api_key=w7c74newrykj8m57rda6xwrk 06-03 21:55:51.278 6034-6034/com.mad.footstats E/RecyclerView: No adapter attached; skipping layout 06-03 21:55:51.279 6034-6034/com.mad.footstats I/chatty: uid=10085(com.mad.footstats) identical 1 line 06-03 21:55:51.279 6034-6034/com.mad.footstats E/RecyclerView: No adapter attached; skipping layout 06-03 21:55:51.507 1393-3495/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 10934976 , only wrote 10934640 06-03 21:55:51.557 1393-3495/? W/audio_hw_generic: Hardware backing HAL too slow, could only write 0 of 720 frames

0 个答案:

没有答案