Кому передается значение возврата loadInBackground ()? - PullRequest
0 голосов
/ 09 апреля 2019

(извините, я не знаю, правильно ли я говорю по-английски, надеюсь, это правильно!) Метод loadInBackground () (в классе BookLoader) возвращает строковое значение, но кому?Я искал, кто тоже вызывает loadInBackground (), но никто этого не делает. Я тоже читаю официальную документацию, но без решений. Спасибо друзьям за советы.

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> {

public EditText mEditText;
public TextView mTextTitle, mTextAuthor;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mEditText = (EditText) findViewById(R.id.bookInput);
    mTextTitle = (TextView) findViewById(R.id.titleText);
    mTextAuthor = (TextView) findViewById(R.id.authorText);

    // to reconnect to the Loader if it already exists
    if(getSupportLoaderManager().getLoader(0)!=null){

        getSupportLoaderManager().initLoader(0,null,this);

    }

}

public void searchBooks(View view) {

    String queryString = mEditText.getText().toString();

    // nasconde la tastiera
    InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

    // Check the status of the network connection.
    ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected() && queryString.length()!=0) {

        mTextAuthor.setText("");
        mTextTitle.setText(R.string.loading);

        Bundle queryBundle = new Bundle();
        queryBundle.putString("queryString", queryString);

        getSupportLoaderManager().restartLoader(0, queryBundle,this);

    }

    else {

        if (queryString.length() == 0) {

            mTextAuthor.setText("");
            mTextTitle.setText("Please enter a search term");

        } else {

            mTextAuthor.setText("");
            mTextTitle.setText("Please check your network connection and try again.");

        }

    }

}

// Called when you instantiate your Loader.
@NonNull
@Override
public Loader<String> onCreateLoader(int i, @Nullable Bundle bundle) {

    return new BookLoader(this, bundle.getString("queryString"));

}


@Override
public void onLoadFinished(@NonNull Loader<String> loader, String s) {

    try {

        JSONObject jsonObject = new JSONObject(s);
        JSONArray itemsArray = jsonObject.getJSONArray("items");

        int i = 0;
        String title = null;
        String authors = null;

        while (i < itemsArray.length() || (authors == null && title == null)) {
            // Get the current item information.
            JSONObject book = itemsArray.getJSONObject(i);
            JSONObject volumeInfo = book.getJSONObject("volumeInfo");

            // Try to get the author and title from the current item,
            // catch if either field is empty and move on.
            try {

                title = volumeInfo.getString("title");
                authors = volumeInfo.getString("authors");
                Log.d("TITLE", volumeInfo.getString("title"));

            } catch (Exception e){

                e.printStackTrace();

            }

            // Move to the next item.
            i++;
        }

        // If both are found, display the result.
        if (title != null && authors != null){

            mTextTitle.setText(title);
            mTextAuthor.setText(authors);
            mEditText.setText("");

        } else {
            // If none are found, update the UI to show failed results.
            mTextTitle.setText("no results");
            mTextAuthor.setText("");

        }

    } catch (Exception e){
        // If onPostExecute does not receive a proper JSON string, update the UI to show failed results.
        mTextTitle.setText("no results");
        mTextAuthor.setText("");
        e.printStackTrace();
    }

}

// Cleans up any remaining resources.
@Override
public void onLoaderReset(@NonNull Loader<String> loader) {

}

}




public class BookLoader extends AsyncTaskLoader<String> {

String mQueryString;

public BookLoader(@NonNull Context context, String queryString) {

    super(context);
    mQueryString = queryString;

}

@Nullable
@Override
public String loadInBackground() {

    return NetworkUtils.getBookInfo(mQueryString);

}

@Override
protected void onStartLoading() {

    super.onStartLoading();

    forceLoad();

}

}

Я редактировал пост.

1 Ответ

1 голос
/ 09 апреля 2019

Как сказано в официальной документации:

onPostExecute (Result), вызывается в потоке пользовательского интерфейса после завершения фоновых вычислений.Результат фоновых вычислений передается на этот шаг в качестве параметра.

Ваше возвращаемое значение отправляется в onPostExecute ().

Я рекомендую вам глубже взглянуть на эта документация

...