我一直致力于创建应用。我注意到我需要使用模式匹配器从网站获取信息并将其显示在Android应用上。我对Android App Development仍然有点新意,但我认为我在Java方面还不错。我在Eclipse中尝试了这个完全相同的代码并且它起作用,所以我有点困惑为什么Android Studio会有所不同。
基本上,我有一个textview,我试图填充维基百科的国家。这些州是拥有海滩的州。我在Eclipse上写的正则表达式抓住了所有状态甚至一些额外的美国领域,并在控制台中显示它们,但在Android中并非如此。
public static String patternMatcher()
{
try {
URL getUrlContent = new URL("https://en.wikipedia.org/wiki/List_of_beaches_in_the_United_States");
BufferedReader reader = new BufferedReader(new InputStreamReader(getUrlContent.openStream()));
String line;
Pattern stateForBeach = Pattern.compile("<h3>(.*>)(.*?)</span><span class=\"mw-editsection\"><span class=\"mw-editsection-bracket\">", Pattern.DOTALL);
//Pattern beach = Pattern.compile("<li><a href=\"(.*?>)(.*?)</a></li>");
Matcher matcher1;
while ((line = reader.readLine()) != null) {
matcher1 = stateForBeach.matcher(line);
if (matcher1.find()) {
matcherString = "States: " + matcher1.group(2);
}
}
}
catch (Exception ex)
{
System.out.println("Error: " + ex);
}
return matcherString;
}
这是将状态添加到textview
的方法public void addItemsToTextView()
{
patternMatcherTextView = (TextView) findViewById(R.id.patternMatcherTextView);
System.out.println(patternMatcher());
patternMatcherTextView.setText(patternMatcher());
}
这是onCreate app方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_which_beach);
stateSpinner = (Spinner) findViewById(R.id.stateSpinner);
patternMatcherTextView = (TextView) findViewById(R.id.patternMatcherTextView);
patternMatcherTextView.setText(patternMatcher());
addItemsToStateSpinner();
stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedState = stateSpinner.getSelectedItem().toString();
System.out.println("State "+selectedState+" has been selected");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
addItemsToTextView();
}
字符串和旋转器已经在上面声明和初始化。