当前位置: 首页 > 知识库问答 >
问题:

Android onitemselectedlistener在片段中引发nullpointer异常

司宏伯
2023-03-14

我尝试了很多方法在片段视图中成功实现了onitemselectedlistener,但不断地得到一个致命的java异常。它始终指向代码中的同一行,用于为spinner设置onitemselectedlistener方法。

android studio logcat错误输出为:

07-21 13:55:06.544 17277-17277/com。vaibhavtech。indoreveg E/AndroidRuntime﹕ 致命异常:主进程:com。vaibhavtech。indoreveg,PID:17277
爪哇。com上的lang.NullPointerException。vaibhavtech。indoreveg。活动蔬菜碎片。android上的onCreateView(VegetablesFragment.java:91)。支持v4.app。碎片android上的performCreateView(Fragment.java:1786)。支持v4.app。碎片管理。android上的moveToState(FragmentManager.java:953)。支持v4.app。碎片管理。android上的moveToState(FragmentManager.java:1136)。支持v4.app。回溯记录。在android上运行(backbackrecord.java:739)。支持v4.app。碎片管理。android上的ExependingActions(FragmentManager.java:1499)。支持v4.app。FragmentManagerImpl 1美元。在android上运行(FragmentManager.java:456)。操作系统。处理程序。android上的handleCallback(Handler.java:808)。操作系统。处理程序。android上的dispatchMessage(Handler.java:103)。操作系统。活套。android上的loop(Looper.java:193)。应用程序。活动线程。java上的main(ActivityThread.java:5395)。郎。反思。方法java上的InvokEnable(本机方法)。郎。反思。方法在com上调用(Method.java:515)。Android内部的操作系统。ZygoteInit$MethodandArgscaler。在com上运行(ZygoteInit.java:837)。Android内部的操作系统。合子岩。dalvik的main(ZygoteInit.java:653)。系统原生艺术。主(本机方法)

片段类:

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_蔬菜。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个答案

封瑞
2023-03-14

确保布局“fragment\u Vegetures”包含一个ID为“R.ID.packingList”的微调器,否则为布局。findViewById(R.id.packingList)返回null,您将在第行spinnerPacking上获得null点异常。setOnItemSelectedListener。

 类似资料:
  • 下面是我生成PDF的代码: 下面是我用来绘制多个字符串的代码: 此代码正常工作,但如果我将更改为,它将引发以下异常: 起初,我认为这是因为有些数据不存在,无法编写,但如果我不更新Voly,它就可以正常工作。然后我认为这是一个问题,当创建了一个新页面但流存在时,没有创建PDPageContentStream。 提前感谢您的帮助!

  • 有没有什么好的方法来引用用创建的片段?或者我应该如何从我的活动(准确地说是从选项菜单)中刷新查看页中的片段?

  • 问题内容: 当我尝试运行项目时,Tomcat返回异常。 有人可以帮助解决这个问题吗?配置类:https : //github.com/intrade/inventory/blob/master/src/main/java/com/springapp/mvc/InitApp/SecurityConfig.java 堆栈跟踪: 安全过滤器出现问题。项目链接:GitHub 问题答案: 该问题与SEC-2

  • 我正尝试在类的方法中使用(以支持拖放)。我想显示我拖动的文件的导入进度。然而,它并不起作用。我不明白问题是什么,或者是什么引起的。 例外情况:

  • 问题内容: 我已经声明了两个FXML文件,并为每一个控制器: rootlayoutcontroller 是控制器的一个 rootlayout.fxml 和 overviewcontroller 是控制器的一个 overview.fxml rootlayout具有带有文件打开项的菜单栏,而总览控制器具有Draw按钮。 我还有另一个叫做DataStructure的类。我想打开一个文件并将路径发送到Ov