如何从PHP JSON数据中填充片段中的ListView?

时间:2018-02-22 02:13:02

标签: java android listview android-fragments

我有一个包含ListView的片段(homePageFrag)。当我尝试使用来自网址的JSON数据填充它时,它无法正常工作。 ListView为空。但是,当我从ArrayList提供静态数据时,它会显示出来。

我想要实现的是在ListView内填充从URL获取的JSON数据中的FragmentHP_JSON_Download正在按预期工作,我在ListView中使用Activity,但在片段中,它没有显示任何数据。

有人可以帮我解决这个问题吗?

请不要这样做。我只是想学习。

homePageFrag.java

public class homePageFrag extends Fragment implements HP_JSON_Download.download_complete {

    boolean open = false;  Context applicationContext;

    public ListView list;
    public ArrayList<HPEntity> countries = new ArrayList<HPEntity>();
    public HP_ListAdapter adapter;

    private final String bus_id[] = {"a1"};
    private final String bus_destination[] = {"A1"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file

        View view = inflater.inflate(R.layout.homepage_lv, container, false);

        list = (ListView) view.findViewById(R.id.homepageListView);
        adapter = new HP_ListAdapter(this);
        list.setAdapter(adapter);

        HP_JSON_Download download_data = new HP_JSON_Download((HP_JSON_Download.download_complete) this);
        download_data.download_data_from_link("http://www.xyz.in/MyApi/Api.php");

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("E-RTC");
    }

    public void get_data(String data) {
        Toast.makeText(getApplicationContext(),"xx",Toast.LENGTH_SHORT).show();

        try {
            JSONArray data_array=new JSONArray(data);

            for (int i = 0 ; i < data_array.length() ; i++) {
                JSONObject obj=new JSONObject(data_array.get(i).toString());

                HPEntity add=new HPEntity();
                add.name = obj.getString("id");
                add.code = obj.getString("name");

                countries.add(add);
            }

            adapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public Context getApplicationContext() {
        return applicationContext;
    }
}

HP_ListAdapter.java

public class HP_ListAdapter  extends BaseAdapter {

    homePageFrag main;

    Context mContext;
    public HP_ListAdapter(Context mContext) {
        this.mContext = mContext;
    }

    HP_ListAdapter(homePageFrag main) {
        this.main = main;
    }

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

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    static class ViewHolderItem {
        TextView name;
        TextView code;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolderItem holder = new ViewHolderItem();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.homepage_item, null);

            holder.name = (TextView) convertView.findViewById(R.id.busID);
            holder.code = (TextView) convertView.findViewById(R.id.busNAME);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolderItem) convertView.getTag();
        }

        holder.name.setText(this.main.countries.get(position).name);
        holder.code.setText(this.main.countries.get(position).code);

        return convertView;
    }
}

HPEntity.java

public class HPEntity {
    String name;
    String code;
}

HP_JSON_Download.java

public class HP_JSON_Download  implements  Runnable  {

    public download_complete caller;

    public interface download_complete {
         void get_data(String data);
    }

    HP_JSON_Download(download_complete caller) {
        this.caller = caller;
    }

    private String link;
    public void download_data_from_link(String link) {
        this.link = link;
        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        threadMsg(download(this.link));
    }

    private void threadMsg(String msg) {
        if (!msg.equals(null) && !msg.equals("")) {
            Message msgObj = handler.obtainMessage();
            Bundle b = new Bundle();
            b.putString("message", msg);
            msgObj.setData(b);
            handler.sendMessage(msgObj);
        }
    }

    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {

            String Response = msg.getData().getString("message");
            caller.get_data(Response);
        }
    };

    public static String download(String url) {
        URL website;
        StringBuilder response = null;
        try {
            website = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) website.openConnection();
            connection.setRequestProperty("charset", "utf-8");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            connection.getInputStream()));

            response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null)
                response.append(inputLine);

            in.close();

        } catch (Exception  e) {
            return "";
        }

        return response.toString();
    }
}

1 个答案:

答案 0 :(得分:1)

我建议你像这样修改你的适配器。

public class HP_ListAdapter  extends BaseAdapter {
    public ArrayList<HPEntity> countries = new ArrayList<HPEntity>();
    Context mContext;

    public HP_ListAdapter(Context mContext, ArrayList<HPEntity> countries) {
        this.mContext = mContext;
        this.countries = countries;
    }

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

    @Override
    public Object getItem(int position) {
        return countries.get(position);
    }

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

    static class ViewHolderItem {
        TextView name;
        TextView code;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolderItem holder = new ViewHolderItem();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.homepage_item, null);

            holder.name = (TextView) convertView.findViewById(R.id.busID);
            holder.code = (TextView) convertView.findViewById(R.id.busNAME);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolderItem) convertView.getTag();
        }

        holder.name.setText(this.countries.get(position).name);
        holder.code.setText(this.countries.get(position).code);

        return convertView;
    }
}

现在从您onCreateView中的Fragment函数初始化适配器。您正在使用this将错误的上下文传递给适配器初始化。您应该使用getActivity()代替。

adapter = new HP_ListAdapter(getActivity(), countries);