vendredi 27 novembre 2015

How can I add item to data base from my customAdapter class?

Okay so I want to add an item to my db after I click a row in my listview. I can only get my onclickListener to work from my customAdapter class and brings up the dialogbox okay but after I add item I am getting an error from my db onCreate method when calling getWritableData. I feel the problem lies with me adding 3 strings to additem instead of adding an item. Although i am not too sure how to either get item data to pass to dbHandler.addItem method or pass 3 strings like I am doing

        package com.example.jamie.pricewatch;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

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

    }
}






        package com.example.jamie.pricewatch;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created by Jamie on 25/11/2015.
 */
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;
    }
}

package com.example.jamie.pricewatch;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
/**
 * Created by Jamie on 25/11/2015.
 */
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;
    }
}

Aucun commentaire:

Enregistrer un commentaire