Autore Topic: URL  (Letto 1011 volte)

Offline teo2490

  • Nuovo arrivato
  • *
  • Post: 39
  • Respect: 0
    • Mostra profilo
URL
« il: 21 Agosto 2012, 09:29:44 CEST »
0
Buongiorno! Avrei una domanda sulla classe URL. Vorrei trasformare in una stringa il contenuto di una pagina html per poi poterne prendere solo una parta da riutilizzzare e avevo pensato di farlo in questo modo:

Codice (Java): [Seleziona]
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class SecondaAttivita extends Activity {
  private TextView tv; 
  @Override
  public void onCreate(Bundle savedInstanceState) {
          URL u = null;
        try {
                u = new URL("http://NOMESITO");
        } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
          InputStream is = null;
        try {
                is = u.openStream();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
          String html=is.toString();
                 
    LinearLayout linear = new LinearLayout(this);
    tv = (TextView) findViewById(R.id.testo1);
      tv.setText(html);    
      linear.addView(tv);
      setContentView(linear);        
  }
}

ma non funziona! Qualcuno saprebbe aiutarmi?
Grazie mille! :-)

EDIT Non so se può servire, ma posto anche il logcat


08-21 07:25:51.836: E/Trace(614): error opening trace file: No such file or directory (2)
08-21 07:25:52.335: D/gralloc_goldfish(614): Emulator without GPU emulation detected.
08-21 07:27:19.586: D/gralloc_goldfish(663): Emulator without GPU emulation detected.
08-21 07:27:29.925: D/AndroidRuntime(663): Shutting down VM
08-21 07:27:29.925: W/dalvikvm(663): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08-21 07:27:29.985: E/AndroidRuntime(663): FATAL EXCEPTION: main
08-21 07:27:29.985: E/AndroidRuntime(663): java.lang.RuntimeException: Unable to start activity ComponentInfo{teo2490.android/teo2490.android.SecondaAttivita}: android.os.NetworkOnMainThreadException
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.os.Looper.loop(Looper.java:137)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.ActivityThread.main(ActivityThread.java:4745)
08-21 07:27:29.985: E/AndroidRuntime(663):    at java.lang.reflect.Method.invokeNative(Native Method)
08-21 07:27:29.985: E/AndroidRuntime(663):    at java.lang.reflect.Method.invoke(Method.java:511)
08-21 07:27:29.985: E/AndroidRuntime(663):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-21 07:27:29.985: E/AndroidRuntime(663):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-21 07:27:29.985: E/AndroidRuntime(663):    at dalvik.system.NativeStart.main(Native Method)
08-21 07:27:29.985: E/AndroidRuntime(663): Caused by: android.os.NetworkOnMainThreadException
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-21 07:27:29.985: E/AndroidRuntime(663):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-21 07:27:29.985: E/AndroidRuntime(663):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-21 07:27:29.985: E/AndroidRuntime(663):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
08-21 07:27:29.985: E/AndroidRuntime(663):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
08-21 07:27:29.985: E/AndroidRuntime(663):    at java.net.URL.openStream(URL.java:462)
08-21 07:27:29.985: E/AndroidRuntime(663):    at teo2490.android.SecondaAttivita.onCreate(SecondaAttivita.java:27)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.Activity.performCreate(Activity.java:5008)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-21 07:27:29.985: E/AndroidRuntime(663):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-21 07:27:29.985: E/AndroidRuntime(663):    ... 11 more
« Ultima modifica: 21 Agosto 2012, 09:32:50 CEST da teo2490 »

Offline bradipao

  • Moderatore globale
  • Utente storico
  • *****
  • Post: 4043
  • keep it simple
  • Respect: +567
    • Github
    • Google+
    • bradipao
    • Mostra profilo
  • Dispositivo Android:
    Nexus 5
  • Play Store ID:
    Bradipao
  • Sistema operativo:
    W7
Re:URL
« Risposta #1 il: 21 Agosto 2012, 10:10:03 CEST »
0
Codice: [Seleziona]
08-21 07:27:29.985: E/AndroidRuntime(663): java.lang.RuntimeException: Unable to start activity ComponentInfo{teo2490.android/teo2490.android.SecondaAttivita}: android.os.NetworkOnMainThreadException
NetworkOnMainThreadException : non puoi fare una richiesta di rete nel main thread, devi gestirla in un thread separato o in un AsyncTask.

Ti consiglio di leggere la documentazione ufficiale (stranamente evitata da tutti), che spiega tutto per filo e per segno e propone pure un esempio minimale.
Connecting to the Network | Android Developers
NON rispondo a domande nei messaggi privati
Bradipao @ Play Store

Offline teo2490

  • Nuovo arrivato
  • *
  • Post: 39
  • Respect: 0
    • Mostra profilo
Re:URL
« Risposta #2 il: 21 Agosto 2012, 11:14:25 CEST »
0
Grazie, ho capito l'errore, ma non riesco comunque ad uscirne. Ho provato ad usare un AsyncTask nella MainActivity facendo così:

Codice (Java): [Seleziona]
import java.io.InputStream;
import java.net.*;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Button;

public class MainActivity extends Activity {
       
  private TextView textView1;
  private Button bottone1;
  private Button bottone2;
  private String res;
  private WebView wb;
 
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   
    //Setta gli oggetti di activity_main.xml
    setContentView(R.layout.activity_main);
   
    //Dichiarazione TextView e Pulsanti
    textView1 = (TextView) findViewById(R.id.testo1);
    textView1.setText("Testo modificato tramite codice 1");
   
    wb = (WebView) findViewById(R.id.myWebView);
    wb.getSettings().setJavaScriptEnabled(true);
   
    bottone1 = (Button) findViewById(R.id.bottone1);
    bottone2 = (Button) findViewById(R.id.bottone2);
   
    //Listener per i pulsanti
    View.OnClickListener gestore = new View.OnClickListener() {
          public void onClick(View view) {
           
            switch(view.getId()){
                       
              case R.id.bottone1:
                textView1.setText("E' stato cliccato il bottone 1 !!!!!");
                break;
                               
              case R.id.bottone2:
                  wb.loadData(res, "text/html", "UTF-8");
                break;
            }  
          }
        };
         
        ApplicationSimpleAsyncTask task = new ApplicationSimpleAsyncTask(this);
        try {
                res = task.execute().get();
        } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
               
        bottone1.setOnClickListener(gestore);
        bottone2.setOnClickListener(gestore);
  }
}


Dove l'AsyncTask è il seguente:

Codice (Java): [Seleziona]
package teo2490.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.pm.PackageManager;
import android.os.AsyncTask;

public class ApplicationSimpleAsyncTask extends
AsyncTask<Void, Void, String>
{
private final MainActivity mainActivity;

private final PackageManager packageManager;

public ApplicationSimpleAsyncTask(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
packageManager = mainActivity.getPackageManager();
}

public String parseISToString(java.io.InputStream is){
           java.io.DataInputStream din = new java.io.DataInputStream(is);
           StringBuffer sb = new StringBuffer();
           try{
             String line = null;
             while((line=din.readLine()) != null){
               sb.append(line+"\n");
             }
           }catch(Exception ex){
             ex.getMessage();
           }finally{
             try{
               is.close();
             }catch(Exception ex){}
           }
           return sb.toString();
         }

@Override
protected String doInBackground(Void... params)
{
        URL u = null;
        try {
                u = new URL("[url=http://dailygospel.org/main.php?language=IT"]VANGELO DEL GIORNO[/url]);
        } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
          InputStream is = null;
        try {
                is = u.openStream();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
          String html=parseISToString(is);
          return html;
}
}

Il logcat è questo:


08-21 09:04:40.605: E/Trace(968): error opening trace file: No such file or directory (2)
08-21 09:04:42.615: D/dalvikvm(968): GC_CONCURRENT freed 263K, 5% free 8144K/8519K, paused 75ms+72ms, total 212ms
08-21 09:04:43.915: D/dalvikvm(968): GC_CONCURRENT freed 372K, 6% free 8162K/8647K, paused 94ms+97ms, total 228ms
08-21 09:04:45.197: D/dalvikvm(968): GC_CONCURRENT freed 414K, 7% free 8185K/8711K, paused 97ms+98ms, total 246ms
08-21 09:04:46.325: D/dalvikvm(968): GC_FOR_ALLOC freed 378K, 6% free 8211K/8711K, paused 42ms, total 42ms
08-21 09:04:47.146: D/dalvikvm(968): GC_CONCURRENT freed 357K, 6% free 8240K/8711K, paused 97ms+95ms, total 224ms
08-21 09:04:47.887: D/gralloc_goldfish(968): Emulator without GPU emulation detected.
08-21 09:04:48.106: I/Choreographer(968): Skipped 30 frames!  The application may be doing too much work on its main thread.
08-21 09:05:32.095: W/IInputConnectionWrapper(968): showStatusIcon on inactive InputConnection
08-21 09:05:35.835: D/dalvikvm(968): GC_CONCURRENT freed 356K, 6% free 8306K/8775K, paused 102ms+98ms, total 262ms
08-21 09:05:36.955: D/dalvikvm(968): GC_CONCURRENT freed 413K, 6% free 8318K/8839K, paused 108ms+104ms, total 258ms
08-21 09:05:37.975: D/dalvikvm(968): GC_CONCURRENT freed 392K, 6% free 8334K/8839K, paused 102ms+5ms, total 143ms
08-21 09:05:39.165: D/dalvikvm(968): GC_CONCURRENT freed 374K, 6% free 8360K/8839K, paused 103ms+6ms, total 154ms
08-21 09:05:40.447: D/dalvikvm(968): GC_CONCURRENT freed 492K, 7% free 8407K/8967K, paused 108ms+93ms, total 243ms
08-21 09:05:41.125: D/webviewglue(968): nativeDestroy view: 0x2a0ffb80
08-21 09:06:59.985: D/dalvikvm(968): GC_CONCURRENT freed 514K, 7% free 8435K/9031K, paused 119ms+6ms, total 192ms
08-21 09:06:59.985: D/dalvikvm(968): WAIT_FOR_CONCURRENT_GC blocked 17ms
08-21 09:08:32.355: E/Trace(1027): error opening trace file: No such file or directory (2)
08-21 09:08:34.666: D/dalvikvm(1027): GC_CONCURRENT freed 261K, 4% free 8141K/8455K, paused 99ms+5ms, total 158ms
08-21 09:08:35.925: D/dalvikvm(1027): GC_CONCURRENT freed 371K, 6% free 8162K/8647K, paused 78ms+5ms, total 134ms
08-21 09:08:37.265: D/dalvikvm(1027): GC_CONCURRENT freed 420K, 7% free 8185K/8711K, paused 111ms+96ms, total 248ms
08-21 09:08:38.425: D/dalvikvm(1027): GC_FOR_ALLOC freed 378K, 6% free 8211K/8711K, paused 38ms, total 38ms
08-21 09:08:39.155: D/dalvikvm(1027): GC_CONCURRENT freed 358K, 6% free 8240K/8711K, paused 97ms+5ms, total 144ms
08-21 09:08:39.955: I/Choreographer(1027): Skipped 40 frames!  The application may be doing too much work on its main thread.
08-21 09:08:39.995: D/gralloc_goldfish(1027): Emulator without GPU emulation detected.
08-21 09:08:40.365: I/Choreographer(1027): Skipped 53 frames!  The application may be doing too much work on its main thread.

Cosa sbaglio? :-[

Offline emaborsa

  • Utente normale
  • ***
  • Post: 274
  • Java Developer
  • Respect: +33
    • Google+
    • emaborsa
    • Mostra profilo
    • www.emaborsa.com
  • Dispositivo Android:
    Samsung Galaxy S2
  • Sistema operativo:
    Linux 10 - Win8.1 - Android 4.1.2
Re:URL
« Risposta #3 il: 21 Agosto 2012, 11:17:19 CEST »
0
...temo tu non abbia capito come funziona l'AsyncTask Questo dev'essere creato nella Activity, e deve fare la chiamata con l'URL. Inoltre devi implementare alcuni metodi, che poi vengono chiamati dal framework.

Offline bradipao

  • Moderatore globale
  • Utente storico
  • *****
  • Post: 4043
  • keep it simple
  • Respect: +567
    • Github
    • Google+
    • bradipao
    • Mostra profilo
  • Dispositivo Android:
    Nexus 5
  • Play Store ID:
    Bradipao
  • Sistema operativo:
    W7
Re:URL
« Risposta #4 il: 21 Agosto 2012, 11:25:18 CEST »
0
Cosa sbaglio? :-[

Mi sa che hai copiato una parte sbagliato di LogCat, perchè non c'è nessun errore della tua applicazione.

Comunque, la tua implementazione e uso dell'AsyncTask è abbastanza diversa da quella dell'esempio che ti ho indicato, e non sono sicuro possa funzionare. Se hai assoluta necessità di seguire la tua strada, comincia a loggare un po' di punti intermedi (con Log.d() ) e vedi dove l'esecuzione deraglia da quanto previsto.
NON rispondo a domande nei messaggi privati
Bradipao @ Play Store