2014-04-14 285 views
0

此主題在這裏已經討論了很多,但沒有一個解決方案適用於我。我想替換從HTML獲得的字符串的一部分。獲取和顯示HTML工作正常,但我不能刪除字符串的任何部分。它的行爲,因爲它沒有找到它。替換字符串部分

請看看波紋管代碼:

public class Main extends Activity { 

public static String URL = ""; 
public static String htmlString; 
public TextView mainText; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main_layout); 

    mainText = (TextView) findViewById(R.id.mainText); 

    constructURL(); 
    getHtml(); 

    htmlString.replaceAll("<head>", "hulo"); 

    mainText.setText(htmlString); 
} 

public void getHtml() { 
    try { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpGet httpGet = new HttpGet(URL); 
     HttpResponse response = httpClient.execute(httpGet, localContext); 
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(
        response.getEntity().getContent() 
        ) 
      ); 
     String line = null; 
     while ((line = reader.readLine()) != null){ 
      htmlString += line + "\n"; 
     } 
    } catch (Exception e) { 
    } 
} 

public void constructURL() { 
    Time time = new Time(); 
    time.setToNow(); 
    String year = convertToString(time.year - 2000); 
    String month = convertToString(time.month + 1); 
    String monthDay = convertToString(time.monthDay); 

    URL = "http://www.gymzl.cz/bakalari/suplovani_st/tr" + year + month + monthDay + ".htm"; 
} 

public String convertToString(int value) { 
    String text = ""; 
    if(value < 10) text = "0"; 
    text += String.valueOf(value); 
    return text; 
} 
} 

的「hulo」更換似乎並沒有工作。

我很抱歉這麼長的代碼,但我已經嘗試了一切。

回答

2

replaceAll不更新調用字符串,您需要將其分配回來。改變這種

htmlString.replaceAll("<head>", "hulo"); 

htmlString = htmlString.replaceAll("<head>", "hulo"); 
+1

謝謝。我應該閱讀JavaDOC。對於那個很抱歉。我會盡快將此標記爲anwser。 – ViliX64

+0

@ViliX沒問題,有時會發生。樂意效勞 :-) –

1
htmlString.replaceAll("<head>", "hulo"); 

回報更換字符串,但不會改變htmlString

所以directle做這樣的

mainText.setText(""+htmlString.replaceAll("<head>", "hulo")); 
1

調用replaceAll後,它將返回替換的字符串。你需要把這個新的字符串分配給某個對象再次

像下面,將其分配給再次htmlString

htmlString = htmlString.replaceAll("<head>", "hulo"); 
0
mainText.setText(htmlString.replaceAll("<head>", "hulo"));