每当我点击按钮时,它给我的最后一个值结果不是最新的

时间:2018-01-07 05:20:00

标签: java android

每当我执行数据函数时,它都会存储正确的QUERY值,但是当我得到JSON时。它给了我最后一个值的结果,而不是给我新值的结果。功能数据或异步功能有问题。

我没有给出错误日志的错误.QUERY字符串保存正确的值,但结果是最后一个字符串。

public class MainActivity extends AppCompatActivity{
        public static String QUERY = null;
        public static String DATA = null;
        SpeechRecognizer speechRecognizer;
        Intent speechIntent;
        TextView textView;
        Button button;
        TextView textView1;

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate (savedInstanceState);
            setContentView (R.layout.activity_main);
            textView = (TextView) findViewById (R.id.text);
            textView1 = (TextView) findViewById (R.id.text1);

            requestPermissions (new String[]{Manifest.permission.INTERNET, Manifest.permission.RECORD_AUDIO}, 10);

            speechRecognizer = SpeechRecognizer.createSpeechRecognizer (this);
            speechRecognizer.setRecognitionListener (new RecognitionListener () {
                @Override
                public void onReadyForSpeech(Bundle bundle) {

                }

                @Override
                public void onBeginningOfSpeech() {

                }

                @Override
                public void onRmsChanged(float v) {

                }

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

                }

                @Override
                public void onEndOfSpeech() {

                }

                @Override
                public void onError(int i) {

                }

                @Override
                public void onResults(Bundle bundle) {
                    ArrayList<String> arrayList = bundle.getStringArrayList (SpeechRecognizer.RESULTS_RECOGNITION);
                    if(arrayList!=null){
                        textView.setText (arrayList.get (0));
                        QUERY = arrayList.get (0);
                    }else {
                        Toast.makeText (MainActivity.this, "Array List is null", Toast.LENGTH_SHORT).show ();
                    }
                }

                @Override
                public void onPartialResults(Bundle bundle) {

                }

                @Override
                public void onEvent(int i, Bundle bundle) {

                }
            });

            speechIntent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            speechIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            speechIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault ());
        }

        public void start(View v) {
            speechRecognizer.startListening (speechIntent);
        }

        public void data(View v){
            Toast.makeText (this, QUERY, Toast.LENGTH_SHORT).show ();
            Async async = new Async ();
            async.execute ();
            if(DATA!=null){
                textView1.setText (DATA);
            }
        } }

    class Async extends AsyncTask<Void, Void, Void>{

        String line = "";
        String data = "";

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                data=null;
                Log.e("Query in url", MainActivity.QUERY);
                URL url = new URL ("https://api.dialogflow.com/v1/query?v=20150910&contexts=[]&lang=en&query="
    + MainActivity.QUERY +"&sessionId=bee67580-d05c-47f6-8d64-a6218c3913e1");
                URLConnection httpURLConnection = url.openConnection ();
                httpURLConnection.setRequestProperty ("Authorization", "Bearer 
            CONFIDENTIAL KEY");
                InputStream inputStream = httpURLConnection.getInputStream ();
                BufferedReader bufferedReader = new BufferedReader (new 
                 InputStreamReader (inputStream));
                while ((line = bufferedReader.readLine ()) != null) {
                    data += line;
                }
            } catch (MalformedURLException e) {
                Log.i ("PROBLEM", "URL");
            } catch (IOException e) {
                Log.i ("PROBLEM", "IOEXCEPTIONe");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            MainActivity.DATA = data;
            super.onPostExecute (aVoid);
        }  }

2 个答案:

答案 0 :(得分:1)

问题是您是否正在调用AsyncTask并且在访问Variable内正在修改的AsynCtask之后立即调出。{/ p>

 Async async = new Async ();
        async.execute ();
        if(DATA!=null){
            textView1.setText (DATA);
        }

此处async将在后台线程上执行,但主线程继续,因此每次都会设置最后DATA值。

<强>解决方案

您最好将setText()代码移至onPostExecute()onPostExecute()  在主线程上运行,因此您可以轻松访问其中的Ui元素。

 @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute (aVoid);
        MainActivity.DATA = data;
        if(DATA!=null){
            textView1.setText (DATA);
        }
    }

答案 1 :(得分:0)

您正在异步完成执行之前设置文本。你在打电话

async.execute (); 
if(DATA!=null){ textView1.setText (DATA);

async.execute马上返回,因此DATA仍然具有旧值。 您需要做的是在onPostExecute函数中设置textView文本。