使用Android中的Fragment在Listview中显示数据

时间:2017-11-03 03:50:20

标签: android listview android-fragments

我尝试在Android中使用片段在listview中显示数据,但它没有显示数据。请检查我的代码。 适配器类:

public class AppAdapter1 extends ArrayAdapter<Apps1> {

    ArrayList<Apps1> actorList1;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public AppAdapter1(Context context, int resource, ArrayList<Apps1> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList1 = objects;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.tvName.setText(actorList1.get(position).getPosition());
        return v;
    }
    static class ViewHolder {
        public TextView tvName;
    }
}

public class FragmentThree1 extends Fragment {
    ArrayList<Apps1> actorsList1;
    public ListView listView;
    String val="";
    AppAdapter1 adapter;
    public FragmentThree1() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View myFragmentView = inflater.inflate(R.layout.fragment_three_1, container, false);
        actorsList1 = new ArrayList<Apps1>();
new JSONAsyncTask().execute("http://--------------");
 ListView listview = (ListView) myFragmentView.findViewById(R.id.list);
       // adapter = new AppAdapter1(getActivity().getApplicationContext(), R.layout.row, actorsList1);
     adapter = new AppAdapter1(getActivity().getBaseContext(), R.layout.row, actorsList1);
         listview.setAdapter(adapter);
        return myFragmentView;
   } }

enter image description here

我从JSON URL检索数据,但在使用它显示listview时没有显示数据。请检查我的上述代码。

1 个答案:

答案 0 :(得分:0)

在此类JSONAsyncTask().execute("http://--------------");中,您只需调用此行,就可以在ArrayList actorsList1中添加数据。

adapter.notifyDataSetChanged();

原因是您的Async类在您的适配器设置数据时获取数据,因此当您完成Async任务时,您需要notify您的适配器更改DataSet

试试这个,它会解决你的问题。