0

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

        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)",

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

4

3 回答 3

1
  Cursor starterCursor = null;
        startManagingCursor(starterCursor);

不就是因为starterCursor空吗。

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

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

于 2013-09-25T10:14:32.700 回答
0

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

Cursor starterCursor = null;
startManagingCursor(starterCursor);
于 2013-09-25T10:17:31.437 回答
0

问题:

当您打开 NPE 时adapter.changeCursor(starterCursor);,要么 要么starterCursoradapternull 。

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

我希望它会有所帮助!

于 2013-09-25T10:56:36.757 回答