用户使用异步任务输入到Url

时间:2013-05-06 09:57:50

标签: android android-asynctask user-input

我目前正在使用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是未定义的,我遵循快速修复,但是当运行该项时,我在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);
    }

和我的logcat:

enter image description here

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

好的问题解决了。

发生的事情是我没有接受用户输入并正确地将其附加到URL。喜欢事情有时如此简单。我也使用Realtime.this作为Gleb建议。谢谢你的帮助。继承了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);
        }
    });