如何将语音识别结果添加到片段?

时间:2014-11-21 20:21:03

标签: android fragment speech-recognition

我的代码结构如下所示;

InputActivity,有开销按钮,收听按钮,语音按钮(此东西属于InputActivity)和片段部分。

如果单击开销按钮,则片段部分将更改为expensefragment,如果单击earningbutton,则片段部分将更改为earningfragment。

每个片段都有一个EditText - 费用,解释。

如果单击“语音”按钮,则会启动SpeechToText API。

我想要做的是向每个片段发送一个语音结果。我尝试了很多东西,但我找不到让它发挥作用的方法。

我的代码如下;

public class InputActivity extends FragmentActivity implements OnClickListener {
private final int GOOGLE_STT = 1000;
final String TAG = "InputActivity";
int mCurrentFragmentIndex;
private ArrayList<String> mResult;
private TextView mResultTextView01;
private TextView mResultTextView02;
public final static int FRAGMENT_ONE = 0;
public final static int FRAGMENT_TWO = 1;
public final static int FRAGMENT_THREE = 2;
public final static int FRAGMENT_FOUR = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_input);
    Button bt_oneFragment = (Button) findViewById(R.id.bt_oneFragment);
    Button bt_twoFragment = (Button) findViewById(R.id.bt_twoFragment);
    Button bt_threeFragment = (Button) findViewById(R.id.bt_threeFragment);
    Button bt_fourFragment = (Button) findViewById(R.id.bt_fourFragment);
    Button bt_voice = (Button) findViewById(R.id.bt_Voice); 
    bt_oneFragment.setOnClickListener(this);
    bt_twoFragment.setOnClickListener(this);
    bt_threeFragment.setOnClickListener(this);
    bt_fourFragment.setOnClickListener(this);
    bt_voice.setOnClickListener(this);
    mResultTextView01 = (EditText)findViewById(R.id.cost); // I know it is not working
    mResultTextView02 = (EditText)findViewById(R.id.explanation); //
    mCurrentFragmentIndex = FRAGMENT_ONE;
    fragmentReplace(mCurrentFragmentIndex);

}

public void fragmentReplace(int reqNewFragmentIndex) {

    Fragment newFragment = null;
    newFragment = getFragment(reqNewFragmentIndex);

    // replace fragment
    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    transaction.replace(R.id.display_fragment, newFragment);

    // Commit the transaction
    transaction.commit();

}

private Fragment getFragment(int idx) {
    Fragment newFragment = null;

    switch (idx) {
    case FRAGMENT_ONE:
        newFragment = new ExpenseCashFragment();
        break;
    case FRAGMENT_TWO:
        newFragment = new ExpenseAccountFragment();
        break;
    case FRAGMENT_THREE:
        newFragment = new EarningCashFragment();
        break;
    case FRAGMENT_FOUR:
        newFragment = new EarningAccountFragment();
        break;

    default:
        Log.d(TAG, "Unhandle case");

    }

    return newFragment;
}

@Override
public void onClick(View v) {

    switch (v.getId()) {

    case R.id.bt_oneFragment:
        mCurrentFragmentIndex = FRAGMENT_ONE;
        fragmentReplace(mCurrentFragmentIndex);
        break;
    case R.id.bt_twoFragment:
        mCurrentFragmentIndex = FRAGMENT_TWO;
        fragmentReplace(mCurrentFragmentIndex);
        break;
    case R.id.bt_threeFragment:
        mCurrentFragmentIndex = FRAGMENT_THREE;
        fragmentReplace(mCurrentFragmentIndex);
        break;
    case R.id.bt_fourFragment:
        mCurrentFragmentIndex = FRAGMENT_FOUR;
        fragmentReplace(mCurrentFragmentIndex);
        break;

    default:
    }

    if (v.getId() == R.id.bt_Voice){
        Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);    
        i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());   
        i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR");                           
        i.putExtra(RecognizerIntent.EXTRA_PROMPT, "speak.");    
        startActivityForResult(i, GOOGLE_STT);;
        }

}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.display_fragment);
    fragment.onActivityResult(requestCode, resultCode, data);
    if( resultCode == RESULT_OK ){  
        showResult(requestCode, data);
    }
    else{                                                       
        String msg = null;

        switch(resultCode){
            case SpeechRecognizer.ERROR_AUDIO:
                msg = "";
                break;
            case SpeechRecognizer.ERROR_CLIENT:
                msg = "";
                break;
            case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                msg = "";
                break;
            case SpeechRecognizer.ERROR_NETWORK:
            case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                msg = ".";
                break;
            case SpeechRecognizer.ERROR_NO_MATCH:
                msg = ".";
                break;
            case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                msg = ".";
                break;
            case SpeechRecognizer.ERROR_SERVER:
                msg = ".";
                break;
            case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                msg = ".";
                break;
        }

        if(msg != null) 
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

}    private void showResult(int requestCode, Intent data){
    String key = "";
    if(requestCode == GOOGLE_STT)           
        key = RecognizerIntent.EXTRA_RESULTS;

    mResult = data.getStringArrayListExtra(key);
    String[] result = new String[mResult.size()];
    mResult.toArray(result);
    String i = result[0];
    String[] count = i.split(" ");
    mResultTextView01.setText(""+count[0]);
    mResultTextView02.setText(""+count[1]);
}
}

,其中一个片段代码如下所示

public class ExpenseCashFragment extends Fragment implements OnClickListener, AdapterView.OnItemSelectedListener 
{

DatePicker datepicker;
Spinner spinner;
Button button;
EditText cost, explanation;
DBAdapter dbAdapter;
String st; // Just for transferring the category data


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.expensecashfragment, container, false);
    spinner = (Spinner) view.findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.expenseCategory, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    datepicker = (DatePicker)view.findViewById(R.id.datepicker);

    //If you want to use this in Activity in the Fragment use getActivity() instead

    openDB();
    return view;
}


@Override
public void onDestroy()
{
    closeDB();
}

private void openDB() {
    dbAdapter = new DBAdapter(getActivity());
    dbAdapter.openW();

}

public void enterData()
{
    String date = setDate();

    if(cost.getText().toString() == null)
        return;

    int cost_value = Integer.parseInt(cost.getText().toString());
    String explanation_value = explanation.getText().toString();
    //Message.message(getActivity(), date + " " + st + " " + cost_value + " " + explanation_value );
    //category string is in the st

    CashExpenseTable ce = new CashExpenseTable(date, st, cost_value, explanation_value);
    long id = dbAdapter.addCashExpense(ce);

    if(id > 0)
    {
        Message.message(getActivity(), "Successfully inserted a row " + id);
    }
    else
    {
        Message.message(getActivity(), "Unsuccessful");
    }
    startActivity(new Intent(this.getActivity(), MainActivity.class));

}

private void closeDB() 
{
    dbAdapter.close();
}


@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
    TextView myText = (TextView) view;
    Toast.makeText(getActivity(), "You selected " + myText.getText(), Toast.LENGTH_SHORT).show();   
    st = (String) myText.getText();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
    // TODO Auto-generated method stub

}

///////////////////////////////////////////////////////// For the datePicker
public String setDate()
{
    int day = datepicker.getDayOfMonth();
    int month = datepicker.getMonth() + 1;
    int year = datepicker.getYear();
    //Toast.makeText(getActivity(), "Today : " + year + "/" + month + "/" + day, Toast.LENGTH_LONG).show();
    return year + "-" + month + "-" + day;
}

@Override
public void onClick(View v) 
{
    switch (v.getId()) {

    case R.id.enterButton:
        //Toast.makeText(getActivity(), "Input completed", Toast.LENGTH_SHORT).show();
        enterData();
        break;

    default:
    }
}
}

我甚至尝试将语音识别代码放入片段中,但我无法使其工作。

1 个答案:

答案 0 :(得分:1)

您的Fragment需要为onActivityResult()方法提供覆盖。您目前正在查找有效的Fragment并调用该方法,但您的Fragment并未提供实施。