NullPointerException正在代码上发生

时间:2014-11-26 06:35:04

标签: java android android-intent android-fragments nullpointerexception

我想要做的是在InputActivity上获取语音结果并将结果传递给片段。 CashExpensefragment是片段之一。基本片段为CashExpensefragment(此片段已在调用InputActivity时显示) 这是logcat

NullPointerException正在这里发生:

11-26 15:23:49.249: E/AndroidRuntime(6157): Caused by: java.lang.NullPointerException
11-26 15:23:49.249: E/AndroidRuntime(6157):     at com.example.money.ExpenseCashFragment.getVoiceResult(ExpenseCashFragment.java:64)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at com.example.money.ExpenseCashFragment.onCreateView(ExpenseCashFragment.java:55)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.app.Activity.performStart(Activity.java:5216)
11-26 15:23:49.249: E/AndroidRuntime(6157):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2083)

InputActivity代码

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);            //intent 생성
    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");
        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.commitAllowingStateLoss();
    }
    ///음성인식 결과값 전달 인텐트

/*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();

}
}

ExpenseCashFragment

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) {
    super.onCreate(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(){
    //
    Bundle args = getArguments();
    CharSequence voiceResult01 = args.getCharSequence("t1");
    CharSequence voiceResult02 = args.getCharSequence("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();
    //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:
    }
}


}

0 个答案:

没有答案