如何从customAdapter类向数据库添加项?

时间:2015-11-28 04:13:33

标签: android sqlite listview onclick custom-adapter

好的,所以我想在listview中单击一行后向我的数据库中添加一个项目。我只能从我的customAdapter类中获取onclickListener并启动对话框,但在添加项目后,我在调用onCreate时从我的db getWritableData方法收到错误。

我觉得问题在于我向additem添加3个字符串而不是添加项目。虽然我不太确定如何将项数据传递给dbHandler.addItem方法或传递3个字符串,就像我正在做的那样

public class searchResults extends AppCompatActivity {
    private String websiteString, searchString;
    private int pos;
    private List<item> li;
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_results);

        Bundle searchBundle = getIntent().getExtras();
        if (searchBundle == null) {
            return;
        }
        searchString = searchBundle.getString("searchString");
        websiteString = searchBundle.getString("websiteString");

        TextView searchText = (TextView) findViewById(R.id.searchResultsTextView);
        searchText.setText("Search for: " + searchString + " from " + websiteString);
        li = searchBundle.getParcelableArrayList("itemL");

        int count = li.size();
        String[] imgLi = new String[count], descLi = new String[count], priceLi = new String[count];
        int i = 0;
        for(item l : li){
            String img = l.getImage(), desc = l.getItemName(), price = l.getPrice();
            imgLi[i] = img;
            descLi[i] = desc;
            priceLi[i] = price;
            i++;
        }
        final int selectedListItem = getIntent().getIntExtra("PositionInList", -1);
        lv=(ListView) findViewById(R.id.searchResultsListView);
        lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        lv.setSelection(selectedListItem);
        lv.setAdapter(new CustomAdapter(this, imgLi, descLi, priceLi));

    }
}

CustomAdapter.java

public class CustomAdapter extends BaseAdapter {

    private String [] image, desc, price;
    private Context context;
    private ListView lv;

    private static LayoutInflater inflater=null;
    public CustomAdapter(Activity mainActivity, String[] imageList, String[] descList, String[] priceList) {
        // TODO Auto-generated constructor stub
        image = imageList;
        desc = descList;
        price = priceList;
        context=mainActivity;
        inflater = ( LayoutInflater )context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return image.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tv;
        TextView tv1;
        ImageView img;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final DBHandler dbHandler = new DBHandler(context, null, null, 1);
        Holder holder=new Holder();
        final View rowView;
        rowView = inflater.inflate(R.layout.item_list, null);
        holder.tv=(TextView) rowView.findViewById(R.id.textViewDesc);
        holder.tv1=(TextView) rowView.findViewById(R.id.textViewPrice);
        holder.img=(ImageView) rowView.findViewById(R.id.imageViewImage);
        holder.tv.setText(desc[position]);
        holder.tv1.setText(price[position]);
        String url = image[position];
        lv = (ListView) rowView.findViewById(R.id.searchResultsListView);
        try {
            new ImageDownloaderTask(holder.img).execute(url);

        } catch (Exception e) {
            e.printStackTrace();
        }
        rowView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                alertDialogBuilder.setMessage("Are you sure you want to add item to PriceWatcher");
                alertDialogBuilder.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                //do what you want to do if user clicks ok
                                dbHandler.addItem(image[position], desc[position], price[position]);


                            }
                        });
                alertDialogBuilder.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //do what you want to do if user clicks cancel.
                            }
                        });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();

            }
        });
        return rowView;
    }
}

DBHandler

public class DBHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "items.db";
    public static final String TABLE_PRODUCTS = "items";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_ITEMNAME = "itemName";
    public static final String COLUMN_PRICE = "price";
    public static final String COLUMN_IMAGE = "image";

    public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_IMAGE + " TEXT, " +
                COLUMN_ITEMNAME + " TEXT, " +
                COLUMN_PRICE + " TEXT, " +
                ")";
        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP_TABLE_IF_EXISTS " + TABLE_PRODUCTS);
        onCreate(db);
    }

    public void addItem(String img, String desc, String price){
        ContentValues values = new ContentValues();
        values.put(COLUMN_IMAGE, img);
        values.put(COLUMN_ITEMNAME, desc);
        values.put(COLUMN_PRICE, price);
        SQLiteDatabase db = getWritableDatabase();
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }

    public void deleteItem(String itemName){
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_ITEMNAME + "=\"" + itemName);
    }

    public String databaseToString() {
        String dbString = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();

        while(!c.isAfterLast()) {
            if(c.getString(c.getColumnIndex("itemName")) != null){
                dbString += c.getString(c.getColumnIndex("itemName"));
                dbString += "\n";
            }
        }
        db.close();
        return dbString;
    }
}

2 个答案:

答案 0 :(得分:1)

将SQLiteDatabase db = getWritableDatabase()更改为SQLiteDatabase database = context.getWritableDatabase(),我认为这一定是个问题,否则你的插入方法是正确的我猜

答案 1 :(得分:0)

很抱歉,人们在onCreate数据库时遇到错误,而且我输入了一个额外的逗号。

无论如何,谢谢你的帮助。