我正在尝试将活动的结果传递给该活动上的片段。
有4个片段和5个按钮。 4个按钮用于更改片段,剩下的是用于语音识别按钮。 我想做的是在完成语音输入时将结果放在片段的成本,语音识别的解释字段中。
语音识别完成后,我的代码崩溃了。我想知道为什么它不起作用,我该怎么做才能使它有效。
这是活动代码
public class InputActivity extends ActionBarActivity implements OnClickListener {
private final int GOOGLE_STT = 1000;
private ArrayList<String> mResult; //음성인식 결과 저장할 list
String mResultTextView01;
String mResultTextView02;
final String TAG = "InputActivity";
int mCurrentFragmentIndex;
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);
bt_oneFragment.setOnClickListener(this);
bt_twoFragment.setOnClickListener(this);
bt_threeFragment.setOnClickListener(this);
bt_fourFragment.setOnClickListener(this);
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");
break;
}
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:
}
}
public void on_bt_voice(View v){
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, "말을 하세요.");
InputActivity.this.startActivityForResult(i, GOOGLE_STT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if( resultCode == RESULT_OK && requestCode == GOOGLE_STT)
{
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); //인식된 데이터 list 받아옴.
String[] result = new String[mResult.size()]; //배열생성.
mResult.toArray(result);// list 배열로 변환
String i = result[0];
String[] count = i.split(" ");
mResultTextView01 = count[0];
mResultTextView02 = count[1];
if(requestCode == GOOGLE_STT){
Log.d(TAG, "fjfj");
ResultTofragment(mResultTextView01, mResultTextView02);
}
}
///음성인식 결과값 전달 인텐트
public void ResultTofragment(String a, String b){
Log.d(TAG, "fj");
switch(mCurrentFragmentIndex)
{
case FRAGMENT_ONE:
Intent intent1 = new Intent(InputActivity.this, ExpenseCashFragment.class);
intent1.putExtra("t1", a);
intent1.putExtra("t2", b);
InputActivity.this.startActivity(intent1);
break;
case FRAGMENT_TWO:
Intent intent2 = new Intent(InputActivity.this, ExpenseAccountFragment.class);
intent2.putExtra("t1", a);
intent2.putExtra("t2", b);
InputActivity.this.startActivity(intent2);
break;
case FRAGMENT_THREE:
Intent intent3 = new Intent(InputActivity.this, EarningCashFragment.class);
intent3.putExtra("t1", a);
intent3.putExtra("t2", b);
InputActivity.this.startActivity(intent3);
break;
case FRAGMENT_FOUR:
Intent intent4 = new Intent(InputActivity.this, EarningAccountFragment.class);
intent4.putExtra("t1", a);
intent4.putExtra("t2", b);
InputActivity.this.startActivity(intent4);
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.input, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:
HomeItem();
break;
default:
}
return true;
}
private void HomeItem()
{
new AlertDialog.Builder(this)
.setTitle("Go to Home")
.setMessage("Want to go to Home?")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(InputActivity.this, MainActivity.class);
InputActivity.this.startActivity(intent);
}
}).show();
}
}
这是我的片段代码之一
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);
cost = (EditText)view.findViewById(R.id.listView_cost);
explanation = (EditText)view.findViewById(R.id.listView_explanation);
button = (Button)view.findViewById(R.id.enterButton);
button.setOnClickListener(this);
//If you want to use this in Activity in the Fragment use getActivity() instead
getVoiceResult();
openDB();
return view;
}
public void getVoiceResult(){
//
Intent intent1 = getActivity().getIntent();
String voiceResult01 = intent1.getStringExtra("t1");
String voiceResult02 = intent1.getStringExtra("t2");
//
cost.setText(""+voiceResult01);
explanation.setText(""+voiceResult02);
Log.d(getTag(), "ggggs");
//
}
@Override
public void onDestroy()
{
super.onDestroy();
closeDB();
}
private void closeDB()
{
dbAdapter.close();
}
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));
}
////////////////////////////////////////////////////////// For the spinner
public void showDialog(View v)
{
}
@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();
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:
}
}
}
这是logcat
11-26 04:50:17.075: E/AndroidRuntime(11263): FATAL EXCEPTION: main
11-26 04:50:17.075: E/AndroidRuntime(11263): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.money/com.example.money.ExpenseCashFragment}: java.lang.ClassCastException: com.example.money.ExpenseCashFragment cannot be cast to android.app.Activity
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.ActivityThread.access$700(ActivityThread.java:140)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.os.Handler.dispatchMessage(Handler.java:99)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.os.Looper.loop(Looper.java:137)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.ActivityThread.main(ActivityThread.java:4946)
11-26 04:50:17.075: E/AndroidRuntime(11263): at java.lang.reflect.Method.invokeNative(Native Method)
11-26 04:50:17.075: E/AndroidRuntime(11263): at java.lang.reflect.Method.invoke(Method.java:511)
11-26 04:50:17.075: E/AndroidRuntime(11263): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)
11-26 04:50:17.075: E/AndroidRuntime(11263): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)
11-26 04:50:17.075: E/AndroidRuntime(11263): at dalvik.system.NativeStart.main(Native Method)
11-26 04:50:17.075: E/AndroidRuntime(11263): Caused by: java.lang.ClassCastException: com.example.money.ExpenseCashFragment cannot be cast to android.app.Activity
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
11-26 04:50:17.075: E/AndroidRuntime(11263): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2025)
11-26 04:50:17.075: E/AndroidRuntime(11263): ... 11 more
答案 0 :(得分:0)
在ResultTofragment函数中,您正在使用四个片段的类对象,并尝试启动片段,就好像它们是活动一样。这就是你得到ClassCastException的原因。
我相信你的意图是显示所选片段,并将你在该函数中添加的Intent extras作为片段的参数传递。有很多方法可以实现这一目标。一种方法是将一个Bundle参数添加到fragmentReplace函数中,然后使用setArguments将其传递给片段:
public void ResultTofragment(String a, String b){
Log.d(TAG, "fj");
Bundle args = new Bundle();
args.putCharSequence("t1", a);
args.putCharSequence("t2", b);
fragmentReplace(mCurrentFragmentIndex, args);
}
public void fragmentReplace(int reqNewFragmentIndex, Bundle args) {
Fragment newFragment = null;
newFragment = getFragment(reqNewFragmentIndex);
if (args != null) {
newFragment.setArguments(args);
}
// replace fragment
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.display_fragment, newFragment);
// Commit the transaction
transaction.commit();
}
请注意,对于其他调用fragmentReplace的地方,如果还没有参数,则可以传递null。最后,在你的片段中,你将从Bundle中获取参数,而不是活动的意图附加信息:
public void getVoiceResult(){
//
Bundle args = getArguments();
CharSequence voiceResult01 = args.getCharSequence("t1");
CharSequence voiceResult02 = args.getCharSequence("t2");
//
cost.setText(""+voiceResult01);
explanation.setText(""+voiceResult02);
Log.d(getTag(), "ggggs");
//
}