【问题标题】:How to populate ListView in a fragment from PHP JSON data?如何从 PHP JSON 数据的片段中填充 ListView?
【发布时间】:2018-02-22 02:13:02
【问题描述】:

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

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

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

【问题讨论】:

  • 您的网络响应是否正确?
  • @AbuYousuf 是的。它是正确的。当我在 Activity 中使用 ListView 而不是在片段中时,我正在获取数据

标签: java android listview android-fragments


【解决方案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;
    }
}

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

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

【讨论】:

  • 我收到 - 无法解决“主要”错误 - 因为您已删除主要声明。我该如何解决这个问题?
  • 我在适配器中添加了homePageFrag main;,应用程序现在在启动片段时崩溃
  • 在getView 中将main.countries 替换为countries
  • 试过了。它仍然崩溃
  • @AbuYousuf 更新了可能导致崩溃的getView 函数。请尝试使用更新的代码并检查它现在是否工作。如果没有,请分享 logcat,让我们知道确切的错误消息是什么。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 2011-09-10
  • 1970-01-01
  • 2016-12-18
相关资源
最近更新 更多