java - ListView 无法显示从 URL 检索的列表

标签 java android url fragment

我是 Android Studio 新手。我正在尝试使用选项 create -> new Fragment (List) 自定义由 IDE 自动创建的 fragment 。我无法显示从 http 页面检索的列表,但如果我手动将项目添加到列表中,模拟器会让我看到它。我该如何解决这个问题?

municipioFragment.java

package com.example.is2_app.ui.municipio;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.is2_app.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class municipioFragment extends Fragment {

    // TODO: Customize parameters
    private int mColumnCount = 1;
    private List<News> lstNews;

    private OnListFragmentInteractionListener mListener;

    public municipioFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        lstNews = new ArrayList<>();   
        getURL();


    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_municipio_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));
        }
        return view;
    }


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

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

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */

    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(News item);
    }

    public void getURL() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final StringBuilder builder = new StringBuilder();
                try {
                    Document doc = Jsoup.connect("http://www.comune.candida.av.it").get();
                    Element content = doc.getElementById("b370");
                    Elements subcontent = content.getElementsByTag("p");
                    String Text = null;
                    String Href = null;
                    int i = 0;
                    for (Element link : subcontent) {
                        Href = link.attr("href");
                        Text = link.text();
                        builder.append("\n").append(Text);
                        i = i + 1;
                        lstNews.add(new News(Integer.toString(i), Text));
                    }


                } catch (IOException e) {
                    builder.append("Error: ").append(e.getMessage()).append("\n");
                }
            }
        }).start();
    }
}

MunicipioRecyclerViewAdapter.java

package com.example.is2_app.ui.municipio;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.is2_app.R;
import com.example.is2_app.ui.municipio.municipioFragment.OnListFragmentInteractionListener;

import java.util.List;


public class MymunicipioRecyclerViewAdapter extends RecyclerView.Adapter<MymunicipioRecyclerViewAdapter.ViewHolder> {


    private final OnListFragmentInteractionListener mListener;
    List<News> mData;

    public MymunicipioRecyclerViewAdapter(List<News> mData, OnListFragmentInteractionListener listener) {
        this.mData = mData;
        this.mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_municipio, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        //holder.mIdView.setText(mValues.get(position).id);
        holder.mContentView.setText(mData.get(position).getId());
        holder.mContentView.setText(mData.get(position).getContent());


    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.item_number);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}

fragment_municipio.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/item_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" />

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" /> </LinearLayout>

fragment_municipio_list.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.example.is2_app.ui.municipioFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context=".ui.municipio.municipioFragment"
    tools:listitem="@layout/fragment_municipio" />

最佳答案

因此,getUrl() 正在线程 中运行。此外,使用 JSoup 获取 Document 需要一些时间。这意味着 onCreateView 可能会在 lstNews 填充您从 Document 中抓取的数据之前运行。

所以你想更新你的数据集;然后,您想通知您的适配器您的数据集发生了变化。

将此方法添加到您的适配器

public void updateData(List<News> mData) {
    this.mData = mData;
    this.notifyDataSetChanged();
}

getUrl() 中的 for 循环之后,您需要执行以下操作:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        recyclerViewAdapter.updateData(lstNews);
    }
});

其中,recyclerViewAdapterrecyclerView 一起定义,并在 onCreateView 中初始化。 所以下面这行:

recyclerView.setAdapter(new MymunicipioRecyclerViewAdapter(lstNews, mListener));

将成为:

recyclerViewAdapter = new MymunicipioRecyclerViewAdapter(lstNews, mListener);
recyclerView.setAdapter(recyclerViewAdapter);

关于java - ListView 无法显示从 URL 检索的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59921058/

相关文章:

java - 如何否定方法引用谓词

java - Linux 和 OSX 以及 Android 根据区域设置的排序不一致

java - QR 扫描仪如何从远程数据库检索数据?

url - 角度 2 : One path for multiple components?

java - 线程中断不起作用(Java Android)

java - 为什么 LibGDX 中的实例会互相覆盖?

java - 在 Android Studio 上将模块或项目作为库导入

javascript - JavaScript中如何获取域名的 "meaningful"节点?

Java gzip pdf 从 url 到文件 - 结果出现轻微字符不匹配

java - 如何使用 OpenPDF 添加段落和边框