2016-07-04 6 views
0

Ich bin neu bei Android und weiß nicht viel. Ich brauche Hilfe, um diesen Code zu ändern - ich möchte etwas Text von einer Website herunterladen. Wenn ich den folgenden Code verwende: new DownloadTextTask(). Execute ("http://www.test.com/file.xml");wie man Text aus dem Internet in Android herunterladen?

Es zeigt nicht den heruntergeladenen Text in TextView, aber wenn ich die App wieder öffnen, kann ich den Text sehen. Ich denke, es ist asynchron, und es hat eine Verzögerung beim Herunterladen von Text.

Wie kann ich dieses Problem beheben, oder einfach nur diesen Code verwenden statt: (I DownloadText() Funktion direkt meine Verwendung Es Arbeit Ball hielt, als ich versuchte!)

TextView txt = (TextView)findViewById(R.id.textTest);   
txt.setText(DownloadText("http://www.test.com/")); 

den gesamten Code:

public class MainActivity extends AppCompatActivity { 
    public InputStream OpenHttpConnection(String urlString) throws IOException{ 
     InputStream in = null; 
     int response = -1; 
     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 
     if (!(conn instanceof HttpURLConnection)) 
      throw new IOException("Not an HTTP connection"); 
     try{ 
      HttpURLConnection httpConn = (HttpURLConnection) conn; 
      httpConn.setAllowUserInteraction(false); 
      httpConn.setInstanceFollowRedirects(true); 
      httpConn.setRequestMethod("GET"); 
      httpConn.connect(); 
      response = httpConn.getResponseCode(); 
      if (response == HttpURLConnection.HTTP_OK) { 
       in = httpConn.getInputStream(); 
      } 
     } 
     catch (Exception ex) 
     { 
      Log.d("MainActivity", ex.getLocalizedMessage()); 
      throw new IOException("Error connecting"); 
     } 
     return in; 
    } 

    public String DownloadText(String URL) 
    { 
     int BUFFER_SIZE = 2000; 
     InputStream in = null; 
     try { 
      in = OpenHttpConnection(URL); 
     } catch (IOException e) { 
      Log.d("MainActivity", e.getLocalizedMessage()); 
      return ""; 
     } 
     InputStreamReader isr = new InputStreamReader(in); 
     int charRead; 
     String str = ""; 
     char[] inputBuffer = new char[BUFFER_SIZE]; 
     try { 
      while ((charRead = isr.read(inputBuffer))>0) { 
//---convert the chars to a String--- 
       String readString = 
       String.copyValueOf(inputBuffer, 0, charRead); 
       str += readString; 
       inputBuffer = new char[BUFFER_SIZE]; 
      } 
      in.close(); 
     } catch (IOException e) { 
      Log.d("MainActivity", e.getLocalizedMessage()); 
      return ""; 
     } 
     return str; 
    } 

    private class DownloadTextTask extends AsyncTask<String, Void, String> { 

     protected String doInBackground(String... urls) { 
      return DownloadText(urls[0]); 
     } 
     @Override 
     protected void onPostExecute(String result) { 
      Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); 

     } 

    } 

    public static class xmlClass 
    { 
     public static String xml =""; 
    } 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

//new DownloadTextTask().execute("http://www.test.com/file.xml"); 

     TextView txt = (TextView)findViewById(R.id.textTest); 
     txt.setText(DownloadText("http://www.test.com/file.xml")); 

    } 
} 
+0

warum verwenden Sie nicht webview für das? –

+0

Verwenden Sie txt.setText (Ergebnis) in onPostExecute-Methode – Muthu

+0

@Muthu Ich muss es in String-Variable speichern, um es zu analysieren. – Saeid

Antwort

2

Sie einen Rückruf von AsyncTask als

private class DownloadTextTask extends AsyncTask { 
MainActivity instance=null; 
    public DownloadTextTask(MainActivity instance){ 
     this.instance=instance; 
    } 


    protected String doInBackground(String... urls) { 
     return DownloadText(urls[0]); 
    } 
    @Override 
    protected void onPostExecute(String result) { 
     Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); 
     if(instance!=null){ 
      instance.callback(result); 
     } 

    } 

} 

folgt und eine Methode namens Rückruf in MainActivity

public class MainActivity extends AppCompatActivity { 
.... your code...... 
    public void callback(String result){ 
    txt.setText(Parse your response); 
    } 
} 

Sie müssen Anruf hinzufügen, wie aus mainactivity folgt

new DownloadTextTask(this).execute("http://www.test.com/file.xml"); 
+0

danke. sorry für meine Frage, aber ich kopierte es in meiner Haupttätigkeit calss. Callback wird jedoch nicht erkannt (Callback-Methode kann nicht aufgelöst werden), und in der downoadtexttask-Klasse liegt ein Fehler vor. – Saeid

+0

wo nennst du neue DownloadTextTask (this)? – Muthu

+0

Funktioniert es jetzt? – Muthu

0

Set Text hier im Code

if (response == HttpURLConnection.HTTP_OK) { 
     in = httpConn.getInputStream(); 
     txt.setText(Parse your response); 
    } 
0

wird es besser sein Parser zu verwenden und XML Um Daten aus Ihrer XML-Datei in Ihre textView abzurufen, schauen Sie sich dieses Beispiel an

Dies ist ein Beispiel für einen XML-Parser aus einer XML-Datei mit ProductId, Name, Anweisungen, Preis und Foto.

+0

Ich habe Parser, aber mein Problem ist, kann ich nicht Xml-Datei aus dem Internet herunterladen! – Saeid

+0

Ich denke, dass, wenn Sie es schnell machen müssen einfach Ihre Daten in eine neue lokale XML-Datei einfügen. –

Verwandte Themen