java - 如何从 PHP JSON 数据填充 ListView fragment ?

标签 java android listview android-fragments

我有一个包含 ListView 的 fragment (homePageFrag) 。当我尝试使用 URL 中的 JSON 数据填充它时,它不起作用。 ListView 是空的。但是,当我从 ArrayList 提供静态数据时,它就会出现。

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

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();
    }
}

最佳答案

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

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;
    }
}

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

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

关于java - 如何从 PHP JSON 数据填充 ListView fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48918557/

相关文章:

javascript - 视网膜(或其他高分辨率)显示屏是否会影响手机和平板电脑之间基于分辨率的差异?

android - 如何从 PhoneGap/Cordova 应用程序直接导航到 Google Play 商店中的应用程序?

android - ViewFlipper 中的 listView - 滚动问题

java - 如何在java中绘制菱形?

java - 从单链表打印节点

我的方法无法识别 Java 枚举类型

安卓开发 : Inserting a local image file into a ListView referenced from a SQLite database via a ViewBinder

java - Nashorn 的 IllegalArgumentException 异常 - 它是 Java 8 中的错误吗?

android - "Create project from existing source"是否修改现有样本?

angularjs - 在 ionic 框架列表中组合 "Checkbox"和 "Avatar"