public class

DocumentFragment

extends Fragment

 java.lang.Object

androidx.fragment.app.Fragment

↳androidx.appsearch.debugview.view.DocumentFragment

Gradle dependencies

compile group: 'androidx.appsearch', name: 'appsearch-debug-view', version: '1.1.0-alpha05'

  • groupId: androidx.appsearch
  • artifactId: appsearch-debug-view
  • version: 1.1.0-alpha05

Artifact androidx.appsearch:appsearch-debug-view:1.1.0-alpha05 it located at Google repository (https://maven.google.com/)

Overview

A fragment for displaying a GenericDocument object.

Summary

Fields
from FragmentmPreviousWho
Constructors
publicDocumentFragment()

Methods
public static DocumentFragmentcreateDocumentFragment(java.lang.String namespace, java.lang.String id)

Factory for creating a DocumentFragment instance.

protected voiddisplayDocument(DebugAppSearchManager debugAppSearchManager)

public voidonCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment.

public ViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view.

public voidonViewCreated(View view, Bundle savedInstanceState)

Called immediately after Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view.

from Fragmentdump, equals, getActivity, getAllowEnterTransitionOverlap, getAllowReturnTransitionOverlap, getArguments, getChildFragmentManager, getContext, getDefaultViewModelCreationExtras, getDefaultViewModelProviderFactory, getEnterTransition, getExitTransition, getFragmentManager, getHost, getId, getLayoutInflater, getLayoutInflater, getLifecycle, getLoaderManager, getParentFragment, getParentFragmentManager, getReenterTransition, getResources, getRetainInstance, getReturnTransition, getSavedStateRegistry, getSharedElementEnterTransition, getSharedElementReturnTransition, getString, getString, getTag, getTargetFragment, getTargetRequestCode, getText, getUserVisibleHint, getView, getViewLifecycleOwner, getViewLifecycleOwnerLiveData, getViewModelStore, hashCode, hasOptionsMenu, instantiate, instantiate, isAdded, isDetached, isHidden, isInLayout, isMenuVisible, isRemoving, isResumed, isStateSaved, isVisible, onActivityCreated, onActivityResult, onAttach, onAttach, onAttachFragment, onConfigurationChanged, onContextItemSelected, onCreateAnimation, onCreateAnimator, onCreateContextMenu, onCreateOptionsMenu, onDestroy, onDestroyOptionsMenu, onDestroyView, onDetach, onGetLayoutInflater, onHiddenChanged, onInflate, onInflate, onLowMemory, onMultiWindowModeChanged, onOptionsItemSelected, onOptionsMenuClosed, onPause, onPictureInPictureModeChanged, onPrepareOptionsMenu, onPrimaryNavigationFragmentChanged, onRequestPermissionsResult, onResume, onSaveInstanceState, onStart, onStop, onViewStateRestored, postponeEnterTransition, postponeEnterTransition, registerForActivityResult, registerForActivityResult, registerForContextMenu, requestPermissions, requireActivity, requireArguments, requireContext, requireFragmentManager, requireHost, requireParentFragment, requireView, setAllowEnterTransitionOverlap, setAllowReturnTransitionOverlap, setArguments, setEnterSharedElementCallback, setEnterTransition, setExitSharedElementCallback, setExitTransition, setHasOptionsMenu, setInitialSavedState, setMenuVisibility, setReenterTransition, setRetainInstance, setReturnTransition, setSharedElementEnterTransition, setSharedElementReturnTransition, setTargetFragment, setUserVisibleHint, shouldShowRequestPermissionRationale, startActivity, startActivity, startActivityForResult, startActivityForResult, startIntentSenderForResult, startPostponedEnterTransition, toString, unregisterForContextMenu
from java.lang.Objectclone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructors

public DocumentFragment()

Methods

public static DocumentFragment createDocumentFragment(java.lang.String namespace, java.lang.String id)

Factory for creating a DocumentFragment instance.

public void onCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after Fragment.onAttach(Activity) and before Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle).

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a LifecycleObserver on the activity's Lifecycle, removing it when it receives the callback.

Any restored child fragments will be created before the base Fragment.onCreate method returns.

Parameters:

savedInstanceState: If the fragment is being re-created from a previous saved state, this is the state.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between Fragment.onCreate(Bundle) and Fragment.onViewCreated(View, Bundle).

A default View can be returned by calling Fragment.Fragment(int) in your constructor. Otherwise, this method returns null.

It is recommended to only inflate the layout in this method and move logic that operates on the returned View to Fragment.onViewCreated(View, Bundle).

If you return a View from here, you will later be called in Fragment.onDestroyView() when the view is being released.

Parameters:

inflater: The LayoutInflater object that can be used to inflate any views in the fragment,
container: If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.
savedInstanceState: If non-null, this fragment is being re-constructed from a previous saved state as given here.

Returns:

Return the View for the fragment's UI, or null.

public void onViewCreated(View view, Bundle savedInstanceState)

Called immediately after Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.

Parameters:

view: The View returned by Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle).
savedInstanceState: If non-null, this fragment is being re-constructed from a previous saved state as given here.

protected void displayDocument(DebugAppSearchManager debugAppSearchManager)

Source

/*
 * Copyright 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.appsearch.debugview.view;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.appsearch.app.GenericDocument;
import androidx.appsearch.debugview.DebugAppSearchManager;
import androidx.appsearch.debugview.R;
import androidx.appsearch.debugview.model.DocumentModel;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;

/**
 * A fragment for displaying a {@link GenericDocument} object.
 *
 * @exportToFramework:hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class DocumentFragment extends Fragment {
    private static final String TAG = "AppSearchDocumentFrag";
    private static final String ARG_NAMESPACE = "document_namespace";
    private static final String ARG_ID = "document_id";

    private String mNamespace;
    private String mId;
    private ListeningExecutorService mExecutor;
    private ListenableFuture<DebugAppSearchManager> mDebugAppSearchManager;
    private DocumentModel mDocumentModel;

    /**
     * Factory for creating a {@link DocumentFragment} instance.
     */
    @NonNull
    public static DocumentFragment createDocumentFragment(
            @NonNull String namespace, @NonNull String id) {
        DocumentFragment documentFragment = new DocumentFragment();
        Bundle args = new Bundle();
        args.putString(ARG_NAMESPACE, namespace);
        args.putString(ARG_ID, id);
        documentFragment.setArguments(args);
        return documentFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mId = getArguments().getString(ARG_ID);
            mNamespace = getArguments().getString(ARG_NAMESPACE);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_document, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mExecutor = ((AppSearchDebugActivity) getActivity()).getBackgroundExecutor();
        mDebugAppSearchManager =
                ((AppSearchDebugActivity) getActivity()).getDebugAppSearchManager();

        Futures.addCallback(mDebugAppSearchManager,
                new FutureCallback<DebugAppSearchManager>() {
                    @Override
                    public void onSuccess(DebugAppSearchManager debugAppSearchManager) {
                        displayDocument(debugAppSearchManager);
                    }

                    @Override
                    public void onFailure(@NonNull Throwable t) {
                        Toast.makeText(getContext(),
                                "Failed to initialize AppSearch: " + t.getMessage(),
                                Toast.LENGTH_LONG).show();
                        Log.e(TAG,
                                "Failed to initialize AppSearch. Verify that the database name "
                                        + "has been provided in the intent with key: databaseName",
                                t);
                    }
                }, ContextCompat.getMainExecutor(getActivity()));
    }

    protected void displayDocument(@NonNull DebugAppSearchManager debugAppSearchManager) {
        mDocumentModel =
                new ViewModelProvider(this,
                        new DocumentModel.DocumentModelFactory(mExecutor, debugAppSearchManager)
                ).get(DocumentModel.class);

        mDocumentModel.getDocument(mNamespace, mId).observe(this, document -> {
            TextView documentView = getView().findViewById(R.id.document_string);
            documentView.setText(document.toString());
        });
    }
}