有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我怎样才能延迟点击按钮的动作,这样我就可以存储一个JSON数组了?

以下代码中的所有内容都可以正常工作,除非用户单击其中一个按钮进行快速操作,而没有时间连接数据库并获取json值

我尝试环绕try-catch块,并尝试检查create-if语句,该语句检查第一个字符=='{',因为这始终是给定json字符串中的第一个字符

这是一节课

package com.example.allrateform;

import 安卓.app.AlertDialog;
import 安卓.content.Intent;
import 安卓.os.AsyncTask;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static com.example.allrateform.MainActivity.UsernameText;

public class Categories extends AppCompatActivity {

    public static String Category;
    public static char[] TextList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categories);

        //CREATING ALL INSTANCES
        final Button ComputersButton=(Button)findViewById(R.id.ComputersButton);
        final Button HobbiesButton=(Button)findViewById(R.id.HobbiesButton);
        final Button BooksButton=(Button)findViewById(R.id.BooksButton);
        final Button TourismButton=(Button)findViewById(R.id.TourismButton);
        final Button GamesButton=(Button)findViewById(R.id.GamesButton);
        final Button FantasyButton=(Button)findViewById(R.id.FantasyButton);
        final Button SportsButton=(Button)findViewById(R.id.SportsButton);

        final TextView TextViewUsername=(TextView)findViewById(R.id.TextViewUsername);
        TextViewUsername.setText(UsernameText);

        getJSON();

        ComputersButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Computers";
                openQuestion();
            }
        });
        HobbiesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Hobbies";
                openQuestion();
            }
        });
        BooksButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Books";
                openQuestion();
            }
        });
        TourismButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Tourism";
                openQuestion();
            }
        });
        GamesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Games";
                openQuestion();
            }
        });
        FantasyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Fantasy";
                openQuestion();
            }
        });
        SportsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Category="Sports";
                openQuestion();
            }
        });
    }

    public void openQuestion(){
        try {
            Intent intent = new Intent(this, Question.class);
            startActivity(intent);
        }catch(Exception ex) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Categories.this);
            builder.setMessage("Try again later")
                    .setNegativeButton("Ok", null)
                    .create()
                    .show();
        }
    }

    public void getJSON() {
        new Categories.BackgroundTask().execute();
    }

    class BackgroundTask extends AsyncTask<Void, Void, String> {

        String json_url;
        String JSON_STRING;

        @Override
        protected void onPreExecute() {
            json_url = "https://allratejohnnycode.000webhostapp.com/List.php";
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();

                while ((JSON_STRING = bufferedReader.readLine()) != null) {
                    stringBuilder.append(JSON_STRING + "\n");
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {
            TextList=result.toCharArray();
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我想提供两种不同的方法

    1st就是你想要的,不过我推荐2nd一个:


    单击按钮会触发循环进度加载程序

    您可以维护一个boolean来表示JSON是否已加载, 因此,当用户单击按钮时,首先检查布尔状态。如果加载-继续创建意图。Else——提供一个循环进度加载器,等待JSON加载。(如果您需要帮助,请给我留言,我将为您提供一个代码示例)


    使用Android View Model架构

    这是一个更“繁重”的解决方案,但在研究Android Architecture Components之后,你会发现这是最干净的&;在后台加载数据的有效方法,同时通常保持数据和UI之间的分离。非常有用的知识



    第一种方法——实施示例

    第1步:添加一个进度条,开头有visibility="gone"。随心所欲地设计

    第二步:试试这个代码。它是有效的(经过测试)

    public class Categories extends AppCompatActivity {
    
        public static String Category;
        public static char[] TextList;
        //4 new variables
        private static volatile boolean isJsonLoaded, isButtonClicked;
        private ProgressBar progressBar;
        private final Object locker = 0; //for concurrent modification & synchronization
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_categories);
    
            TextView TextViewUsername = findViewById(R.id.TextViewUsername);
            TextViewUsername.setText(UsernameText);
    
            this.progressBar = findViewById(R.id.progressBar);
            isJsonLoaded = false;
            isButtonClicked = false;
    
            initButtons();
            getJSON();
        }
    
        //Slightly beautified your code
        private void initButtons() {
            //Temp array of buttons
            ArrayList<Button> buttons = new ArrayList<>(Arrays.asList(
                    (Button) findViewById(R.id.ComputersButton),
                    (Button) findViewById(R.id.HobbiesButton),
                    (Button) findViewById(R.id.BooksButton),
                    (Button) findViewById(R.id.TourismButton),
                    (Button) findViewById(R.id.GamesButton),
                    (Button) findViewById(R.id.FantasyButton),
                    (Button) findViewById(R.id.SportsButton)
            ));
    
            //Mutual 'onClick' listener for all of them
            View.OnClickListener buttonClick = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Get the button's name
                    String buttonName = getResources().getResourceEntryName(v.getId());
                    //Eliminate the "...Button" part
                    Category = buttonName.substring(0, buttonName.indexOf("Button"));
                    handleButtonClick();
                }
            };
    
            for (Button button : buttons)
                button.setOnClickListener(buttonClick);
        }
    
        public void handleButtonClick() {
            synchronized (locker) {
                if (isJsonLoaded) openQuestion();
                else {
                    isButtonClicked = true;
    
                    //Show the progress bar
                    progressBar.setVisibility(View.VISIBLE);
                }
            }
        }
    
        void openQuestion() {
            Intent intent = new Intent(this, Question.class);
            startActivity(intent);
        }
    
        public void getJSON() {
            new Categories.BackgroundTask().execute();
        }
    
        class BackgroundTask extends AsyncTask<Void, Void, String> {
    
            String json_url;
            String JSON_STRING;
    
            @Override
            protected void onPreExecute() {
                json_url = "https://allratejohnnycode.000webhostapp.com/List.php";
            }
    
            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(json_url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
    
                    while ((JSON_STRING = bufferedReader.readLine()) != null) {
                        stringBuilder.append(JSON_STRING + "\n");
                    }
    
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
    
                    return stringBuilder.toString().trim();
    
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                return null;
            }
    
            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);
            }
    
            @Override
            protected void onPostExecute(String result) {
                TextList = result.toCharArray();
                isJsonLoaded = true;
                synchronized (locker) {
                    if (isButtonClicked)
                        openQuestion();
                }
    
                //Hide the progress bar
                progressBar.setVisibility(View.GONE);
            }
        }
    }