简体   繁体   中英

How do I hold the Async Task from executing before the user input is stored in a variable that is required by the Async Task

Following is the code to get the keyword from the user:

class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    private static String keywordToSearch = "";

    private static String keyword;

    public void Search(View view) {
        EditText nameTextBox = (EditText) view.findViewById(R.id.keyword);
        Editable editable = nameTextBox.getText();
        keyword = editable.toString();
    }

    private void searchKeyWord()
    {
        keywordToSearch = keyword;
    }

    public static String getKeyword()
    {
        return keywordToSearch;
    }
}

There is another class that implements Async Task and needs the keyword as its input to search the web.

But the application crashed, maybe because both the UI and the Async Thread executed simultaneously and that the Async task did not have the input led to the application crashing.

How can I hold the Async task from executing until the keyword is fetched and stored in a variable?

Subclasses of AsyncTask can have constructors with parameters. Obtain the input, use it to construct your AsyncTask , then execute it.

Try this :-

if(keyword!=null){
 //call your async task Class here 
 //ex:- new Hello.execute(); - Hello is your AsyncTask class
}

You can also pass your keyword inside the execute method as new Hello.execute(keyword);

单击按钮时调用异步类。

    EditText nameTextBox = (EditText) view.findViewById(R.id.keyword);

    nameTextBox.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s) {
            // call aynctask here after check 's' length like "s.toString().length() > 0" 
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count){}
    });

Here when edittext value changes then you get the value at after text changed listener method then you send that value in your asynctask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM