Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20646

AutoCompleteText in Fragments

I'm trying to create a AutoCompleteText in Fragments, I've seen a lot of examples, and didn't work for me... I'm always getting the same error with the adapter. The thing is on my code does not appears any error, but at the time I launch my APP and click on the fragment it crashes.

My LlistaGenericaFragment.java looks like :

public class LlistaGenericaFragment extends Fragment {

String[] totselements;
String[] imatgeselements;

public LlistaGenericaFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.llista_generica_fragment, container, false);
    return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    totselements = getResources().getStringArray(R.array.tots);
   imatgeselements = getResources().getStringArray(R.array.imagenestots);
    // Each row in the list stores country name, currency and flag
    List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

    for(int i=0;i<24;i++){
        HashMap<String, String> hm = new HashMap<String,String>();
        hm.put("txt", totselements[i]);
        hm.put("flag", (imatgeselements[i]) );

        aList.add(hm);
    }

    // Keys used in Hashmap
    String[] from = { "imatge","text"};

    // Ids of views in listview_layout
    int[] to = { R.id.imatgeelement,R.id.textelement};

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.llista_generica_fragment, from, to);

    // Getting a reference to CustomAutoCompleteTextView of activity_main.xml layout file
    CustomAutoCompleteTextView autoComplete = ( CustomAutoCompleteTextView) getActivity().findViewById(R.id.autocomplete);


    /** Defining an itemclick event listener for the autocompletetextview */
    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
            /** Each item in the adapter is a HashMap object.
             *  So this statement creates the currently clicked hashmap object
             * */
            HashMap<String, String> hm = (HashMap<String, String>) arg0.getAdapter().getItem(position); // UNCHECKED CAST ??????
     }
    };
 /** Setting the adapter to the listView */
    autoComplete.setAdapter(adapter);
}

Also I've created a class to AutoCompleteTextView, and it looks like :

public class CustomAutoCompleteTextView extends AutoCompleteTextView {

public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

/** Returns the country name corresponding to the selected item */
@Override
protected CharSequence convertSelectionToString(Object selectedItem) {
    /** Each item in the autocompetetextview suggestion list is a hashmap object */
    HashMap<String, String> hm = (HashMap<String, String>) selectedItem; // <-- UNCHEKED CAST ????????
    return hm.get("txt");
}

The error that I'm getting on LogCat is this :

02-01 17:12:13.229    5317-5317/joancolmenero.taulaperiodica.com.taulaperiodicaapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: joancolmenero.taulaperiodica.com.taulaperiodicaapp, PID: 5317
java.lang.NullPointerException
        at joancolmenero.taulaperiodica.com.taulaperiodicaapp.LlistaGenericaFragment.onCreate(LlistaGenericaFragment.java:100)
        at android.app.Fragment.performCreate(Fragment.java:1678)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:859)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
        at android.app.BackStackRecord.run(BackStackRecord.java:684)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
        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:5102)
        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:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)

Where at joancolmenero.taulaperiodica.com.taulaperiodicaapp.LlistaGenericaFragment.onCreate(LlistaGenericaFragment.java:100) is pointing autoComplete.setAdapter(adapter);.

When I changed getActivity() for getView() it does not crash but it says :

02-01 17:51:49.118  10048-11634/joancolmenero.taulaperiodica.com.taulaperiodicaapp W/Filter﹕ An exception occured during performFiltering()!
java.lang.NullPointerException
        at android.widget.SimpleAdapter$SimpleFilter.performFiltering(SimpleAdapter.java:354)
        at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.os.HandlerThread.run(HandlerThread.java:61)

Hope you can help me.

Upvotes: 0

Views: 190

Answers (1)

Blackbelt
Blackbelt

Reputation: 157467

if the AutoCompleteTextView is part of the layout that you returned in onCreateView, calling getActivity().findViewById insinde onCreate of your Fragment subclass, will return a null object, because the fragment is not yet attached to the Activity's view hierarchy. The easiest fix, in your case is to move your logic inside onActivityCreated, which is called after onCreateView, and use getView().findViewById to look for the Views that belong to the layout you returned in onCreateView

Upvotes: 4

Related Questions