Android onitemselectedlistener在片段中抛出nullpointer异常

时间:2015-07-21 08:56:20

标签: android spinner onitemselectedlistener

我在片段视图中尝试了很多方法来成功使用onitemselectedlistener,但是不断得到一个致命的异常java.lang.NullPointerException并且它总是指向用于为微调器设置onitemselectedlistener方法的代码中的同一行。

android studio logcat错误输出是:

  

07-21 13:55:06.544 17277-17277 / com.vaibhavtech.indoreveg   E / AndroidRuntime:FATAL EXCEPTION:主要流程:   com.vaibhavtech.indoreveg,PID:17277
  显示java.lang.NullPointerException       在com.vaibhavtech.indoreveg.activity.VegetablesFragment.onCreateView(VegetablesFragment.java:91)       在android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)       在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)       在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)       在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)       在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)       在android.support.v4.app.FragmentManagerImpl $ 1.run(FragmentManager.java:456)       在android.os.Handler.handleCallback(Handler.java:808)       在android.os.Handler.dispatchMessage(Handler.java:103)       在android.os.Looper.loop(Looper.java:193)       在android.app.ActivityThread.main(ActivityThread.java:5395)       at java.lang.reflect.Method.invokeNative(Native Method)       在java.lang.reflect.Method.invoke(Method.java:515)       在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:837)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)at   dalvik.system.NativeStart.main(原生方法)

片段类:

public class VegetablesFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private Spinner spinnerPacking;
// array list for spinner adapter
private ArrayList<Packing> spinnerList;
// Product json url
private static final String url = "http://www.indoreveg.com/androidapi1/products.php?category=vegetable";
private ProgressDialog pDialog;
private List<Products> productsList = new ArrayList<Products>();
private ListView listView;
private CustomListAdapter adapter;
public VegetablesFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View layout = inflater.inflate(R.layout.fragment_vegetables, container, false);
    listView = (ListView) layout.findViewById(R.id.list);
    spinnerPacking = (Spinner) layout.findViewById(R.id.packingList);
    spinnerList = new ArrayList<Packing>();
    /* spinner item select listener */
    spinnerPacking.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            // TODO Auto-generated method stub
            String msupplier=spinnerPacking.getSelectedItem().toString();
            Log.e("Selected item : ",msupplier);
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });
    adapter = new CustomListAdapter(getActivity(), productsList);
    listView.setAdapter(adapter);
    pDialog = new ProgressDialog(getActivity());
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();
    populateSpinner();
    // Creating volley request obj
    JsonArrayRequest productsReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            Log.d(TAG, response.toString());
            hidePDialog();
            // Parsing json
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject obj = response.getJSONObject(i);
                    Products products = new Products();
                    products.setTitle(obj.getString("name"));
                    products.setThumbnailUrl(obj.getString("image"));
                    products.setOurPrice(obj.getString("our_price"));
                    products.setMarketPrice(obj.getString("market_price"));
                    // Packing is json array
                    JSONArray packingArry = obj.getJSONArray("packing");
                    ArrayList<String> packings = new ArrayList<String>();
                    for (int j = 0; j < packingArry.length(); j++) {
                        packings.add((String) packingArry.get(j));
                    }
                    products.setPacking(packings);
                    // adding products to products array
                    productsList.add(products);
                    JSONArray mpackingArray = obj.getJSONArray("packing");
                    for (int m = 0; m < mpackingArray.length(); m++) {
                    JSONObject packObj = (JSONObject) mpackingArray.get(m);
                    Packing pack = new Packing(packObj.getString("pack"));
                        spinnerList.add(pack);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            // notifying list adapter about data changes
            // so that it renders the list view with updated data
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();
        }
    });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(productsReq);
    return layout;
}
@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}
private void populateSpinner() {
    List<String> lables = new ArrayList<String>();

    for (int i = 0; i < spinnerList.size(); i++) {
        lables.add(spinnerList.get(i).getPackingnm());
    }
    // Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button  spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerPacking.setAdapter(spinnerAdapter);
}
}

请帮忙。感谢

fragment_vegetable.xml

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
       xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".MainActivity" >
    <ListView
       android:id="@+id/list"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:divider="@color/list_divider"
       android:dividerHeight="1dp"
       android:listSelector="@drawable/list_row_selector" />
    </RelativeLayout>

适配器GetView方法:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) convertView = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView) convertView.findViewById(R.id.title);
if (imageLoader == null)
    imageLoader = AppController.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
    TextView ourPrice = (TextView) convertView.findViewById(R.id.ourPrice);
    TextView packing = (TextView) convertView.findViewById(R.id.packing);
    TextView marketPrice = (TextView) convertView.findViewById(R.id.marketPrice);
    Spinner packingSpinner = (Spinner) convertView.findViewById(R.id.packingList);
    packingSpinner.setOnItemSelectedListener(this);
    // getting products data for the row
    Products p = productsItems.get(position);
    // thumbnail image
    thumbNail.setImageUrl(p.getThumbnailUrl(), imageLoader);
    // title
    title.setText(p.getTitle());
    // ourPrice
    ourPrice.setText("Our Price: " + String.valueOf(p.getOurPrice()));
    // packing
    List<String> lables = new ArrayList<String>();
    for (int i = 0; i < p.getPacking().size(); i++) {
        lables.add(p.getPacking().get(i));
    }
    // Creating adapter for spinner
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, lables);
    // Drop down layout style - list view with radio button
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // attaching data adapter to spinner
    packingSpinner.setAdapter(spinnerAdapter);
    String packingStr = "";
    for (String str : p.getPacking()) {
        packingStr += str + ", ";
    }
    packingStr = packingStr.length() > 0 ? packingStr.substring(0,
            packingStr.length() - 2) : packingStr;
    packing.setText(packingStr);
    // marketPrice
    marketPrice.setText("Market Price: " + String.valueOf(p.getMarketPrice()));
    marketPrice.setPaintFlags(marketPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    return convertView;
}

1 个答案:

答案 0 :(得分:1)

确保您的布局“fragment_vegetables”包含ID为“R.id.packingList”的Spinner,否则layout.findViewById(R.id.packingList)将返回null,您将在行spinnerPacking.setOnItemSelectedListener上获得NullPointerException。