2016-12-02 4 views
1

Я использую одну кнопку для выполнения двух задач.Single button multiple action

  1. Watson Разговор.
  2. Watson текст в речь.

Мой код выполняется только в том случае, если у моего TextView есть текстовое имя (строка), но текст в речь воспроизводит последний ответ от ответа, даже если новый ответ отклика обновляется на дисплее TextView на моем пользовательском интерфейсе телефона. Продолжение этого здесь Race condition with UI thread issue.

Также я узнал, если я держу TextView пустой я получаю ошибку: это enter image description here код здесь:

private class ConversationTask extends AsyncTask<String, Void, String> { 
    String textResponse = new String(); 
    @Override 
    protected String doInBackground(String... params) { 
     System.out.println("in doInBackground"); 
     MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build(); 
     // async 
     GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() { 
      @Override 
      public void onResponse(MessageResponse response) { 
       context = response.getContext(); 
       textResponse = response.getText().get(0); 
       reply.setText(textResponse); 
       System.out.println(textResponse); 
      } 
      @Override 
      public void onFailure(Exception e) { 
      } 
     }); 
     return textResponse; 
    } 
} 

// 
private class WatsonTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(final String... textToSpeak) { 
     /* runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       textView.setText(" "); 
      } 
     });*/ 
     TextToSpeech textToSpeech = initTextToSpeechService(); 
     streamPlayer = new StreamPlayer(); 
     streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute()); 
     return "Text to Speech Done"; 
    } 
    /*@Override protected void onPostExecute(String result) { 
     textView.setText(""); 
    }*/ 
} 

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

    //Register the UI controls. 
    input = (EditText) findViewById(R.id.input); 
    send = (ImageButton) findViewById(R.id.send); 
    textView = (TextView) findViewById(R.id.textView); 
    reply = (TextView) findViewById(R.id.reply); 
    play = (ImageButton) findViewById(R.id.play); 
    new ConversationTask().execute(""); 

    //Button function 
    send.setOnClickListener(action3); 
} 


    //five actions on button click 
public void action5() { 
    String textResponse = new String(); 
    System.out.println("Text to Speech:" + reply.getText()); 
    //textView.setText(""); 
    WatsonTask task = new WatsonTask(); 
    task.execute(String.valueOf(reply.getText())); 
    //new WatsonTask().execute(reply.getText().toString()); 
} 


View.OnClickListener action3 = new View.OnClickListener() { 
    public void onClick(View v) { 
     //action here// 
     new ConversationTask().execute(input.getText().toString()); 
     action5(); 
    } 
}; 

}

Пожалуйста, помогите.

+1

Предоставлять код и ошибки не на фотографиях. вы можете опубликовать их отформатированные здесь. – XtremeBaumer

+0

Добавил код выше. Пожалуйста, проверьте –

+0

. Вы пытались переместить логику action5() в onResponse внутри asyncTask? –

ответ

1

Действие 3

View.OnClickListener action3 = new View.OnClickListener() { 
    public void onClick(View v) { 
     //action here// 
     new ConversationTask().execute(input.getText().toString()); 
    } 
}; 

Действие 5

public void action5(String replyString) { 
    WatsonTask task = new WatsonTask(); 
    task.execute(replyString); 
} 

Диалог Задача

private class ConversationTask extends AsyncTask<String, Void, String> { 
    String textResponse = new String(); 
    @Override 
    protected String doInBackground(String... params) { 
     System.out.println("in doInBackground"); 
     MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build(); 
     // async 
     GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() { 
      @Override 
      public void onResponse(MessageResponse response) { 
       context = response.getContext(); 
       textResponse = response.getText().get(0); 
       reply.setText(textResponse); 
       action5(textResponse); 
      } 
      @Override 
      public void onFailure(Exception e) { 
      } 
     }); 
     return textResponse; 
    } 
} 

WatsonTask

private class WatsonTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(final String... textToSpeak) { 
     reply.setText(textToSpeak[0]); 
     TextToSpeech textToSpeech = initTextToSpeechService(); 
     streamPlayer = new StreamPlayer(); 
     streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute()); 
     return textToSpeak[0]; 
    } 
} 

И ради полноты адреса на комментарий Марчин Jedynak

+0

Благодарим за редактирование. Я пробовал, но ничего не слышал. –

+0

@Juian The Audio сейчас платит, но пока нет ответа на разговор в моем телефоне UI –

+0

@sabiha taskin Я отредактировал свой ответ, проверьте его, пожалуйста, –

0

Я думаю, что ваш сценарий программа будет следовать следующие последовательности:

  1. Введите текст для разговора задачи.

  2. Получить результат беседы из GLS_service.message().

  3. Введите результат из последовательности 2, чтобы сделать голос.

Итак, попробуйте изменить ваш код так.

// There is no need to return String. Just send result to TextToSpeech. 
//private class ConversationTask extends AsyncTask<String, Void, String> { 
private class ConversationTask extends AsyncTask<String, Void, Void> { 
    String textResponse = new String(); 
    @Override 
    protected String doInBackground(String... params) { 
     System.out.println("in doInBackground"); 
     MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build(); 
     // async 
     GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() { 
      @Override 
      public void onResponse(MessageResponse response) { 
       context = response.getContext(); 
       textResponse = response.getText().get(0); 
       reply.setText(textResponse); 
       System.out.println(textResponse); 
       action5(textResponse); // It is real result that you want. 
      } 
      @Override 
      public void onFailure(Exception e) { 
      } 
     }); 
     //return textResponse; // Not necessary. 
    } 
} 

// 
private class WatsonTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(final String... textToSpeak) { 
     /* runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       textView.setText(" "); 
      } 
     });*/ 
     TextToSpeech textToSpeech = initTextToSpeechService(); 
     streamPlayer = new StreamPlayer(); 
     streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute()); 
     return "Text to Speech Done"; 
    } 
    /*@Override protected void onPostExecute(String result) { 
     textView.setText(""); 
    }*/ 
} 

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

    //Register the UI controls. 
    input = (EditText) findViewById(R.id.input); 
    send = (ImageButton) findViewById(R.id.send); 
    textView = (TextView) findViewById(R.id.textView); 
    reply = (TextView) findViewById(R.id.reply); 
    play = (ImageButton) findViewById(R.id.play); 
    new ConversationTask().execute(""); 

    //Button function 
    send.setOnClickListener(action3); 
} 


    //five actions on button click 
// Need a parameter to get String. 
//public void action5() { 
public void action5(String text) { 
    // String textResponse = new String(); // Replace to parameter as "text". 
    //System.out.println("Text to Speech:" + reply.getText()); 
    System.out.println("Text to Speech:" + text); 
    //textView.setText(""); 
    WatsonTask task = new WatsonTask(); 
    //task.execute(String.valueOf(reply.getText())); 
    task.execute(text); // Replace to parameter as "text". 
    //new WatsonTask().execute(reply.getText().toString()); 
} 


View.OnClickListener action3 = new View.OnClickListener() { 
    public void onClick(View v) { 
     //action here// 
     new ConversationTask().execute(input.getText().toString()); 
     // action5(); // This invoking is not necessary at this point. 
     // Try to invoke this method after you get conversation result. 
    } 
}; 

Если он не работает, даже вы изменились, я хочу знать, как вы реализуете initTextToSpeechService() метод.

Надеюсь, это вам поможет.

+0

Спасибо, что вы правы с последовательностью. Я попробовал ваш код, но Voice не воспроизводится. Также я внес изменения в ConversationTask(), который вы предоставили: protected Void doInBackground (String ... params). –

+0

My 'initTextToSpeech()' is: 'private TextToSpeech initTextToSpeechService() { TextToSpeech service = new TextToSpeech(); String username = "xxxxxxxxxxx"; Строковый пароль = "xxxxxxxxxxxx"; service.setUsernameAndPassword (имя пользователя, пароль); service.setEndPoint ("https://stream.watsonplatform.net/text-to-speech/api"); служба возврата; } ' –

+0

Также я не вижу' System.out.println («Текст в речь:« + текст »),' в моей консоли –