【问题标题】:Null Pointer Exception in Custom Adapter自定义适配器中的空指针异常
【发布时间】:2013-09-25 10:10:20
【问题描述】:

我正在开发一个应用程序,但在自定义适配器中出现空指针异常。 我的自定义适配器代码如下-

        public class CustomCursorAdapter extends CursorAdapter {
SQLiteDatabase dh = DatabaseHelpereKOT.getInstance().getDb();
private LayoutInflater mInflater;
private Context mContext;
Cursor cursor, c;
boolean isMain;
View convertView;
ViewHolder holder;
private String item;
private String description;
private String name_NO;
private String description_NO;
private int category;
private double price;
private LayoutInflater inflater;
private View detailsLayout;
private AlertDialog detailsDialog;
private final String TAG = "RestaurantHome";
private Integer id;
MainScreen main_screen_obj;

public Handler addMenuItemHandler = new Handler() {

    @Override
    public void handleMessage(android.os.Message msg) {
        if (msg.what == 1) {
            System.out.println("inside handler");
            Toast.makeText(mContext, (String) msg.obj, Toast.LENGTH_SHORT)
                    .show();  
        }
    };

};

public CustomCursorAdapter(Context context, Cursor c, Boolean isMain) {
    super(context, c);
    mInflater = LayoutInflater.from(context);
    mContext = context;
    cursor = c;
    this.isMain = isMain;
    // restaurantHome = (RestaurantHome) context;
}

public CustomCursorAdapter(Context context, Cursor c) {
    super(context, c);
    mInflater = LayoutInflater.from(context);
    mContext = context;
    cursor = c;
}

@Override
public void bindView(View view, Context context, final Cursor cursor) {
    holder = (ViewHolder) view.getTag();

    holder.setTvTitle((TextView) view
            .findViewById(R.id.main_body_item_title));
    holder.setTvPrice((TextView) view
            .findViewById(R.id.main_body_item_title_price));

    holder.getTvPrice().setText(
            cursor.getString(cursor.getColumnIndex("Item_cost")) + ".00");

    holder.getTvTitle().setText(
            cursor.getString(cursor.getColumnIndex("name_NO")));
    holder.getTvDescription().setText(
            cursor.getString(cursor.getColumnIndex("description_NO")));
    int _id = cursor.getInt(cursor.getColumnIndex("_id"));
    view.setTag(R.id.main_body_item_title, _id);   
    // System.out.println("_id :"+_id);
    int type = cursor.getInt(cursor.getColumnIndex("item_type")); 
    if (type == 1) {
        //holder.getImType().setPadding(6, 0, 0, 0);
        holder.getImType().setBackgroundResource(R.drawable.non_veg);
    } else {  
        holder.getImType().setBackgroundResource(R.drawable.veg);
    }

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final ViewHolder holder;
    // System.out.println("parent.getTag(R.id.main_body_item_title) :"+parent.getTag(R.id.main_body_item_title));
    c = cursor;
    convertView = mInflater.inflate(R.layout.list_row, parent, false);
    holder = new ViewHolder();
    holder.setId(cursor.getInt(0));


    ((ImageView) (convertView
            .findViewById(R.id.main_body_item_title_second_pics)))
            .setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    // System.out.println(view.getTag());
                    addToDB(holder.getId());
                    //Toast.makeText(getApplicationContext(), "insertDataOrder method", 2000).show();
                    System.out.println("i m in ryt [palce");
                }
            });

    convertView.setTag(holder);
    return convertView;
}

void addToDB(Integer objId) {
    if (objId != null) {
        int _id = objId;
        Cursor cursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp,
                new String[] { "_id", "name", "description", "name_NO",
                        "description_NO", "availablequantity", "itemprice",
                        "imagename", "smallImageName", "item_type",
                        "category" }, "_id=?", new String[] { String
                        .valueOf(_id) }, null, null, null);
        if ((cursor != null) && (cursor.getCount() > 0)
                && cursor.moveToFirst()) {
            item = cursor.getString(cursor.getColumnIndex("name"));
            description = cursor.getString(cursor
                    .getColumnIndex("description"));
            name_NO = cursor.getString(cursor.getColumnIndex("name_NO"));
            description_NO = cursor.getString(cursor
                    .getColumnIndex("description_NO"));
            category = cursor.getInt(cursor.getColumnIndex("category"));
            price = cursor.getDouble(cursor.getColumnIndex("itemprice"));

            // _id INTEGER PRIMARY KEY,type INTEGER,title TEXT,description
            // 
            // TEXT, price DOUBLE,category INTEGER
            ContentValues orderValues = new ContentValues();
            Log.d(TAG, "Values Insert Order : " + category + ", " + item
                    + ", " + description + ", " + price);
            orderValues.put("category", category);
            orderValues.put("title", name_NO);
            orderValues.put("description", description);
            orderValues.put("price", price);
            /*if (RestaurantHome.Applocale.equals("no")) {
                orderValues.put("title", name_NO);
                orderValues.put("description", description_NO);
            }*/
            dh.insert(DatabaseHelpereKOT.RESTAURANT_menu_order, null, orderValues);
            String msg = "Menu Item Added Successfully";
            Message msgObject = new Message();
            msgObject.what = 1;
            msgObject.obj = msg;
            addMenuItemHandler.sendMessage(msgObject);

            System.out.println("Click my Order");
            /*System.out.println("OrderListAdapter.totalCount  ="
                    + OrderListAdapter.totalCount);*/
            // select COUNT(*) from CDs;

            /*
             * restaurantHome.intiliazeOrderListDialog();
             * restaurantHome.createOrderListDialog();
             * restaurantHome.showOrderListDialog();
             */
        }
        cursor.close();
    }

}

}

这是我的质押轨迹。

     09-25 10:08:01.192: E/AndroidRuntime(11097): FATAL EXCEPTION: main
     09-25 10:08:01.192: E/AndroidRuntime(11097): java.lang.NullPointerException
     09-25 10:08:01.192: E/AndroidRuntime(11097):   at            com.dm.ekot.MainScreen$1.onClick(MainScreen.java:149)
    09-25 10:08:01.192: E/AndroidRuntime(11097):    at android.view.View.performClick(View.java:3110)
    09-25 10:08:01.192: E/AndroidRuntime(11097):    at android.view.View$PerformClick.run(View.java:11928)
      09-25 10:08:01.192: E/AndroidRuntime(11097):  at android.os.Handler.handleCallback(Handler.java:587)
     09-25 10:08:01.192: E/AndroidRuntime(11097):   at android.os.Handler.dispatchMessage(Handler.java:92)
    09-25 10:08:01.192: E/AndroidRuntime(11097):    at android.os.Looper.loop(Looper.java:132)
   09-25 10:08:01.192: E/AndroidRuntime(11097):     at android.app.ActivityThread.main(ActivityThread.java:4025)
   09-25 10:08:01.192: E/AndroidRuntime(11097):     at java.lang.reflect.Method.invokeNative(Native Method)

我在这段代码中遇到错误-

      Cursor starterCursor = null;
            startManagingCursor(starterCursor);
            starterCursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null,
                    "item_id=?", new String[] { String.valueOf("1") },
                    null, null, null);
            System.out.println("before defore cahnge cursor"+starterCursor);
            adapter.changeCursor(starterCursor);

           System.out.println("before menulist setadapter");
            menuList.setAdapter(adapter);   

在这一行

          adapter.changeCursor(starterCursor);

我的数据库的这个结构

       "create table "
                    + RESTAURANT_menu_temp
                    + " (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,item_id TEXT , item_type TEXT , item_name TEXT , Item_cost DOUBLE)",

和 我必须在数据库中保存一些数据,这些数据正在成功进行,通过单击一个按钮,我必须通过自定义适配器显示所有这些数据,但是我得到空指针异常,问题出在哪里,请一些人帮助我。我真的非常感谢所有人。我是安卓新手。

【问题讨论】:

    标签: android nullpointerexception custom-adapter


    【解决方案1】:
      Cursor starterCursor = null;
            startManagingCursor(starterCursor);
    

    是不是因为starterCursor为空。

    顺便说一句,startManagingCursor 似乎已被弃用!

    此方法在 API 级别 11 中已弃用。请改用带有 LoaderManager 的新 CursorLoader 类;这也可以通过 Android 兼容性包在旧平台上使用。

    【讨论】:

    • @lazy..但是在初始化之后。新数据分配给 starterCursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null, "item_id=?", new String[] { String.valueOf("1") }, null, null, null);
    • @lazy..then 为什么它在这一行出现异常 adapter.changeCursor(starterCursor);
    • @lazy..但我已经将此代码用于另一个对我来说很好的项目..
    • @BlueGreen 为什么在调用adapter.changeCursor(starterCursor)...之前没有为游标添加空检查...
    • @PankajKumar...我用我的查询初始化光标..但仍然得到相同的异常...在这一行......adapter.changeCursor(starterCursor)
    【解决方案2】:

    问题:

    当您在 adapter.changeCursor(starterCursor); 上获得 NPE 时, starterCursoradapter 为 null 。

    1: 检查您是否实例化了您的 CustomCursorAdapter ?如果没有,那就去做吧。

    2: 如果starterCursor 为空,则进行以下更改:

    当前:

    startManagingCursor(starterCursor);
            starterCursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null,
                    "item_id=?", new String[] { String.valueOf("1") },
                    null, null, null);
    

    如下修改:

            starterCursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null,
                    "item_id=?", new String[] { String.valueOf("1") },
                    null, null, null);
    startManagingCursor(starterCursor);
    

    希望对你有帮助!!

    【讨论】:

    • @mehul..我厌倦了这个但仍然遇到同样的问题
    • 你有instantiated你的CustomCursorAdapter吗? starterCursoradapter 肯定为空。
    • @mehul ..你是对的..这是初始化问题...但是请您在另一个问题上帮助我.?.我将非常感谢您的帮助...我是安卓新手。
    • @BlueGreen:很高兴能提供帮助。还有什么问题?
    • @Mehul...这是我显示 item 的代码,但它对我不起作用。 menuList = (ListView) findViewById(R.id.menu_list);光标 cursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null,"item_name=?", new String[] {"%"}, null,null, null);开始管理光标(光标);适配器 = new CustomCursorAdapter(this, cursor); menuList.setAdapter(适配器);
    【解决方案3】:

    您在分配null 后尝试启动光标。您需要分配一个值:

    Cursor starterCursor = null;
    startManagingCursor(starterCursor);
    

    【讨论】:

      猜你喜欢
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      相关资源
      最近更新 更多