2011-11-16 5 views
0

J'essaie d'utiliser l'exemple VoiceRecognition pour envoyer du texte reconnu par la voix à un bot Internet. Tout ce dont j'ai besoin est d'envoyer des informations à une URL et d'obtenir le code HTML. J'ai trouvé un problème en essayant de démarrer httpclient dans onActivityResult, et je ne sais pas comment le résoudre. Voici le code:Comment lancer une nouvelle activité ou tâche depuis onActivityResult

public class BkVRMobileActivity extends Activity 
{ 

    private static final int REQUEST_CODE = 1234; 
    private ListView wordsList; 
    private TextView texto1; 
    private TextView texto2; 

    /** 
    * Called with the activity is first created. 
    */ 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.voice_recog); 

    ImageButton speakButton = (ImageButton) findViewById(R.id.speakButton); 
    wordsList = (ListView) findViewById(R.id.list); 
    texto1 = (TextView) findViewById(R.id.textView1); 
    texto2 = (TextView) findViewById(R.id.textView2); 

    // Disable button if no recognition service is present 
    PackageManager pm = getPackageManager(); 
    List<ResolveInfo> activities = pm.queryIntentActivities(
      new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); 
    if (activities.size() == 0) 
    { 
     speakButton.setEnabled(false); 
    } 

} 

/** 
* Handle the action of the button being clicked 
*/ 
public void speakButtonClicked(View v) 
{ 
    startVoiceRecognitionActivity(); 
    System.out.println("--al lio --"); 
    } 

/** 
* Fire an intent to start the voice recognition activity. 
*/ 
private void startVoiceRecognitionActivity() 
{ 
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
      RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Reconocimiento de Voz activado..."); 
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1); 
    startActivityForResult(intent, REQUEST_CODE); 
} 

/** 
* Handle the results from the voice recognition activity. 
*/ 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) 

    { 
     ArrayList<String> matches = data.getStringArrayListExtra(
     RecognizerIntent.EXTRA_RESULTS); 
     //wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,matches)); 
     texto1.setText(matches.get(0)); 

     String laurl = "http://www.pandorabots.com/pandora/talk-xml?input=" + matches.get(0) + "&botid=9cd68de58e342fb8"; 

     //open the url using httpclient for reading html source 
     getXML(laurl); 

     //System.out.println(laurl); 



     } 

    //super.onActivityResult(requestCode, resultCode, data); 
} 

public String getXML(String url){ 
    String log = null; 
    try { 

     HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
     HttpGet httpget = new HttpGet(url); // 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 
     texto2.setText(resString); 


    } catch (UnsupportedEncodingException e) { 
     log = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
    } catch (MalformedURLException e) { 
     log = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
    } catch (IOException e) { 
     log = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
    } 

    return log; 

}

}

+0

Problème, quel problème? –

+0

Je reçois cette erreur:/AndroidRuntime (10618): java.lang.RuntimeException: Echec de la livraison du résultat ResultInfo {who = null, demande = 1234, résultat = -1, data = Intent {(a des extras)}} to activity {prototipos .gneis.bk/prototipos.gneis.bk.BkVRMobileActivity}: android.os.NetworkOnMainThreadException – user1049156

Répondre

1
android.os.NetworkOnMainThreadException 

getXML doit fonctionner sur un thread séparé comme il le fait des requêtes réseau (ce qui peut prendre beaucoup de temps) qui, le thread d'interface utilisateur entraînera ANR

Quelque chose comme:

public String getXML(String url){ 
    new AsyncTask<String, Void, String>() { 
       private String doInBackgroundThread(String... params) 
       { 
        try { 

         HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
         HttpGet httpget = new HttpGet(params[0]); // 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 
         return resString; 
        } catch (UnsupportedEncodingException e) { 
        } catch (MalformedURLException e) { 
        } catch (IOException e) { 
        } 
       } 

       @Override 
       protected void onPostExecute(String result) 
       { 
        texto2.setText(result); 
       } 
      }.execute(url); 
} 
+0

Merci enfin j'ai fait quelque chose comme ça. Un nouveau fil a été la solution – user1049156

Questions connexes