2013-01-19 32 views
9

OK, więc jestem nowy dla Androida i chcę, aby cały tekst ze strony internetowej był napisany na ciąg. Znalazłem wiele takich pytań, ale jak już powiedziałem, jestem nowy w Androidzie i nie wiem, jak z nich korzystać w mojej aplikacji. Dostaję błędy. Tylko jedna metoda udało mi się ją uruchomić, wykorzystuje WebView i JavaScript i jest wolna jak diabli. Czy ktoś może mi powiedzieć inny sposób na zrobienie tego lub jak przyspieszyć WebView, ponieważ nie używam go w ogóle do oglądania treści. BTW Dodałem poniższy kod, żeby przyspieszyć WebviewPobierz tekst ze strony internetowej na ciąg

webView.getSettings().setJavaScriptEnabled(true); 
    webView.getSettings().setBlockNetworkImage(true); 
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); 
    webView.getSettings().setPluginsEnabled(false); 
    webView.getSettings().setSupportMultipleWindows(false); 
    webView.getSettings().setSupportZoom(false); 
    webView.getSettings().setSavePassword(false); 
    webView.setVerticalScrollBarEnabled(false); 
    webView.setHorizontalScrollBarEnabled(false); 
    webView.getSettings().setAppCacheEnabled(false); 
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); 

I proszę, jeśli wiesz lepiej i szybciej niż przy użyciu roztworu WebView proszę dać mi cały kod źródłowy główny przedmiot lub wytłumaczyć gdzie mam napisać to, więc nie dostaję błędów .. Z góry dziękuję !!

+0

Jeśli chcesz tylko tekst z danego elementu HTML, można przyjrzeć [JSoup] (http://jsoup.org/). –

Odpowiedz

27

użyj:

public class ReadWebpageAsyncTask extends Activity { 
    private TextView textView; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     textView = (TextView) findViewById(R.id.TextView01); 
    } 

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 
      String response = ""; 
      for (String url : urls) { 
       DefaultHttpClient client = new DefaultHttpClient(); 
       HttpGet httpGet = new HttpGet(url); 
       try { 
        HttpResponse execute = client.execute(httpGet); 
        InputStream content = execute.getEntity().getContent(); 

        BufferedReader buffer = new BufferedReader(
          new InputStreamReader(content)); 
        String s = ""; 
        while ((s = buffer.readLine()) != null) { 
         response += s; 
        } 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
      return response; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      textView.setText(Html.fromHtml(result)); 
     } 
    } 

    public void readWebpage(View view) { 
     DownloadWebPageTask task = new DownloadWebPageTask(); 
     task.execute(new String[] { "http://www.google.com" }); 

    } 
} 

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    > 

    <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/readWebpage" android:onClick="readWebpage" android:text="Load Webpage"></Button> 
    <TextView android:id="@+id/TextView01" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Example Text"></TextView> 
</LinearLayout> 
+0

jak odczytać zawartość http://ddceutkal.org/SSDC_GD.pdf @K_Anas i pokazać w jakimś textview-nulll –

+1

wszystkie przestarzałe ... –

2

Widząc, jak nie jesteś zainteresowany przeglądania treści w ogóle, można użyć następujących:

W celu uzyskania kodu źródłowego z adresu URL można użyć tego:

HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do 
HttpResponse response = httpclient.execute(httpget); // Executeit 
HttpEntity entity = response.getEntity(); 
InputStream is = entity.getContent(); // Create an InputStream with the response 
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
StringBuilder sb = new StringBuilder(); 
String line = null; 
while ((line = reader.readLine()) != null) // Read line by line 
    sb.append(line + "\n"); 

String resString = sb.toString(); // Result is here 

is.close(); // Close the stream 

Producent Upewnij się, że uruchamiasz to z głównego wątku UI w AsyncTask lub Thread.

5

Jest to kod I zazwyczaj używają pobrać ciąg z internetu

class RequestTask extends AsyncTask<String, String, String>{ 

@Override 
// username, password, message, mobile 
protected String doInBackground(String... url) { 
    // constants 
    int timeoutSocket = 5000; 
    int timeoutConnection = 5000; 

    HttpParams httpParameters = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
    HttpClient client = new DefaultHttpClient(httpParameters); 

    HttpGet httpget = new HttpGet(url[0]); 

    try { 
     HttpResponse getResponse = client.execute(httpget); 
     final int statusCode = getResponse.getStatusLine().getStatusCode(); 

     if(statusCode != HttpStatus.SC_OK) { 
      Log.w("MyApp", "Download Error: " + statusCode + "| for URL: " + url); 
      return null; 
     } 

     String line = ""; 
     StringBuilder total = new StringBuilder(); 

     HttpEntity getResponseEntity = getResponse.getEntity(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(getResponseEntity.getContent())); 

     while((line = reader.readLine()) != null) { 
      total.append(line); 
     } 

     line = total.toString(); 
     return line; 
    } catch (Exception e) { 
     Log.w("MyApp", "Download Exception : " + e.toString()); 
    } 
    return null; 
} 

@Override 
protected void onPostExecute(String result) { 
    // do something with result 
} 
} 

I można uruchomić zadanie z

new RequestTask().execute("http://www.your-get-url.com/");

+0

Jak rozumiem, powinienem umieścić nową właściwość RequestTask() w onCreate() i drugi kod poza onCreate() w prawo? jeśli to prawda, dostaję błąd na TAG - TAG nie może być rozwiązany na zmiennej. jak to naprawić? a ciąg linii to cały tekst z prawej strony? – null

+0

tak. linia ciągów to cała odpowiedź jako ciąg znaków. a TAG to tylko zmienna łańcuchowa, którą zdefiniowałem wcześniej. zastąp go dowolnym ciągiem twojego chocie. Zmodyfikowalem moją odpowiedź. I tak, możesz umieścić nową funkcję RequestTask() w dowolnym miejscu, gdy chcesz rozpocząć pobieranie. –

Powiązane problemy