【问题标题】:Not able to get the XML DOM parsed data on Main thread of process无法在进程的主线程上获取 XML DOM 解析数据
【发布时间】:2015-12-14 14:23:40
【问题描述】:

我没有从代码中得到想要的输出。

我使用 XML DOM 解析从链接中获取标题、发布日期、描述和图像:http://autosportsindia.com/feed

通过编写的代码没有获得任何输出。即使 Logcat 显示正在从链接中获取数据。

请告诉我我的代码有什么问题。建议使用代码或链接解析 XML 的任何其他方法。

public class  MainActivity extends AppCompatActivity implements ResultsCallBack {

PlaceholderFragment taskFragment;
ListView articlesListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        taskFragment = new PlaceholderFragment();
        getSupportFragmentManager().beginTransaction().add(taskFragment, "MyFragment").commit();

    } else {
        taskFragment = (PlaceholderFragment) getSupportFragmentManager().findFragmentByTag("MyFragment");
    }
    taskFragment.startTask();

    articlesListView = (ListView) findViewById(R.id.articlesListView);

}

@Override
public void onPreExecute() {

}

@Override
public void onPostExecute(ArrayList<HashMap<String, String>> results) {

    articlesListView.setAdapter(new MyAdapter(this, results));
}

public static class PlaceholderFragment extends Fragment {

    AutoSportsIndia downloadTask;
    ResultsCallBack callBack;

    public PlaceholderFragment() {
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        callBack = (ResultsCallBack) activity;

        if(downloadTask!=null)
        {
            downloadTask.onAttach(callBack);
        }
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);
    }

    public void startTask() {
        if (downloadTask != null) {
            downloadTask.cancel(true);
        } else {
            downloadTask = new AutoSportsIndia(callBack);
            downloadTask.execute();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callBack = null;
        if(downloadTask!=null) {
            downloadTask.onDetach();
        }

    }
}


public static class AutoSportsIndia extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {

    ResultsCallBack callBack =null;

    public AutoSportsIndia(ResultsCallBack callBack) {
        this.callBack = callBack;

    }

    public void onAttach(ResultsCallBack callBack) {
        this.callBack = callBack;

    }

    public void onDetach() {
        callBack = null;

    }

    protected void onPreExecute() {
        if(callBack!=null)
        {
            callBack.onPreExecute();
        }

    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {

        String downloadURL = "http://autosportsindia.com/feed";
        ArrayList<HashMap<String, String>> results = new ArrayList<>();
        try {
            URL url = new URL(downloadURL);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            processXML(inputStream);
        } catch (Exception e) {
            L.m(e + "");
        }
        return results;
    }

    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

        if(callBack!=null)
        {
            callBack.onPostExecute(result);
        }

    }

    public ArrayList<HashMap<String, String>> processXML(InputStream inputStream) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document xmlDocument = documentBuilder.parse(inputStream);
        Element rootElement = xmlDocument.getDocumentElement();
        L.m("" + rootElement.getTagName());
        NodeList itemsList = rootElement.getElementsByTagName("item");
        NodeList itemChildren = null;
        Node currentItem = null;
        Node currentChild = null;
        int count = 0;
        ArrayList<HashMap<String, String>> results = new ArrayList<>();
        HashMap<String, String> currentMap = null;

        for (int i = 0; i < itemsList.getLength(); i++) {

            currentItem = itemsList.item(i);
            itemChildren = currentItem.getChildNodes();

            currentMap = new HashMap<>();

            for (int j = 0; j < itemChildren.getLength(); j++) {
                currentChild = itemChildren.item(j);
                if (currentChild.getNodeName().equalsIgnoreCase("title")) {

                    currentMap.put("title", currentChild.getTextContent());
                   String temp="title: "+currentChild.getTextContent();
                   L.m(temp);
             }
             if (currentChild.getNodeName().equalsIgnoreCase("pubDate")) {

                   String temp1="pubDate: "+currentChild.getTextContent();
                 currentMap.put("pubDate", currentChild.getTextContent());
                   L.m(temp1);
             }

             if (currentChild.getNodeName().equalsIgnoreCase("description")) {

                 currentMap.put("description", currentChild.getTextContent());
                   String temp="description: "+currentChild.getTextContent();
                   L.m(temp);
             }
             if (currentChild.getNodeName().equalsIgnoreCase("media:thumbnail")) {
                    count++;
                    if (count == 2) {
                        L.m(currentChild.getAttributes().item(0).getTextContent());
                        currentMap.put("imageURL", currentChild.getAttributes().item(0).getTextContent());
                    }
                }

                if (currentMap != null && !currentMap.isEmpty()) {
                    results.add(currentMap);
                }
            }
            count = 0;
        }
        return results;
    }

}

}

interface ResultsCallBack {
    public void onPreExecute();

    public void onPostExecute(ArrayList<HashMap<String, String>> results);
}

class MyAdapter extends BaseAdapter {

ArrayList<HashMap<String, String>> dataSource = new ArrayList<>();
Context context;
LayoutInflater layoutInflater;

public MyAdapter(Context context, ArrayList<HashMap<String, String>> dataSource) {
    this.context = context;
    this.dataSource = dataSource;
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    MyHolder holder = null;
    if(row == null)
    {
       row = layoutInflater.inflate(R.layout.custom_view, parent, false);
        holder = new MyHolder(row);
        row.setTag(holder);
    }
    else
    {
         holder = (MyHolder)row.getTag();
    }
    HashMap<String, String> currentItem = dataSource.get(position);
    holder.articleTitleText.setText(currentItem.get("title"));
    holder.articlePublishedDateText.setText(currentItem.get("pubDate"));
   // holder.articleImage.setImageURI(Uri.parse(currentItem.get("imageURL")));
    holder.articleDescriptionText.setText(currentItem.get("description"));

    return row;
}
}

class MyHolder {
    TextView articleTitleText;

    TextView articlePublishedDateText;

    ImageView articleImage;

TextView articleDescriptionText;

public MyHolder(View view) {

articleTitleText = (TextView) 

view.findViewById(R.id.articleTitleText);

articlePublishedDateText = (TextView) view.findViewById(R.id.articlePublishedDate);


    articleImage = (ImageView) view.findViewById(R.id.articleImage);

    articleDescriptionText = (TextView) view.findViewById(R.id.articleDescriptionText);
}

}

XML 页面:-

  • activity_main.xml

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/articlesListView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    

  • custom_view.xml

    <TextView
        android:id="@+id/articleTitleText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:padding="12dp"
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#444"/>
    
    <TextView
        android:id="@+id/articlePublishedDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/articleTitleText"
        android:paddingBottom="4dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="4dp"
        android:text="Date"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#444"/>
    
    <View
        android:id="@+id/separator1"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_below="@+id/articlePublishedDate"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:background="#e67e22"/>
    
    <ImageView
        android:id="@+id/articleImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/separator1"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_launcher"/>
    
    <TextView
        android:id="@+id/articleDescriptionText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/articleImage"
        android:padding="12dp"
        android:text="Description"
        android:textColor="#444"/>
    

【问题讨论】:

  • 请最小化您的代码以显示您遇到的问题。见stackoverflow.com/help/mcve
  • 您是否尝试过调试代码、单步执行并查看正在处理的值?
  • 是的,我试过了。问题出在
  • onPostExecute(ArrayList> results)
  • 该方法有 1 行代码。不,2行代码。那么那 1 或 2 行代码有什么问题呢?

标签: java android xml dom import


【解决方案1】:

processXML 方法构建并返回一个ArrayList&lt;HashMap&lt;String, String&gt;&gt;

doInBackground方法中调用,但返回值被丢弃。 doInBackground 然后返回一个本地的results 对象,它是一个空列表。

如果您通过processXMLdoInBackground 方法进行了调试,您就会看到这一点。当我在评论中询问“您是否尝试过调试代码、单步调试并查看正在处理的值”时,您显然没有。

【讨论】:

  • 您能否提供更好的代码来解析我发布的链接。非常感谢您。
  • 不,我不会为你编写代码。我帮你找到了导致列表为空的错误,也就是你说的问题。如果之后还有问题,这次尝试调试代码,如果还是有问题,再问一个问题。
  • 感谢@Andreas!现在调试后,我的代码给出了正确的输出
猜你喜欢
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多