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

Java tutorial

Introduction

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

Source

package com.gqp.duoduo.ui.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
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.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.speech.VoiceRecognitionService;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gqp.common.adapter.ViewHolderBind;
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.SearchMoveGoodsResultAdapter;
import com.gqp.duoduo.base.BaseActivity;
import com.gqp.duoduo.base.Constants;
import com.gqp.duoduo.custom.view.NumView;
import com.gqp.duoduo.model.GoodsMoveDetail;
import com.gqp.duoduo.model.InventoryList;
import com.gqp.duoduo.model.ItemModel;
import com.gqp.duoduo.model.MoveItemModel;
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.util.ArrayList;
import java.util.HashMap;
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 SearchMoveGoodActivity 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<GoodsMoveDetail.NormalGoodsEntity> mList;
    //    private SearchMoveGoodsResultAdapter adapter;
    private TextView searchCommit;
    private EditText searchText;
    private String warehousecode, flag;
    private TextView search_result_ok;
    private ImageView search_voice;
    private LinearLayout search_result_listview;
    private Map<String, GoodsMoveDetail.NormalGoodsEntity> selectedGoodsEntityMap;

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

        setContentView(R.layout.search_move_view);
        warehousecode = getIntent().getStringExtra("warehousecode");
        flag = getIntent().getStringExtra("flag");

        mList = new ArrayList<>();
        selectedGoodsEntityMap = new HashMap<>();

        //        adapter = new_version SearchMoveGoodsResultAdapter(this, mList);
        searchText = (EditText) findViewById(R.id.search_edittext1);
        searchCommit = (TextView) findViewById(R.id.search_commit1);
        search_result_ok = (TextView) findViewById(R.id.search_result_ok);
        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);
        search_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSearch();
            }
        });

        searchCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = searchText.getText().toString();
                if (App.getNetState()) {
                    getGoodsList(input);
                } else {
                    showToast("??");
                }
            }
        });
        search_result_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxBus.getDefault().send(new Event.SelectFinish(selectedGoodsEntityMap));
                SearchMoveGoodActivity.this.finish();
            }
        });

        search_result_listview = (LinearLayout) findViewById(R.id.search_result_listview);

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

        compositeSubscription.add(RxTextView.textChangeEvents((EditText) findViewById(R.id.search_edittext1))
                .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()) {
                            getGoodsList(input);

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

                    }
                })

        );

    }

    private void getGoodsList(String input) {

        if (TextUtils.isEmpty(input)) {
            return;
        }
        Request request = new Request.Builder().url(HttpUrl.QUERY_MOVE_GOODS)
                .post(new FormEncodingBuilder().add("warehousecode", warehousecode).add("goodsname", input)
                        .add("offsetApp", "1").add("limitApp", "100").build())
                .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
                .tag(System.currentTimeMillis()).build();

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

                    }

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

                    @Override
                    public void onNext(InventoryList inventoryList) {
                        mList.clear();
                        int size = inventoryList.getMessage().size();
                        search_result_listview.removeAllViews();
                        mList.addAll(inventoryList.getMessage());

                        if (mList != null && mList.size() > 0) {
                            LayoutInflater inflater = LayoutInflater.from(SearchMoveGoodActivity.this);
                            int index = 0;
                            for (GoodsMoveDetail.NormalGoodsEntity entity : mList) {
                                View view = inflater.inflate(R.layout.search_goods_move_detail_item, null);
                                SearchGoodsViewItemHolder holder = new SearchGoodsViewItemHolder(view);
                                holder.bind(entity, index);
                                search_result_listview.addView(view);

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

                                index++;
                            }

                        }
                    }
                }));
    }

    public class SearchGoodsViewItemHolder extends ViewHolderBind<GoodsMoveDetail.NormalGoodsEntity> {
        SimpleDraweeView draweeView;
        TextView nameTextView;
        TextView wnumTextView;
        TextView wUnitTextView;
        TextView wbignumTextView;
        TextView wBigunitTextView;
        NumView bigNumView;
        NumView numView;
        TextView bigUnit;
        TextView unit;
        TextView status;
        TextView label01;
        TextView label02;

        LinearLayout layout;
        GoodsMoveDetail.NormalGoodsEntity entity;

        public SearchGoodsViewItemHolder(View view) {
            super(view);
            draweeView = (SimpleDraweeView) view.findViewById(R.id.goods_move_item_icon);
            nameTextView = (TextView) view.findViewById(R.id.goods_move_item_name);
            label01 = (TextView) view.findViewById(R.id.label01);
            label02 = (TextView) view.findViewById(R.id.label02);
            wnumTextView = (TextView) view.findViewById(R.id.goods_move_item_wnum);
            wbignumTextView = (TextView) view.findViewById(R.id.goods_move_item_wbignum);
            wUnitTextView = (TextView) view.findViewById(R.id.goods_move_item_wunit);
            wBigunitTextView = (TextView) view.findViewById(R.id.goods_move_item_wbigunit);
            bigNumView = (NumView) view.findViewById(R.id.goods_move_item_big_numview);
            numView = (NumView) view.findViewById(R.id.goods_move_item_numview);
            bigUnit = (TextView) view.findViewById(R.id.goods_move_item_big_unit);
            unit = (TextView) view.findViewById(R.id.goods_move_item_unit);
            status = (TextView) view.findViewById(R.id.goods_move_item_status);
            layout = (LinearLayout) view.findViewById(R.id.goods_move_item_num_layout);
        }

        @Override
        public void bind(GoodsMoveDetail.NormalGoodsEntity data, int pos) {

            this.entity = data;
            if (!TextUtils.isEmpty(data.getImg())) {
                draweeView.setImageURI(Uri.parse(data.getImg()));
            } else {
                draweeView.setImageResource(R.mipmap.goods);
            }

            if ("1".equals(flag)) {
                label01.setText("");
            } else {
                label01.setText("");
            }
            label02.setText("");
            nameTextView.setText(data.getGoodsname() + " 1*" + data.getChangeunit());
            wnumTextView.setText("" + data.getNowinventorynum());
            wbignumTextView.setText("" + data.getNowinventorybignum());
            wUnitTextView.setText(data.getUnit());
            wBigunitTextView.setText(data.getBigunit());
            bigUnit.setText(data.getBigunit());
            unit.setText(data.getUnit());

            if (selectedGoodsEntityMap != null && selectedGoodsEntityMap.containsKey(data.getGoodscode())) {
                bigNumView.setNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceBigNum());
                numView.setNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceNum());
                data.setChoiceNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceNum());
                data.setChoiceBigNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceBigNum());
            }
            TextWatcher tw02 = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    int num = entity.getChoiceBigNum();
                    try {
                        num = Integer.parseInt(charSequence.toString());
                    } catch (Exception e) {
                        num = 0;
                    }
                    entity.setChoiceBigNum(num);

                    selectedGoodsEntityMap.put(entity.getGoodscode(), entity);
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            };

            TextWatcher tw01 = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    int num = entity.getChoiceNum();
                    int bigNum = entity.getChoiceBigNum();
                    try {
                        num = Integer.parseInt(charSequence.toString());
                    } catch (Exception e) {
                        num = 0;
                    }
                    if (num >= entity.getChangeunit()) {
                        if (entity.getChangeunit() == 0) {
                            showMess();
                            return;
                        } else {
                            bigNum = entity.getChoiceBigNum() + num / entity.getChangeunit();
                        }
                        entity.setChoiceBigNum(bigNum);
                        if (entity.getChangeunit() == 0) {
                            showMess();
                            return;
                        } else {
                            num = num % entity.getChangeunit();
                        }

                        numView.setNum(num);
                        bigNumView.setNum(bigNum);
                    }
                    entity.setChoiceNum(num);
                    selectedGoodsEntityMap.put(entity.getGoodscode(), entity);
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            };
            numView.addTextWatcher(tw01);
            bigNumView.addTextWatcher(tw02);

        }
    }

    public void showMess() {
        //    AlertDialog.Builder?AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //    Title
        //builder.setIcon(R.drawable.ic_launcher);
        //    Title
        // builder.setTitle("");
        //    Content??
        builder.setMessage("?????0??!");
        //    PositiveButton

        //?
        builder.setNegativeButton("?", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //             Toast.makeText(mContext, "?.." , Toast.LENGTH_SHORT).show();
            }
        });
        //?
        builder.show();

    }

    public static class Event {
        public static class SelectFinish {
            public Map<String, GoodsMoveDetail.NormalGoodsEntity> selectMap;

            public SelectFinish(Map<String, GoodsMoveDetail.NormalGoodsEntity> selectMap) {
                this.selectMap = selectMap;
            }

            public Map<String, GoodsMoveDetail.NormalGoodsEntity> getSelectMap() {
                return selectMap;
            }
        }
    }

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