Question

My fragment needs to create a spinner to control what gets displayed in the webview. There is also a progress bar that shows the loading from the spinner selection. Everything works well in a standard activity but moving it to a fragment is proving problematic. I will post the fragment and error.

Thanks!

the error occurs at this line:

spLoadFrom.setAdapter(spinnerArrayAdapter);

Here is the code:

package com.example.fragmenttest.app;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;

public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
ProgressBar pd = null;
public static final String PREFS_NAME2 = "SearchFile";
Spinner spLoadFrom;
WebView wv;

private LinearLayout container;
private Button nextButton, closeButton;
private EditText findBox;

private ArrayAdapter<CharSequence> spinnerArrayAdapter;

String name[] = { "mystuff" };
String displayName[] = {
        "mystuff" };

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment BlankFragment.
 */
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
    BlankFragment fragment = new BlankFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
public BlankFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

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

    wv = (WebView) container.findViewById(R.id.webview);
    pd = (ProgressBar) container.findViewById(R.id.pBar);
    spLoadFrom = (Spinner) container.findViewById(R.id.Spinner02);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, displayName);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spLoadFrom.setAdapter(spinnerArrayAdapter);

    SpinnerListener spListener = new SpinnerListener();

    spLoadFrom.setOnItemSelectedListener(spListener);
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.atcsectionweb2, container, false);
}

public class SpinnerListener implements AdapterView.OnItemSelectedListener {
    public SpinnerListener() {
    }

    public void onItemSelected(AdapterView<?> arg0, View arg1,
                               final int position, long arg2) {

        WebView wv = (WebView) getView().findViewById(R.id.webview);

        wv.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100
                        && pd.getVisibility() == ProgressBar.GONE) {
                    pd.setVisibility(ProgressBar.VISIBLE);
                }
                pd.setProgress(progress);
                if (progress == 100) {
                    pd.setVisibility(ProgressBar.GONE);
                }
            }
        });

        wv.getSettings().setLoadWithOverviewMode(true);
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setBuiltInZoomControls(true);
        wv.getSettings().setSupportZoom(true);
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        wv.loadUrl("file:///android_asset/" + name[position]);

    }

    public void onNothingSelected(AdapterView<?> arg0) {

    }
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

}

And the error:

04-23 19:17:10.621    9679-9679/com.example.fragmenttest.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.fragmenttest.app, PID: 9679
java.lang.NullPointerException
        at com.example.fragmenttest.app.BlankFragment.onCreateView(BlankFragment.java:243)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:614)
        at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
        at dalvik.system.NativeStart.main(Native Method)

Here is the XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ProgressBar
    android:id="@+id/pBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Spinner
    android:id="@+id/Spinner02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/pBar" />

<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/Spinner02" />

<LinearLayout
    android:id="@+id/layoutId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/webview"
    android:orientation="horizontal" >

</LinearLayout>

</RelativeLayout>
Was it helpful?

Solution

You have to use your inflated fragment layout:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.atcsectionweb2, container, false);

    wv = (WebView) v.findViewById(R.id.webview);
    pd = (ProgressBar) v.findViewById(R.id.pBar);
    spLoadFrom = (Spinner) v.findViewById(R.id.Spinner02);
    (...)

    return v;
 }

OTHER TIPS

I got the same issue while setting adapter to spinner in fragment.... and solved it by....

if (getActivity() != null) { spLoadFrom.setAdapter(spinnerArrayAdapter); }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top