使用okhttp从异步调用中填充列表视图

时间:2019-03-08 04:25:03

标签: android listview okhttp3

在Android Studio中,我试图创建一个片段,在该片段上显示一个项目列表,这些项目是使用okhttp从Http调用中获得的。

问题是我的适配器似乎无法正常工作。我没有任何错误或其他任何信息,但未显示我的列表。就其本身而言,Http调用是有效的,我得到了一个汽车品牌列表,该列表映射到类型为gson with gson的列表。

这是我到目前为止的内容:

public class MakeFragment extends Fragment {

private List<Make> allMake = new ArrayList<>();
ListView listView;
MakeAdapter adapter;

private OnFragmentInteractionListener mListener;

public MakeFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View root = inflater.inflate(R.layout.fragment_make, container, false);

    listView = (ListView) root.findViewById(R.id.make_list);
    adapter = new MakeAdapter(allMake,getContext());
    listView.setAdapter(adapter);

    new MyTask().execute();

    return root;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}


public class MyTask extends AsyncTask<Void,Void,List<Make>> {

    @Override
    protected List<Make> doInBackground(Void... voids) {
        ImaApi api = new ImaApiImpl();
        return api.getAllMake();
    }

    @Override
    protected void onPostExecute(List<Make> result) {
        super.onPostExecute(result);
        allMake.addAll(result);
        adapter.notifyDataSetChanged();
    }

}}

我的适配器:

public class MakeAdapter extends BaseAdapter{

    List<Make> list = new ArrayList<>();
    Context context;

    public MakeAdapter(List<Make> list, Context context) {
        this.list = list;
        this.context = context;
    }

    public void setList(List<Make> list ){
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        ViewHolder viewHolder;

        if (convertView == null){

            View view = LayoutInflater.from(context).inflate(R.layout.make_list_item,parent,false);

            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        Make make = list.get(position);

        viewHolder.textView.setText(make.name);

        return viewHolder.itemView;
    }

    public static class ViewHolder{

        TextView textView;
        View itemView;

        public ViewHolder(View itemView) {
            this.itemView = itemView;
            textView = itemView.findViewById(R.id.text_view);
        }

    }
}

我的make_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_marginTop="10dp">
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:textSize="20dp"
        android:maxLength="5"
        android:text=""/>

</android.support.v7.widget.CardView>

最后是我的MakeFragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MakeFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dasfaddsa" />

    <ListView
        android:id="@+id/make_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible" />
</FrameLayout>

我一直在尝试复制此tutorial。当我使用调试器时,适配器getCount向我显示我有43个对象,并且应该调用getView方法。

编辑:我正在添加getAllMake()方法来提供帮助,但它正在按预期方式工作。

@Override
public List<Make> getAllMake() {
    Request request = new Request.Builder()
            .url(baseUrl + "/api/v1/brand/")
            .build();
    Response response = null;
    String responseBody = "";
    try {
        response = client.newCall(request).execute();
        responseBody = response.body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }

    MakeWrapper makeWrapper = gson.fromJson(responseBody, MakeWrapper.class);
    return makeWrapper.content;
}

1 个答案:

答案 0 :(得分:0)

尝试一下,

public class MakeFragment extends Fragment {

private List<Make> allMake = new ArrayList<>();
ListView listView;
MakeAdapter adapter;

private OnFragmentInteractionListener mListener;

public MakeFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View root = inflater.inflate(R.layout.fragment_make, container, false);

    listView = (ListView) root.findViewById(R.id.make_list);
    adapter = new MakeAdapter(allMake,getContext());
    listView.setAdapter(adapter);

    new MyTask().execute();

    return root;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}


public class MyTask extends AsyncTask<Void,Void,List<Make>> {

    @Override
    protected List<Make> doInBackground(Void... voids) {
        ImaApi api = new ImaApiImpl();
        return api.getAllMake();
    }

    @Override
    protected void onPostExecute(List<Make> result) {
        super.onPostExecute(result);
        allMake.addAll(result);
        adapter.notifyDataSetChanged();
        }

    }}