片段中的自动完成文本

时间:2015-02-01 16:21:03

标签: java android android-fragments autocompletetextview

我正在尝试在Fragments中创建一个AutoCompleteText,我已经看过很多例子,并且对我不起作用......我总是和adapter得到同样的错误。事情是我的代码没有出现任何错误,但在我启动我的APP并点击它崩溃的片段。

我的LlistaGenericaFragment.java看起来像:

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);
}

此外,我已经为AutoCompleteTextView创建了一个类,它看起来像:

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");
}

我在LogCat上遇到的错误是:

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)

at joancolmenero.taulaperiodica.com.taulaperiodicaapp.LlistaGenericaFragment.onCreate(LlistaGenericaFragment.java:100)指向autoComplete.setAdapter(adapter);的位置。

当我为getView()更改getActivity()时,它不会崩溃,但它会说:

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)

希望你能帮助我。

1 个答案:

答案 0 :(得分:4)

如果AutoCompleteTextView是您在onCreateView中返回的布局的一部分,调用getActivity().findViewById insinde onCreate of Fragment子类,将返回一个null对象,因为该片段还没有附加到Activity的视图层次结构。在您的情况下,最简单的修复方法是将您的逻辑移到onActivityCreated之后调用onCreateView,并使用getView().findViewById查找属于您在{返回的布局的视图{1}}