com.gqp.duoduo.ui.activity.SearchProductForOrderActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.gqp.duoduo.ui.activity.SearchProductForOrderActivity.java

Source

package com.gqp.duoduo.ui.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.speech.VoiceRecognitionService;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.gqp.common.adapter.ViewHolderBind;
import com.gqp.common.cache.SpCache;
import com.gqp.common.exception.ErrorMessageException;
import com.gqp.common.http.HttpRequest;
import com.gqp.common.rx.android.schedulers.AndroidSchedulers;
import com.gqp.common.rx.bus.RxBus;
import com.gqp.duoduo.App;
import com.gqp.duoduo.R;
import com.gqp.duoduo.adapter.SearchGoodsResultAdapter;
import com.gqp.duoduo.base.BaseActivity;
import com.gqp.duoduo.base.Constants;
import com.gqp.duoduo.database.DeliverModel;
import com.gqp.duoduo.database.Goods;
import com.gqp.duoduo.database.OrderDeliverModel;
import com.gqp.duoduo.database.dao.GoodsDao;
import com.gqp.duoduo.model.GoodsList;
import com.gqp.duoduo.utils.HttpUrl;
import com.gqp.duoduo.utils.StringUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.view.ViewClickEvent;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * Created by admin on 2015/10/29.
 */
public class SearchProductForOrderActivity extends BaseActivity implements RecognitionListener {
    //?
    private static final int REQUEST_UI = 1;
    public static final int STATUS_None = 0;
    public static final int STATUS_WaitingReady = 2;
    public static final int STATUS_Ready = 3;
    public static final int STATUS_Speaking = 4;
    public static final int STATUS_Recognition = 5;
    private SpeechRecognizer speechRecognizer;
    private int status = STATUS_None;
    private long speechEndTime = -1;
    private static final int EVENT_ERROR = 11;

    private List<Goods> mList;
    //    private SearchGoodsResultAdapter adapter;
    private TextView searchCommit;
    private EditText searchText;
    private String id, name, isBarcode;
    private TextView searchOk, search_num;
    private LinearLayout listView;
    private ImageView search_voice;
    private Map<String, Goods> selectMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_goods_view);
        id = getIntent().getStringExtra(Constants.PARAM_MARKET_CODE);
        name = getIntent().getStringExtra(Constants.PARAM_MARKET_NAME);
        isBarcode = getIntent().getStringExtra("isBarcode");
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        sp.edit().remove(Constants.EXTRA_INFILE).commit(); // infile?PCM?????
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this,
                new ComponentName(this, VoiceRecognitionService.class));
        speechRecognizer.setRecognitionListener(this);
        mList = new ArrayList<>();
        selectMap = new HashMap<>();

        //        adapter = new_version SearchGoodsResultAdapter(this, mList);
        searchText = (EditText) findViewById(R.id.search_edittext);
        searchCommit = (TextView) findViewById(R.id.search_commit);
        searchOk = (TextView) findViewById(R.id.search_result_ok);
        search_num = (TextView) findViewById(R.id.search_num);
        search_voice = (ImageView) findViewById(R.id.search_voice);

        if (!TextUtils.isEmpty(isBarcode)) {
            searchText.setText(isBarcode);
        }
        searchCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = searchText.getText().toString();
                if (App.getNetState()) {
                    getGoodsList(input);

                } else {
                    showToast("???");
                    getLocalData(input);
                }
            }
        });

        search_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSearch();
            }
        });

        searchOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataInsert(selectMap);
                selectMap = new HashMap<String, Goods>();
                mList = new ArrayList<Goods>();
                listView.removeAllViews();
                searchText.setText("");
                Intent intent = new Intent(SearchProductForOrderActivity.this, UpdateDeliverActivity.class);
                SearchProductForOrderActivity.this.startActivity(intent);
                SearchProductForOrderActivity.this.finish();
            }
        });

        listView = (LinearLayout) findViewById(R.id.search_result_listview);
        //        listView.setAdapter(adapter);

        compositeSubscription
                .add(RxView.clickEvents(findViewById(R.id.search_back)).subscribe(new Action1<ViewClickEvent>() {
                    @Override
                    public void call(ViewClickEvent viewClickEvent) {
                        finish();
                    }
                }));
        compositeSubscription.add(RxBus.getDefault().register(SearchGoodsResultAdapter.Event.class)
                .subscribe(new Action1<SearchGoodsResultAdapter.Event>() {
                    @Override
                    public void call(SearchGoodsResultAdapter.Event searchGoodsResultAdapter) {
                        search_num.setText("?" + searchGoodsResultAdapter.getNum() + "?");
                    }
                }));

        compositeSubscription.add(RxTextView.textChangeEvents((EditText) findViewById(R.id.search_edittext))
                .throttleLast(2, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TextViewTextChangeEvent>() {
                    @Override
                    public void call(TextViewTextChangeEvent textViewTextChangeEvent) {

                        String input = textViewTextChangeEvent.text().toString();

                        if (App.getNetState()) {
                            getGoodsList(input);

                        } else {
                            showToast("???");
                            getLocalData(input);
                        }

                    }
                })

        );

        Observable<MainActivity.MainActivityEvent.DeliverEvent> deliverEventObservable = RxBus.getDefault()
                .register(MainActivity.MainActivityEvent.DeliverEvent.class);

        compositeSubscription
                .add(deliverEventObservable.subscribe(new Action1<MainActivity.MainActivityEvent.DeliverEvent>() {
                    @Override
                    public void call(MainActivity.MainActivityEvent.DeliverEvent deliverEvent) {

                        finish();
                    }
                }));

    }

    private void getLocalData(String input) {
        if (TextUtils.isEmpty(input)) {
            return;
        }
        List<Goods> list = App.getDaoSession(this).getGoodsDao().queryBuilder()
                .where(GoodsDao.Properties.Goodsname.like("%" + input + "%")).limit(10).list();
        mList.clear();
        mList.addAll(list);
        listView.removeAllViews();
        if (mList != null && mList.size() > 0) {
            LayoutInflater inflater = LayoutInflater.from(SearchProductForOrderActivity.this);
            int index = 0;
            for (Goods entity : mList) {
                View view = inflater.inflate(R.layout.search_goods_view_item, null);
                SearchGoodsViewItemHolder holder = new SearchGoodsViewItemHolder(view);
                holder.bind(entity, index);
                listView.addView(view);

                View divider = new View(SearchProductForOrderActivity.this);
                divider.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                divider.setBackgroundColor(Color.parseColor("#dddddd"));
                listView.addView(divider);

                index++;
            }

        }
    }

    private void getGoodsList(String input) {

        if (TextUtils.isEmpty(input)) {
            return;
        }
        FormEncodingBuilder builder = new FormEncodingBuilder().add("customerid", id).add("page", "0").add("size",
                "65535");
        if (!TextUtils.isEmpty(isBarcode)) {
            builder.add("barcode", input);
            builder.add("goodsname", "");
        } else {
            builder.add("goodsname", input);
        }
        Request request = new Request.Builder().url(HttpUrl.QUERY_GOODS).post(builder.build())
                .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
                .tag(System.currentTimeMillis()).build();

        compositeSubscription
                .add(HttpRequest.modelRequest(request, GoodsList.class).subscribe(new Subscriber<GoodsList>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        //                                showToast("");
                        if (e instanceof ErrorMessageException) {
                            if (App.getNetState()) {
                                reLogin();
                            } else {
                                showToast("??");
                            }
                        }
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onNext(GoodsList inventoryList) {
                        mList.clear();
                        mList.addAll(inventoryList.getRows());
                        listView.removeAllViews();
                        if (mList != null && mList.size() > 0) {
                            LayoutInflater inflater = LayoutInflater.from(SearchProductForOrderActivity.this);
                            int index = 0;
                            for (Goods entity : mList) {
                                View view = inflater.inflate(R.layout.search_goods_view_item, null);
                                SearchGoodsViewItemHolder holder = new SearchGoodsViewItemHolder(view);
                                holder.bind(entity, index);
                                listView.addView(view);

                                View divider = new View(SearchProductForOrderActivity.this);
                                divider.setLayoutParams(
                                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
                                divider.setBackgroundColor(Color.parseColor("#dddddd"));
                                listView.addView(divider);

                                index++;
                            }

                        }
                    }
                }));
    }

    public void dataInsert(Map<String, Goods> map) {
        if (map != null) {
            Iterator<Map.Entry<String, Goods>> it = map.entrySet().iterator();
            String marketName = SpCache.getString(Constants.CURRENT_MARKET_NAME, "");
            while (it.hasNext()) {
                Map.Entry<String, Goods> entry = it.next();
                Goods goodsEntity = entry.getValue();

                //                App.getDaoSession(this).getDeliverModelDao().queryBuilder().where(DeliverModelDao.Properties.Id.like("%" + goodsEntity.getGoodscode() + "%")).buildDelete().executeDeleteWithoutDetachingEntities();
                //////////
                OrderDeliverModel model = new OrderDeliverModel();
                model.setMarketName(marketName);

                model.setName(goodsEntity.getGoodsname());
                model.setGoodscode(goodsEntity.getGoodscode());

                Gson gson = new Gson();
                String jsonstr = gson.toJson(goodsEntity, Goods.class);
                model.setGoodsjson(jsonstr);

                model.setId(goodsEntity.getGoodscode() + "_0");

                model.setType("0");

                model.setBignum(0);

                model.setNum(0);
                model.setSaveday(goodsEntity.getSaveday());
                model.setChangeunit(goodsEntity.getChangeunit());
                model.setBigcostprice(goodsEntity.getBigitemprice());

                model.setCostprice(goodsEntity.getItemprice());

                model.setBigunit(goodsEntity.getBigunit());

                model.setUnit(goodsEntity.getUnit());
                model.setBigKuCun(goodsEntity.getBigunitnum());
                model.setKuCun(goodsEntity.getUnitnum());

                model.setImg(goodsEntity.getImagpath());
                model.setBarCode(goodsEntity.getBarcode());

                model.setIsAdd("0");

                model.setIscheck(false);
                model.setBrand(goodsEntity.getBrand());
                model.setBrandname(goodsEntity.getBrandname());

                if (TextUtils.isEmpty(goodsEntity.getProductionperiod())) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DATE, -18);
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    model.setProductdate(sf.format(calendar.getTime()));
                } else {
                    model.setProductdate(goodsEntity.getProductionperiod());
                }
                Calendar calendar = Calendar.getInstance();
                model.setCreatetime("" + calendar.getTimeInMillis());

                App.getDaoSession(this).getOrderDeliverModelDao().insertOrReplace(model);

            }
        }

    }

    public class SearchGoodsViewItemHolder extends ViewHolderBind<Goods> {
        private SimpleDraweeView deliverViewItemIcon;
        private TextView deliverViewItemName;
        private TextView deliverViewItemDate;
        private TextView deliverViewItemNum;
        private CheckBox deliverViewItemCheck;

        public SearchGoodsViewItemHolder(View view) {
            super(view);
            deliverViewItemIcon = (SimpleDraweeView) view.findViewById(R.id.goods_view_item_icon);
            deliverViewItemName = (TextView) view.findViewById(R.id.goods_view_item_name);
            deliverViewItemDate = (TextView) view.findViewById(R.id.goods_view_item_bigitemprice);
            deliverViewItemNum = (TextView) view.findViewById(R.id.goods_view_item_itemprice);
            deliverViewItemCheck = (CheckBox) view.findViewById(R.id.goods_view_item_item_check);
        }

        @Override
        public void bind(final Goods data, int pos) {
            if (!TextUtils.isEmpty(data.getImagpath()) && !data.getImagpath().startsWith(".")) {
                deliverViewItemIcon.setImageURI(Uri.parse(data.getImagpath()));
            }
            deliverViewItemIcon.setOnClickListener(new MyOnClickListener(pos));
            deliverViewItemName.setText(data.getGoodsname());
            deliverViewItemDate.setText("?" + data.getBigunitnum() + data.getBigunit()
                    + data.getUnitnum() + data.getUnit());
            deliverViewItemNum.setText(
                    "???" + StringUtil.priceFormat(data.getItemprice()) + "/" + data.getUnit());
            deliverViewItemCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        if (selectMap == null) {
                            selectMap = new HashMap<String, Goods>();
                        }
                        selectMap.put(data.getGoodscode(), data);
                        search_num.setText("?" + selectMap.size() + "?");
                    } else {
                        if (selectMap != null) {
                            selectMap.remove(data.getGoodscode());
                        }
                        search_num.setText("?" + selectMap.size() + "?");
                    }
                }
            });

        }
    }

    public class MyOnClickListener implements View.OnClickListener {
        private int pos;

        public MyOnClickListener(int pos) {
            this.pos = pos;
        }

        @Override
        public void onClick(View v) {
            Goods entity = mList.get(pos);
            Intent intent = new Intent(SearchProductForOrderActivity.this, UpdateChoiceProductActivity.class);

            intent.putExtra(Constants.PARAM_MARKET_CODE, id);
            intent.putExtra(Constants.PARAM_MARKET_NAME, name);
            intent.putExtra(Constants.PARAM_GOODS_CODE, entity.getGoodscode());
            Gson gson = new Gson();
            String jsonstr = gson.toJson(entity, Goods.class);
            intent.putExtra(Constants.PARAM_GOODS, jsonstr);

            intent.putExtra("comflag", entity.getComflag());
            intent.putExtra("itemprice", entity.getItemprice());
            intent.putExtra("title", entity.getGoodsname());
            intent.putExtra("isCun", entity.getIsHu());
            intent.putExtra("isKu", entity.getIsKu());
            SearchProductForOrderActivity.this.startActivity(intent);
            SearchProductForOrderActivity.this.finish();
        }
    }

    public void startSearch() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SearchProductForOrderActivity.this);
        boolean api = sp.getBoolean("api", false);
        if (api) {
            switch (status) {
            case STATUS_None:
                start();
                //                    searchVoice.setText("?");
                status = STATUS_WaitingReady;
                break;
            case STATUS_WaitingReady:
                cancel();
                status = STATUS_None;
                //                    searchVoice.setText("");
                break;
            case STATUS_Ready:
                cancel();
                status = STATUS_None;
                //                    searchVoice.setText("");
                break;
            case STATUS_Speaking:
                stop();
                status = STATUS_Recognition;
                //                    searchVoice.setText("");
                break;
            case STATUS_Recognition:
                cancel();
                status = STATUS_None;
                //                    searchVoice.setText("");
                break;
            }
        } else {
            start();
        }
    }

    public void bindParams(Intent intent) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("tips_sound", true)) {
            intent.putExtra(Constants.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start);
            intent.putExtra(Constants.EXTRA_SOUND_END, R.raw.bdspeech_speech_end);
            intent.putExtra(Constants.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
            intent.putExtra(Constants.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error);
            intent.putExtra(Constants.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);
        }
        if (sp.contains(Constants.EXTRA_INFILE)) {
            String tmp = sp.getString(Constants.EXTRA_INFILE, "").replaceAll(",.*", "").trim();
            intent.putExtra(Constants.EXTRA_INFILE, tmp);
        }
        if (sp.getBoolean(Constants.EXTRA_OUTFILE, false)) {
            intent.putExtra(Constants.EXTRA_OUTFILE, "sdcard/outfile.pcm");
        }
        if (sp.contains(Constants.EXTRA_SAMPLE)) {
            String tmp = sp.getString(Constants.EXTRA_SAMPLE, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_SAMPLE, Integer.parseInt(tmp));
            }
        }
        if (sp.contains(Constants.EXTRA_LANGUAGE)) {
            String tmp = sp.getString(Constants.EXTRA_LANGUAGE, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_LANGUAGE, tmp);
            }
        }
        if (sp.contains(Constants.EXTRA_NLU)) {
            String tmp = sp.getString(Constants.EXTRA_NLU, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_NLU, tmp);
            }
        }

        if (sp.contains(Constants.EXTRA_VAD)) {
            String tmp = sp.getString(Constants.EXTRA_VAD, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_VAD, tmp);
            }
        }
        String prop = null;
        if (sp.contains(Constants.EXTRA_PROP)) {
            String tmp = sp.getString(Constants.EXTRA_PROP, "").replaceAll(",.*", "").trim();
            if (null != tmp && !"".equals(tmp)) {
                intent.putExtra(Constants.EXTRA_PROP, Integer.parseInt(tmp));
                prop = tmp;
            }
        }

        // offline asr
        {
            intent.putExtra(Constants.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1");
            intent.putExtra(Constants.EXTRA_LICENSE_FILE_PATH, "/sdcard/easr/license-tmp-20150530.txt");
            if (null != prop) {
                int propInt = Integer.parseInt(prop);
                if (propInt == 10060) {
                    intent.putExtra(Constants.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_Navi");
                } else if (propInt == 20000) {
                    intent.putExtra(Constants.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_InputMethod");
                }
            }
            intent.putExtra(Constants.EXTRA_OFFLINE_SLOT_DATA, buildTestSlotData());
        }
    }

    private String buildTestSlotData() {
        JSONObject slotData = new JSONObject();
        JSONArray name = new JSONArray().put("?").put("");
        JSONArray song = new JSONArray().put("").put("?");
        JSONArray artist = new JSONArray().put("?").put("?");
        JSONArray app = new JSONArray().put("").put("");
        JSONArray usercommand = new JSONArray().put("?").put("");
        try {
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_NAME, name);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_SONG, song);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_ARTIST, artist);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_APP, app);
            slotData.put(Constants.EXTRA_OFFLINE_SLOT_USERCOMMAND, usercommand);
        } catch (JSONException e) {

        }
        return slotData.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            onResults(data.getExtras());
        }
    }

    private void start() {
        //        txtLog.setText("");
        //        print("?");
        Intent intent = new Intent();
        bindParams(intent);
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        {

            String args = sp.getString("args", "");
            if (null != args) {
                //                print("?" + args);
                intent.putExtra("args", args);
            }
        }
        boolean api = sp.getBoolean("api", false);
        if (api) {
            speechEndTime = -1;
            speechRecognizer.startListening(intent);
        } else {
            intent.setAction("com.baidu.action.RECOGNIZE_SPEECH");
            startActivityForResult(intent, REQUEST_UI);
        }

        //        txtResult.setText("");
    }

    private void stop() {
        speechRecognizer.stopListening();
        //        print("?");
    }

    private void cancel() {
        speechRecognizer.cancel();
        status = STATUS_None;
        //        print("??");
    }

    @Override
    public void onReadyForSpeech(Bundle params) {
        status = STATUS_Ready;
        //        print("??");
    }

    @Override
    public void onBeginningOfSpeech() {
        status = STATUS_Speaking;
        //        searchVoice.setText("");
        //        print("??");
    }

    @Override
    public void onRmsChanged(float rmsdB) {

    }

    @Override
    public void onBufferReceived(byte[] buffer) {

    }

    @Override
    public void onEndOfSpeech() {
        speechEndTime = System.currentTimeMillis();
        status = STATUS_Recognition;
        //        print("???");
        //        searchVoice.setText("");
    }

    @Override
    public void onError(int error) {
        status = STATUS_None;
        StringBuilder sb = new StringBuilder();
        switch (error) {
        case SpeechRecognizer.ERROR_AUDIO:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_CLIENT:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
            sb.append("???");
            break;
        case SpeechRecognizer.ERROR_NETWORK:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_NO_MATCH:
            sb.append("?");
            break;
        case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
            sb.append("");
            break;
        case SpeechRecognizer.ERROR_SERVER:
            sb.append("?");
            break;
        case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
            sb.append("");
            break;
        }
        sb.append(":" + error);
        //        print("" + sb.toString());
        //        searchVoice.setText("");
    }

    @Override
    public void onResults(Bundle results) {
        long end2finish = System.currentTimeMillis() - speechEndTime;
        status = STATUS_None;
        ArrayList<String> nbest = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        //        print("?" + Arrays.toString(nbest.toArray(new_version String[nbest.size()])));
        System.out.println("" + nbest.get(0));
        //        String json_res = results.getString("origin_result");
        //        try {
        //            print("origin_result=\n" + new_version JSONObject(json_res).toString(4));
        //        } catch (Exception e) {
        //            print("origin_result=[warning: bad json]\n" + json_res);
        //        }
        if (nbest != null && nbest.size() > 0) {
            getGoodsList(nbest.get(0));
        } else {
            showToast("?");
        }
        //        searchVoice.setText("");
        String strEnd2Finish = "";
        if (end2finish < 60 * 1000) {
            strEnd2Finish = "(waited " + end2finish + "ms)";
        }
    }

    @Override
    public void onPartialResults(Bundle partialResults) {
        ArrayList<String> nbest = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        if (nbest.size() > 0) {
            //            print("~" + Arrays.toString(nbest.toArray(new_version String[0])));
        }
    }

    @Override
    public void onEvent(int eventType, Bundle params) {
        switch (eventType) {
        case EVENT_ERROR:
            String reason = params.get("reason") + "";
            //                print("EVENT_ERROR, " + reason);
            break;
        case VoiceRecognitionService.EVENT_ENGINE_SWITCH:
            int type = params.getInt("engine_type");
            //                print("*?" + (type == 0 ? "" : ""));
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compositeSubscription != null) {
            if (!compositeSubscription.isUnsubscribed()) {
                compositeSubscription.unsubscribe();
            }
            compositeSubscription = null;
        }
    }
}