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

Java tutorial

Introduction

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

Source

package com.gqp.duoduo.ui.activity;

import android.app.DatePickerDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.speech.VoiceRecognitionService;
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.OrderListAdapter;
import com.gqp.duoduo.base.BaseActivity;
import com.gqp.duoduo.base.Constants;
import com.gqp.duoduo.database.SaleOrder;
import com.gqp.duoduo.model.OrderList;
import com.gqp.duoduo.utils.HttpUrl;
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.Date;
import java.util.List;
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/19.
 */
public class SearchHisOrderActivity 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<SaleOrder> mList;
    private OrderListAdapter adapter;
    private TextView searchCommit;
    private EditText searchText;
    private ImageView search_voice;

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

        setContentView(R.layout.search_his_order_view);

        mList = new ArrayList<>();
        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);
        search_voice = (ImageView) findViewById(R.id.search_voice);
        adapter = new OrderListAdapter(this, mList);
        adapter.setCompositeSubscription(compositeSubscription);
        searchText = (EditText) findViewById(R.id.search_edittext);
        searchCommit = (TextView) findViewById(R.id.search_commit);
        searchCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = searchText.getText().toString();
                if (App.getNetState()) {
                    getInventoryList(input);
                } else {
                    showToast("?????");
                    //                    getLocalData(input);
                }
            }
        });
        search_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                startSearch();
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(SearchHisOrderActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        //EditText ?100
                        searchText.setText(new StringBuilder().append(year).append("-")
                                .append((month + 1) < 10 ? "0" + (month + 1) : (month + 1)).append("-")
                                .append((day < 10) ? "0" + day : day));
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
                        .show();

            }
        });

        ListView listView = (ListView) findViewById(R.id.search_result_listview);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(SearchHisOrderActivity.this, HisOrderDetailActivity.class);
                intent.putExtra("id", mList.get(position).getIrcode());
                intent.putExtra("knowsapp", mList.get(position).getKnowsapp());
                SearchHisOrderActivity.this.startActivity(intent);
            }
        });

        compositeSubscription
                .add(RxView.clickEvents(findViewById(R.id.search_back)).subscribe(new Action1<ViewClickEvent>() {
                    @Override
                    public void call(ViewClickEvent viewClickEvent) {
                        finish();
                    }
                }));

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

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

                        if (App.getNetState()) {
                            getInventoryList(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<RepsitoryList.RowsEntity> tmpList = new_version ArrayList<>();
     List<Goods> list = App.getDaoSession(this).getGoodsDao().queryBuilder().where(GoodsDao.Properties.Goodsname.like("%" + input + "%")).limit(10).list();
     for (Goods goods:list){
         RepsitoryList.RowsEntity entity = new_version RepsitoryList.RowsEntity();
         entity.setGoodscode(goods.getGoodscode());
         entity.setBigunit(goods.getBigunit());
         entity.setChangeunit(goods.getChangeunit());
         entity.setGoodsname(goods.getGoodsname());
         entity.setImg(goods.getImagpath());
         entity.setNowinventorybignum(goods.getBigunitnum());
         entity.setNowinventorynum(goods.getUnitnum());
         entity.setUnit(goods.getUnit());
         entity.setManufacturedate(goods.getProductionperiod());
         tmpList.add(entity);
     }
     mList.clear();
        
     mList.addAll(tmpList);
     adapter.notifyDataSetChanged();
     }*/
    private void getInventoryList(String input) {

        if (TextUtils.isEmpty(input)) {
            return;
        }
        //        try {
        //            SimpleDateFormat sf = new_version SimpleDateFormat("yyyyMMdd");
        //            Date date = sf.parse(input);
        //            SimpleDateFormat sf1 = new_version SimpleDateFormat("yyyy-MM-dd");
        //            input = sf1.format(date);
        //        }catch (Exception e){
        //            e.printStackTrace();
        //        }

        FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder().add("page", "0").add("size", "100");
        formEncodingBuilder.add("status", "4");
        formEncodingBuilder.add("customer", input);
        Request request = new Request.Builder().url(HttpUrl.ORDER_LIST_NEW).post(formEncodingBuilder.build())
                .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
                .tag(System.currentTimeMillis()).build();

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

                    }

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

                    @Override
                    public void onNext(OrderList inventoryList) {
                        int size = inventoryList.getRows().get(0).getPageList().size();
                        mList.clear();
                        mList.addAll(inventoryList.getRows().get(0).getPageList());
                        adapter.notifyDataSetChanged();

                    }
                }));
    }

    public void startSearch() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SearchHisOrderActivity.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) {
            getInventoryList(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;
        }
    }
}