0

我目前正在使用 XMLPullParser 来解析来自火车站 API 的页面。我正在使用 Async 任务执行此操作,以跟上较新版本的 android。

目前我已将 XML 字符串硬编码到类中,结果显示在列表视图中。

但是,我无法附加 baseURL 以将用户输入的查询添加到它的末尾。在使用以下代码使用异步任务之前,我没有遇到任何问题:

    public void StationDetails(){
    //--- Search button ---
    Button btnSearch = (Button) findViewById(R.id.btnSearch);
    btnSearch.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

    //--- EditText View ---
    EditText input = (EditText)  findViewById(R.id.inputStation);
    StringBuilder URL = new StringBuilder(baseURL);
    URL.append(input);
    String fullURL = URL.toString();
          }
      });
       }

但我无法将其与异步方法联系起来。我似乎在网上找不到任何东西,非常感谢任何人在这件事上的帮助。

这是带有硬编码字符串的类:

public class Realtime extends Activity {

// Irish Rail Site URL
private static final String baseURL =  "http://api.irishrail.ie/realtime/realtime.asmx/getStationDataByNameXML?StationDesc=Malahide";
// XML TAG Name
private static final String TAG_ITEM = "objStationData";
private static final String TAG_ORIGIN = "Origin";
private static final String TAG_DEST = "Destination";
private static final String TAG_SCHARR = "Scharrival";
private static final String TAG_EXPARR = "Exparrival";
private static final String TAG_DIRECT = "Direction";
private static final String TAG_STAT = "Status";
private static final String TAG_TRAINTYPE = "Traintype";

private RealtimeListviewAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stations_realtime_layout);

    ListView listView = (ListView) findViewById(R.id.listview);
    mAdapter = new RealtimeListviewAdapter(this);
    // set adapter
    listView.setAdapter(mAdapter);
    // use AsyncTask to parse the URL data
    ParseTask task = new ParseTask(this);
    task.execute(baseURL);

    // --- Register the list view for long press menu options
    registerForContextMenu(listView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class ParseTask extends
        AsyncTask<String, Void, ArrayList<StationDetails>> {
    private ProgressDialog dialog;

    public ParseTask(Context c) {
        dialog = new ProgressDialog(c);
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Loading Station Info...");
        dialog.show();
    }

    @Override
    protected ArrayList<StationDetails> doInBackground(String... params) {
        String strUrl = params[0];
        HttpURLConnection httpConnection = null;
        InputStream is = null;
        try {
            URL url = new URL(strUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(10000);
            httpConnection.connect();
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                is = httpConnection.getInputStream();
                return parseNews(is);
            }

        } catch (Exception e) {
            // TODO
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (httpConnection != null) {
                httpConnection.disconnect();
                httpConnection = null;
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<StationDetails> result) {
        // set the result
        mAdapter.setData(result);
        // notify to refresh
        mAdapter.notifyDataSetChanged();

        // Close the progress dialog
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}

private ArrayList<StationDetails> parseNews(InputStream in)
        throws XmlPullParserException, IOException {
    ArrayList<StationDetails> newsList = new ArrayList<StationDetails>();
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser pullParser = factory.newPullParser();
    pullParser.setInput(in, "UTF-8");
    int eventType = pullParser.getEventType();
    StationDetails item = null;
    while (eventType != XmlPullParser.END_DOCUMENT) {
        String tagName;

        if (eventType == XmlPullParser.START_TAG) {
            tagName = pullParser.getName();
            if (tagName.equals(TAG_ITEM)) {
                item = new StationDetails();
            } else if (tagName.equals(TAG_ORIGIN)) {
                if (item != null) {
                    item.mOrigin = pullParser.nextText();
                }

            } else if (tagName.equals(TAG_DEST)) {
                if (item != null) {
                    item.mDestination = pullParser.nextText();
                }
            } else if (tagName.equals(TAG_SCHARR)) {
                if (item != null) {
                    item.mSchArrival = pullParser.nextText();
                }
            } else if (tagName.equals(TAG_EXPARR)) {
                if (item != null) {
                    item.mExpArrival = pullParser.nextText();
                }
            } else if (tagName.equals(TAG_DIRECT)) {
                if (item != null) {
                    item.mDirection = pullParser.nextText();
                }
            } else if (tagName.equals(TAG_STAT)) {
                if (item != null) {
                    item.mStatus = pullParser.nextText();
                }
            }

        } else if (eventType == XmlPullParser.END_TAG) {
            tagName = pullParser.getName();
            if (tagName.equals(TAG_ITEM)) {
                newsList.add(item);
                item = null;

            }
        }
        eventType = pullParser.next();
    }
    return newsList;
}

编辑更新

好的,我将 fullURL 的 stringbuilder 放在按钮的 onClickListener 中。现在我想要的是在单击按钮时执行任务。我将 parsetask 任务、.excute 等移到了这个 clickListener 中。然而,这给了我一个错误,说实时的 View.OnClickListener 是未定义的,我遵循快速修复,但是当运行 porject 时,我在 logcat 中得到一个错误,说不能转换为 android.content.Context。

这是快速修复后代码现在的样子的片段

searchBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Append user input to baseURL
            StringBuilder URL = new StringBuilder(baseURL);
            URL.append(userInput);
            String fullURL = URL.toString();

            // use AsyncTask to parse the URL data
            ParseTask task = new ParseTask(this);
            task.execute(fullURL);
        }
    });

public ParseTask(OnClickListener onClickListener) {
        dialog = new ProgressDialog((Context) onClickListener);
    }

和我的日志:

在此处输入图像描述

我仍然无法弄清楚这一点,任何人的帮助都会非常受欢迎

4

2 回答 2

0

OK 问题解决了。

发生的事情是我没有接受用户输入并将其正确附加到 URL。喜欢有时事情如此简单。我还按照 Gleb 的建议使用了 Realtime.this。谢谢你的帮助。这是 onClickListener 中有效的代码......

searchBtn.setOnClickListener(new View.OnClickListener() {

        private String userInput;

        @Override
        public void onClick(View v) {
            ListView listView = (ListView) findViewById(R.id.listview);
            mAdapter = new RealtimeListviewAdapter(Realtime.this);
            //set adapter
            listView.setAdapter(mAdapter);
            StringBuilder URL = new StringBuilder(baseURL);
            etStation = (EditText) findViewById(R.id.inputStation);
            userInput = etStation.getText().toString();
            URL.append(userInput);
            String fullURL = URL.toString();
            //use AsyncTask to parse the RSS data
            ParseTask task = new ParseTask(Realtime.this);
            task.execute(fullURL);
        }
    });
于 2013-05-09T05:33:46.583 回答
0

为什么不直接将完整的 URL 发送到 AsyncTask?看起来像:

StringBuilder URL = new StringBuilder(baseURL);
URL.append(input);
String fullURL = URL.toString();// use AsyncTask to parse the URL data
ParseTask task = new ParseTask(this);
task.execute(fullURL);
于 2013-05-06T10:11:13.797 回答