【问题标题】:User Input to Url using Async Task使用异步任务对 URL 的用户输入
【发布时间】:2013-05-06 09:57:49
【问题描述】:

我目前正在使用 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 的字符串构建器放在按钮的 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);
    }

还有我的日志猫:

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

【问题讨论】:

    标签: android android-asynctask user-input


    【解决方案1】:

    为什么不直接将完整的 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);
    

    【讨论】:

    • 我曾尝试将它放在 onCreate 方法中,但它给了我一个:构造函数 Realtime.ParseTask(new View.OnClickListener(){}) 是未定义的错误。我尝试了它提供的两个快速修复来更改或创建构造函数,但是当我运行应用程序时我没有得到任何响应
    • 您确定将正确的上下文传递给您的 ParseTask 吗?看看这个:stackoverflow.com/questions/9506778/…
    • 是的,我几乎是肯定的,你可以看到我的 parsetask 方法有(上下文 c),它与对话框一起使用,然后与 onPreExecute() 一起使用。在这两种方法中构建字符串会有帮助吗?
    • 您遇到了类转换异常。您没有正确传递上下文。看看这一行: ParseTask task = new ParseTask(this);请注意,您没有传递上下文,而是传递了 Listener 对象引用。如果 sn-p 位于 Realtime 类,请尝试使用 Realtime.this。无论如何,将正确的指针传递给构造函数。
    • 好吧,我用 Realtime.this 代替,因为 realtime 是我的课,没有错误,运行良好,但现在结果没有打印出来,我的对话框加载但什么也没有,是否还有另一部分更改后我需要添加的代码?感谢您的帮助
    【解决方案2】:

    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);
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 2017-10-30
      • 2015-10-28
      • 1970-01-01
      • 2013-03-29
      相关资源
      最近更新 更多