0

I am developing a app but i am getting Null pointer exception in Custom adapter. My custom-adapter code is as follow-

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

}

}

This is my stake-trace.

     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)

I am getting error at this code-

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

In this line

          adapter.changeCursor(starterCursor);

this structure of my database

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

, and I have to save some data in database which is going on successfully and by click on a button i have to show all these data by custom adapter , but i ma getting null pointer exception , where is problem please some body help me.I am really thanks full to all. I am new in android.

3 Answers 3

1
  Cursor starterCursor = null;
        startManagingCursor(starterCursor);

Isn't it because of starterCursor being null.

By the way it seems that startManagingCursor is deprecated!

This method was deprecated in API level 11. Use the new CursorLoader class with LoaderManager instead; this is also available on older platforms through the Android compatibility package.

Sign up to request clarification or add additional context in comments.

5 Comments

@lazy..But after initialization. new data assign to starterCursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null, "item_id=?", new String[] { String.valueOf("1") }, null, null, null);
@lazy..then why it is giving exception in this line adapter.changeCursor(starterCursor);
@lazy..but i already used this code for another project which work fine for me..
@BlueGreen Why did not you add null check for cursor before calling adapter.changeCursor(starterCursor)...
@PankajKumar...i initialize cursor with my query.. but still getting same exception...at this line........adapter.changeCursor(starterCursor)
0

Issue:

as you are getting NPE on adapter.changeCursor(starterCursor); , either starterCursor or adapter is null .

1: check whether have you instantiated your CustomCursorAdapter ? if not,then do it.

2: if starterCursor is null then do the following changes:

Current:

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

Change it as below:

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

I hope it will be helpful !!

8 Comments

@mehul..I tired this but still getting same problem
have you instantiated your CustomCursorAdapter ? either starterCursor or adapter is null for sure.
@mehul..you are right..it was issue on initialization... but will you please help me in another issue.?.i will be really thank full to you for help...i am new in android.
@BlueGreen: I'm glad to help.what is another issue?
@Mehul...this is my code to show item , but it doesn't work for me. menuList = (ListView) findViewById(R.id.menu_list); Cursor cursor = dh.query(DatabaseHelpereKOT.RESTAURANT_menu_temp, null,"item_name=?", new String[] {"%"}, null,null, null); startManagingCursor(cursor); adapter = new CustomCursorAdapter(this, cursor); menuList.setAdapter(adapter);
|
0

You are trying to start cursor after assignning it null. You need assign a value:

Cursor starterCursor = null;
startManagingCursor(starterCursor);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.