从远程XML为android创建一个数组

时间:2011-06-20 17:25:16

标签: android xml arrays sax

我有一个远程XML文件,我想用它来填充listview。

我目前正在设置应用程序以从本地阵列创建列表视图。如何使用在线存储的XML文件填充数组?该数组当前位于strings.xml

public class ArchiveListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(ArrayAdapter.createFromResource(getApplicationContext(),
            R.array.archivetitle, R.layout.archiveitem));

    final String[] links = getResources().getStringArray(R.array.archivelinks);

    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            String content = links[position];
            Intent showContent = new Intent(getApplicationContext(),
                    ArchiveViewerActivity.class);
            showContent.setData(Uri.parse(content));
            startActivity(showContent);
        }
    });
}
}

1 个答案:

答案 0 :(得分:0)

您可以在下面提到的步骤中执行此操作:

1&GT;准备xml所在的请求URI。

prepareRequestUrl();

2 - ;从Web服务器获取响应:

/** 
 * fetch the response for the request url
 * @param request url string
 * @return InputStream
 */
public InputStream getResponse(String reqUrl) throws AppException {

    URL                 url             =   null;
    URLConnection       connection      =   null;
    HttpURLConnection   httpConnection  =   null;
    int                 reponseCode     =   0;
    InputStream         inputStream     =   null;

    try {

        url = new URL(reqUrl);

        connection = url.openConnection();

        httpConnection = (HttpURLConnection) connection;

        reponseCode = httpConnection.getResponseCode();

    } catch (MalformedURLException e) {

    } catch (IOException e) {

    }

    if (reponseCode == HttpURLConnection.HTTP_OK) {
        try {

            inputStream = httpConnection.getInputStream();

        } catch (IOException e) {

        }
    }
    else    {
        throw new AppException(AppConstants.HTTP_RESPONSE_FAILURE);
    }

    return inputStream;
}

3&GT;解析从服务器收到的输入流xml:

                   inputStream = super.getResponse(requestUrl);             
        result= xmlParser.parseList(inputStream);

4&GT;在列表视图中显示相应的结果。

注意:始终建议使用异步任务来执行任何网络操作。在这种情况下,调用we-server。

希望这有帮助!