2013-04-22 10 views
16

Ta metoda zwraca źródło podanego adresu URL.Niezgodność typu: nie można przekonwertować z StringBuilder na ciąg

private static String getUrlSource(String url) { 
    try { 
     URL localUrl = null; 
     localUrl = new URL(url); 
     URLConnection conn = localUrl.openConnection(); 
     BufferedReader reader = new BufferedReader(
      new InputStreamReader(conn.getInputStream())); 
     String line = ""; 
     String html; 
     StringBuilder ma = new StringBuilder(); 
     while ((line = reader.readLine()) != null) { 
      ma.append(line); 
     } 
     return ma; 
    } catch (Exception e) { 
     Log.e("ERR",e.getMessage()); 
    } 
} 

To daje mi ten błąd:

Type mismatch: cannot convert from StringBuilder to String 

I dwie możliwości:

  1. Change the return type to StringBuilder. Ale chcę zwrócić String.
  2. Change type of ma to String. Po zmianie ciągu nie ma metody append().
+6

'powrócić ma.toString() ; '??? – Esailija

+0

Na marginesie, możesz chcieć użyć polecenia 'ma.append (line) .append (LINE_SEPERATOR)' lub twoje linie będą zniekształcone jak: To jest linia 1. To jest linia 2. To jest linia 3. ' – corsiKa

Odpowiedz

37

Wystarczy użyć

return ma.toString(); 

zamiast

return ma; 

ma.toString() zwraca ciąg znaków dla StringBuilder.

Zobacz StringBuilder#toString() szczegółowe informacje

Jak Valeri Atamaniouk sugerowane w komentarzach, należy również zwrócić coś w bloku catch, inaczej dostaniesz błąd kompilatora dla missing return statement, więc edycji

} catch (Exception e) { 
    Log.e("ERR",e.getMessage()); 
} 

do

} catch (Exception e) { 
    Log.e("ERR",e.getMessage()); 
    return null; //or maybe return another string 
} 

Byłby to dobry pomysł.


EDIT

Jak sugeruje Esailija, mamy trzy anty-wzorców w tym kodzie

} catch (Exception e) {   //You should catch the specific exception 
    Log.e("ERR",e.getMessage()); //Don't log the exception, throw it and let the caller handle it 
    return null;     //Don't return null if it is unnecessary 
} 

więc myślę, że lepiej jest zrobić coś takiego:

private static String getUrlSource(String url) throws MalformedURLException, IOException { 
    URL localUrl = null; 
    localUrl = new URL(url); 
    URLConnection conn = localUrl.openConnection(); 
    BufferedReader reader = new BufferedReader(
      new InputStreamReader(conn.getInputStream())); 
    String line = ""; 
    String html; 
    StringBuilder ma = new StringBuilder(); 
    while ((line = reader.readLine()) != null) { 
     ma.append(line); 
    } 
    return ma.toString(); 
} 

A następnie, gdy go nazwiesz:

try { 
    String urlSource = getUrlSource("http://www.google.com"); 
    //process your url source 
} catch (MalformedURLException ex) { 
    //your url is wrong, do some stuff here 
} catch (IOException ex) { 
    //I/O operations were interrupted, do some stuff here 
} 

sprawdzić te linki do dalszych szczegółów dotyczących Javy Anti-patterns:

+0

Dodaj wyjątek powrót –

+0

@ValeriAtamaniouk co? – BackSlash

+0

Funkcja musi również zwrócić wartość w przypadku wyjątku. Jeśli nie zauważyłeś. –

1

mam ten sam problem podczas konwersji StringBuilder do String, i używam powyższego punktu, ale to nie daje prawidłowego rozwiązania. użyciu powyżej wyjście kodu pochodzi jak to

String out=ma.toString(); 
// out=[Ljava.lang.String;@41e633e0 

Potem dowiedzieć się poprawna solution.Think jest utworzyć nowy moment String wstawiony z StringBuilder tak ..

String out=new String(ma); 
Powiązane problemy