【问题标题】:Loading Parsed XML data into simpleListAdapter?将解析的 XML 数据加载到 simpleListAdapter 中?
【发布时间】:2012-02-28 14:48:16
【问题描述】:

我正在编写 3 个类/活动,我希望(最终)能够使用股票 android 布局将解析的 XML 数据加载到 simpleListAdapter 中。

我的策略是 Activity A:启动 SAX 解析器,加载处理程序,从 Activity C 检索 ArrayList>,并将 ArrayList 加载到 simpleListAdapter。

Activity B 是处理程序(我知道它有效,因为我以前使用过它,没有问题)。

最后,Activity C 包含返回 Strings 的方法,这些方法由处理程序给定值,然后将这些字符串加载到一个 ArrayList> 中,然后通过 Intent 发送给 Activity A。

但出现的只是黑屏。

我正在使用的测试 XML 站点是 http://www.google.com/ig/api?weather=Boston+Massachusetts"

这是 Activity A + C 的代码(我知道处理程序有效)。

活动(A):

public class xmlparser extends ListActivity implements OnClickListener {

static final String XMLsite = "http://www.google.com/ig/api weather=Boston+Massachusetts";


public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  





@SuppressWarnings("unchecked")
@Override
    try{
        URL website = new URL(XMLsite);
        //getting xmlreader to parse data
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        HandlingXMLStuff doingWork = new HandlingXMLStuff();
        xr.setContentHandler(doingWork);
        xr.parse(new InputSource(website.openStream()));

        ArrayList<HashMap<String, String>> list =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");

        String[] from = { "name", "purpose" };
        int[] to = { android.R.id.text1, android.R.id.text2 };

        SimpleAdapter adapter = new SimpleAdapter(this, list,
                android.R.layout.simple_list_item_2, from, to);
        setListAdapter(adapter);


        }catch(Exception e){

    }
}

活动(C):

package com.school;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class XMLDataCollected extends Activity{
 /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, xmlparser.class);
    ArrayList<HashMap<String, String>> list = buildData();
    intent.putExtra("arraylist", list);
    startActivity(intent);
}

int temp = 0;
String city = null;

public void setCity(String c){
    city = c;

}
public void setTemp(int t){
    temp = t;
}


private ArrayList<HashMap<String, String>> buildData() {
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    list.add(putData(city, "temp"));
    list.add(putData("city", "temp"));
    list.add(putData("city", "temp"));
    return list;
}

private HashMap<String, String> putData(String name, String purpose) {
    HashMap<String, String> item = new HashMap<String, String>();
    item.put("name", name);
    item.put("purpose", purpose);
    return item;
}
}

任何建议都会有所帮助。

附:我之前使用过这个 XML 过程将数据加载到 textview 中,所以我知道它至少能够解析 XML 标签并将它们设置在 Activity C 中的方法上,然后在 textview 中检索和设置字符串,但是我的最终目标是能够将信息加载到 simpleListAdapter 中。

谢谢

【问题讨论】:

  • 你的代码一团糟。您不需要 3 个活动来解析站点中的 xml 并将其显示在 ListView 中。
  • 哇,非常感谢。
  • Here 是您遇到问题时需要遵循的方案。这不是一个 XML 解析演示,只是通过以下步骤屏幕。

标签: android xml-parsing saxparser listadapter


【解决方案1】:

正如其他人所说,您的代码是悲惨的。此选项不需要两个活动。而是考虑一个 AsyncTask 或一个带有 XMLParser 的服务留在活动一中。然后 Activity 负责启动 AsyncTask 或 Service 并在数据可用时检索(解析)其数据。

public class ActivityOne extends Activity {
    private static final String ADDRESS = "...";
    @Override public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        new FetchDataTask(ADDRESS).execute();
    }


    private class FetchDataTask extends AsyncTask<Void, Void, Void> {
        private URL mWebsite;
        private ArrayList<???> mListActivityContent;

        public FetchDataTask(String address) {
            mWebsite = new URL(address);
        }

        @Override public void doInBackground(Void... voids) {
            //getting xmlreader to parse data
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            HandlingXMLStuff doingWork = new HandlingXMLStuff();
            xr.setContentHandler(doingWork);
            xr.parse(new InputSource(mWebsite.openStream()));
            /*
             * Now, you are going to want other parsing and
             * array building stuff here. Looking at your code,
             * I can't figure out how the XMLDataCollected
             * Activity is used, sorry, so you will have to tweak
             * this to accomodate it.
             */
        }

        @Override public void onPostExecute(Void voids) {
            SimpleAdapter adapter = new SimpleAdapter(ActivityOne.this,
            list, android.R.layout.simple_list_item_2, from, to);

            ActivityOne.this.setListAdatper(adapter);
        }
    }
}

【讨论】:

  • 我显然是 android 和解析的新手。我浏览了 4 个关于在 android 中解析 xml 的示例,包括包含 4 个类的 google 开发者示例。每个人都采用不同的方法,建立 Parser、Handler 和 Datacollected 类是唯一对我最有意义的类,这就是我保留这个模型的原因。如果您知道有关将 xml 解析为自定义列表视图的任何教程/示例,那么您将非常好/有建设性地分享。谢谢
  • @Bob,我发布了类似于我将如何完成此任务的内容。对它持保留态度,我不得不假设一些事情。希望能帮助到你! :) PS:我不是故意要表现得那么严厉,但有些事情需要说清楚;学习恕我直言的最佳方式。
  • 嘿,非常感谢 Aedon,我没有太多时间尝试您的建议,但我确实遇到了本教程,我认为这可能会帮助其他人开始 xml 解析路径:androidhive.info/2011/11/android-xml-parsing-tutorial跨度>
【解决方案2】:

这是一个使用 simpleAdapter 将国家名称和国家代码从 java 本地列表视图中列出的示例示例 SimpleAdapter详细了解@http://www.tutorialsbuzz.com/2014/06/simpleadaper-bind-hashmap-listview.html

另一个使用 SimpleAdapter@http://www.tutorialsbuzz.com/2015/03/android-sax-xml-parser-http.html 解析 XML 并显示到 ListView 中的示例

列表视图项的 XML 布局

文件:list_items.xml

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

<TextView
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:padding="5dp"
    android:textSize="18dp" />

<TextView
    android:id="@+id/code"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" />

</LinearLayout> 

文件:MainActivity.java

 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Locale;
 import android.app.ListActivity;
 import android.os.Bundle;
 import android.widget.ListAdapter;
 import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity {

ArrayList<HashMap<String, String>> countries;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String[] locales = Locale.getISOCountries();

    countries = new ArrayList<HashMap<String, String>>();

    for (String countryCode : locales) {
        Locale obj = new Locale("", countryCode);

        HashMap<String, String> country = new HashMap<String, String>();

        String country_name = obj.getDisplayCountry();
        String country_code = obj.getCountry();

        country.put("name", country_name);
        country.put("code", country_code);

        countries.add(country);

    }
    //  keys of hashmap
    String[] from = { "name", "code" };

    // view id's to which data to be binded
    int[] to = { R.id.name_id, R.id.code_id };

    //Creating Adapter
    ListAdapter adapter = new SimpleAdapter(MainActivity.this, countries,
            R.layout.list_items, from, to);

    //Setting Adapter to ListView
    setListAdapter(adapter);

}

}

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 2015-09-10
    • 1970-01-01
    • 2021-11-04
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多