Delete an item from List - android

I'm creating an app that scans bar codes, saves them in a db and manages them through a list.
So, these are classes that interested in my problem
Main
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scanner_menu);
Button addButton = (Button) findViewById (R.id.addMenuButton);
addButton.setOnClickListener (new OnClickListener(){
public void onClick (View v){
startActivity(new Intent(CodiceBarreActivity.this, AggiungiCodiceActivity.class));
}
});
Button listButton = (Button) findViewById (R.id.ViewlistButton);
listButton.setOnClickListener (new OnClickListener(){
public void onClick (View v){
startActivity(new Intent(CodiceBarreActivity.this, ProdottiSelectionActivity.class));
}
});
}
static final class ProductData {
long _id;
String barcode;
String format;
String title;
String price;
}
}
helper
private SQLiteDatabase db;
public ProductDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
StringBuilder sql = new StringBuilder();
sql.append("create table ")
.append(PRODUCT_TABLE)
.append("( ")
.append(" _id integer primary key,")
.append(" barcode text,")
.append(" format text,")
.append(" title text,")
.append(" price text")
.append(") ");
db.execSQL(sql.toString());
Log.d(TAG, PRODUCT_TABLE + "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + PRODUCT_TABLE);
Log.d(TAG, PRODUCT_TABLE + "table dropped");
onCreate(db);
}
db
private static final String PRODUCT_TABLE = "products";
private static final BigDecimal ONE_HUNDRED = new BigDecimal("100");
private SQLiteDatabase db;
public CodiciDatabase(Context context) {
ProductDatabaseHelper helper = new ProductDatabaseHelper(context);
db = helper.getWritableDatabase();
}
public boolean insert(ProductData product) {
ContentValues vals = new ContentValues();
vals.put("_id", product._id);
vals.put("barcode", product.barcode);
vals.put("format", product.format);
vals.put("title", product.title);
vals.put("price", product.price);
return db.insert(PRODUCT_TABLE, null, vals) != -1;
}
interested class
private ProductDatabaseHelper dbHelper;
private static final String PRODUCT_TABLE = "products";
ProductData product = new ProductData();
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new ProductDatabaseHelper(this);
}
#Override
protected void onResume(){
super.onResume();
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + PRODUCT_TABLE, null);
setListAdapter(new CursorAdapter(this, cursor, true) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
TextView textView = new TextView(ProdottiSelectionActivity.this);
return textView;
}
#Override
public void bindView (View view, Context context, Cursor cursor){
TextView textView = (TextView) view;
textView.append(cursor.getString(1));
textView.append("\n");
textView.append(cursor.getString(2));
textView.append("\n");
textView.append(cursor.getString(3));
textView.append("\n");
textView.append(cursor.getString(4));
registerForContextMenu(textView);
}
});
}
#Override
protected void onDestroy(){
super.onDestroy();
dbHelper.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
}
}
I need to implement the method onListItemClick so that you delete the selected item.I'm going crazy looking for the right syntax I hope you can help me!

Seems to me like you may be getting errors in your "interested class". Your code is a bit confusing in some places, I'm not exactly sure if your using a list view or not. But it would be helpful to use a list view and bind it to a onItemClickListener. You will use extends ListActivity in the layout you want to display the items in, make sure to put a listview element in your list view layout. Then to populate your list view, you'll have:
String[] tableColumnNames = new String[] {
"TABLE COLUMN NAMES SEPARATED BY COMMAS" };
int[] textViewLabelNames = new int[] { "NAMES OF TEXT VIEW LABELS IN XML ROW LAYOUT" };
SimpleCursorAdapter stuff = new SimpleCursorAdapter(this,
R.layout.your_created_xml_row_layout, cursor, tableColumnNames,
textViewLabelNames);
this.setListAdapter(stuff);
Then bind your onClickListener:
listView.setOnItemClickListener(new OnItemClickListener() {
//ListView item is clicked
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
Referring back to your code:
When onListItemClick is triggered you need to delete from the database the row corresponding to the id passed into the onListItemClick method. You then need to update your cursor to reflect the changes on the view by using cursor.requery().
So in order to delete an item from a database with a certain id you can do this:
ProductDatabaseHelper helper = new ProductDatabaseHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.delete("TABLE NAME HERE", "NAME OF ID COLUMN HERE" + "=" + id, null);
database.close();
You can also view the SQLiteDatabase Docs for a helpful description of the method signature.

something like this should work:
db.delete("products", "barcode" + "="+ barcodeToDelete, null);
replace barcodeToDelte with the value of the barcode that you want to delete from the table. If you won't know the value of the barcode you could delete it based on any of the other fields in your database too by subbing them in for "barcode" in the method above.

Related

Data not being inserted in Table on Button Press

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}
Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~
this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed
The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()
Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

SQLite Database to listView?

I'm trying to get data from column ITEMS in my Database to appear in the Items listView when you click the add button. At the moment when you click the add button it just saves a item in a column of the database. I would appreciate an answer!
The main Java class (New_Recipe)
public class New_Recipe extends AppCompatActivity {
Button add,done,display;
EditText Recipe_Name,Recipe_Item,Recipe_Steps;
String search;
WebView webView;
DatabaseHelper databaseHelper;
ListView Items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new__recipe);
databaseHelper = new DatabaseHelper(this);
setTitle("New Recipe");
add = (Button) findViewById(R.id.button2);
done = (Button) findViewById(R.id.button);
Recipe_Name = (EditText) findViewById(R.id.editText);
Recipe_Item = (EditText) findViewById(R.id.editText2);
Recipe_Steps = (EditText) findViewById(R.id.editText3);
webView = (WebView) findViewById(R.id.webView);
display = (Button) findViewById(R.id.button3);
Items = (ListView) findViewById(R.id.listView);
AddData();
viewAll();
}
public void AddData() {
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean inserted = databaseHelper.insertData1(Recipe_Name.getText().toString(),
Recipe_Steps.getText().toString());
if (inserted == true)
Log.d("Database", "Data successfully inserted!");
else Log.d("Database","Data did not insert!");
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean inserted = databaseHelper.insertData2(Recipe_Item.getText().toString());
if (inserted == true)
Log.d("Database", "Data successfully inserted!");
else Log.d("Database","Data did not insert!");
}
});
}
public void viewAll() {
display.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = databaseHelper.getAllData();
if (res.getCount() == 0) {
showMessage("Error","No Data found!");
return;
}
StringBuffer stringBuffer = new StringBuffer();
while (res.moveToNext()) {
stringBuffer.append("Names :"+res.getString(0)+"\n");
stringBuffer.append("Items :"+res.getString(1)+"\n");
stringBuffer.append("Steps :"+res.getString(2)+"\n\n");
}
showMessage("Success!",stringBuffer.toString());
}
});
}
public void showMessage(String title,String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void onSearch(View v) {
search = "Recipes";
webView.loadUrl("https://www.google.com/search?q="+search);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new__recipe, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The Database Java class (DatabaseHelper)
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Recipes.db";
public static final String TABLE_NAME = " Recipe_Table";
public static final String COL1 = "NAME";
public static final String COL2 = "ITEMS";
public static final String COL3 = "STEPS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
Log.d("Database", "Database should be made!");
}
#Override
public void onCreate (SQLiteDatabase db){
db.execSQL("create table " + TABLE_NAME + " (NAME TEXT PRIMARY KEY,ITEMS TEXT,STEPS TEXT)");
Log.d("Database", "Database should be made!, Again");
}
#Override
public void onUpgrade (SQLiteDatabase db,int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
Log.d("Database", "Table exists");
onCreate(db);
}
public boolean insertData1(String name,String steps) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, name);
contentValues.put(COL3, steps);
long result = db.insert(TABLE_NAME,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean insertData2(String items) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, items);
long result = db.insert(TABLE_NAME,null,contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getItemData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select"+COL2+"from"+TABLE_NAME,null);
return res;
}
}
The real Android way to do this would be to use a combination of ContentProvider and CursorAdapter.
Android already has a way to take a Cursor from a query and put the data in a ListView: The CursorAdapter class. You just override getView() to create the item view for your list.
Here's what a custom ContentProvider will get you: When you create a content provider URI and query it to get a Cursor, a DataObserver is set up, so that when you insert/delete/update data through the ContentProvider using that URI, the Cursor will get a notification that the data has changed and will re-query the data. When that Cursor has been set on a CursorAdapter, the adapter will also see that the cursor data has changed and call notifyDataSetChanged().
So the net result is that when you add a record, your ListView is automatically refreshed with current data.
For an introduction to Content Providers, refer to this article: Content Providers | Android Developers.
You need to create an adapter that the list view can draw its data from. You will pass the data from your getAllData() call to the adapter, which the list view will then display.
If you haven't already, you can create a custom class which extends base adapter, implement the methods correctly, then all you have to worry about it the data.
First off, I always like to build a class that can store my data retrieved from the database. Something simple, like:
public class ItemObject {
// Instance variables.
private String mName, mItem, mStep;
// Constructor.
public ItemObject(String name, String item, String step) {
mName = name;
mItem = item;
mStep = step;
}
// Create getters for each item.
public String getName() { /*...*/ }
public String getItem() { /*...*/ }
public String getStep() { /*...*/ }
}
Now you have an object that can store the items retrieved from the database table. In your while loop after calling getAllData() you create your ItemObject there.
For example:
List<ItemObject> itemObjectList = new ArrayList<>();
while (res.moveToNext()) {
// Extract values from the cursor.
String name = res.getString(0);
String item = res.getString(1);
String step = res.getString(2);
// Create the ItemObject and add it to the list.
ItemObject item = new ItemObject(name, item, step);
// Add it to the list.
itemObjectList.add(item);
}
Now, you'll have a list of items you can pass directly to your adapter.
public class ItemsListAdapter extends BaseAdapter {
// Instance variables.
private Context mContext;
private List<ItemObject> mItemObjectList;
// Constructor.
public ItemsListAdapter(Context context, List<itemObjectList> itemObjectList) {
mContext = context;
mItemObjectList = itemObjectList;
}
#Override
public int getCount() {
return mItemObjectList.size();
}
#Override
public Object getItem(int position) {
return mItemObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Inflate your layout for each row here. I wont include list view
// optimization here, as you should look it up, its documentation
// is readily available.
LayoutInflater inflater = LayoutInflater.from(mContext);
// Inflate the layout.
View layout = inflater.inflate(R.layout.<your_list_view_row_layout>, null);
// Reference the views inside the layout that will display each value. (Name, Item, Step);
TextView nameView = (TextView) layout.findViewById(R.id.<your_text_view_id>);
// Do this for each view.
// Now retrieve your data from the array list.
ItemObject item = (ItemObject) getItem(position);
// Now you have your item and the 3 values associated with it.
// Set the values in the UI.
nameView.setText(item.getName());
// Return the view.
return layout;
}
// Use this method to modify the data in the list view.
// It's an ArrayList so simply add or remove elements, clear it, etc.
public List<ItemObject> getAdapterList() {
return mItemObjectList;
}
}
To update the items in the list view, call getAdapterList() and modify the items in the ArrayList that is returned. After modification, you must invalidate the list by calling notifyDataSetChanged() on the adapter itself.
Hope this points you in the right direction.

Trying to Toast a single item from Database with OnItemSelected in a Spinner

The spinner has items that are dynamically added with two editText's and a Button. When the user inputs text into the first EditText it displays that text in the spinner. I am trying to Toast KEY_CALORIES from the second EditText that is sent into the database with OnItemSelected. I am trying to learn as a hobby so, an explanation would be great.
MainActivity. At the bottom is the OnItemSelected.
public class MainActivity extends Activity implements OnItemSelectedListener {
Button AddBtn;
EditText et;
EditText cal;
Spinner spn;
SQLController SQLcon;
ProgressDialog PD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AddBtn = (Button) findViewById(R.id.addbtn_id);
et = (EditText) findViewById(R.id.et_id);
cal = (EditText) findViewById(R.id.et_cal);
spn = (Spinner) findViewById(R.id.spinner_id);
spn.setOnItemSelectedListener(this);
SQLcon = new SQLController(this);
// opening database
SQLcon.open();
loadtospinner();
AddBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new MyAsync().execute();
}
});
}
public void loadtospinner() {
Cursor c = SQLcon.readData();
ArrayList<String> al = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(DBhelper.MEMBER_NAME));
al.add(name);
c.moveToNext();
}
ArrayAdapter<String> aa1 = new ArrayAdapter<String>(
getApplicationContext(), R.layout.spinner_item, R.id.textView1,
al);
spn.setAdapter(aa1);
// closing database
SQLcon.close();
al.add("Shit");
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
String name = et.getText().toString();
String calories = cal.getText().toString();
// opening database
SQLcon.open();
// insert data into table
SQLcon.insertData(name, calories);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
loadtospinner();
PD.dismiss();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
/* I am trying to Toast KEY_CALORIES from the database
* Tried many solution that failed and can't seem to grasp retrieving a single item from the database.
* Appreciate your help
*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
DataBase
public class SQLController {
private DBhelper dbhelper;
private Context ourcontext;
private SQLiteDatabase database;
public SQLController(Context c) {
ourcontext = c;
}
public SQLController open() throws SQLException {
dbhelper = new DBhelper(ourcontext);
database = dbhelper.getWritableDatabase();
return this;
}
public void close() {
dbhelper.close();
}
public void insertData(String name, String calories) {
ContentValues cv = new ContentValues();
cv.put(DBhelper.MEMBER_NAME, name);
cv.put(DBhelper.KEY_CALORIES, calories);
database.insert(DBhelper.TABLE_MEMBER, null, cv);
}
public Cursor readData() {
String[] allColumns = new String[] { DBhelper.MEMBER_ID,
DBhelper.MEMBER_NAME, DBhelper.KEY_CALORIES };
Cursor c = database.query(DBhelper.TABLE_MEMBER, allColumns, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
Helper
public class DBhelper extends SQLiteOpenHelper {
// TABLE INFORMATTION
public static final String TABLE_MEMBER = "member";
public static final String MEMBER_ID = "_id";
public static final String MEMBER_NAME = "name";
public static final String KEY_CALORIES = "calories";
// DATABASE INFORMATION
static final String DB_NAME = "MEMBER.DB";
static final int DB_VERSION = 2;
// TABLE CREATION STATEMENT
private static final String CREATE_TABLE = "create table " + TABLE_MEMBER
+ "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MEMBER_NAME + " TEXT NOT NULL," + KEY_CALORIES
+ " INT NOT NULL);";
public DBhelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
onCreate(db);
}
}
Edit It is Toasting the cal but every single cal entered into the database any suggestion to just show the cal that is clicked?
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
/*
* I am trying to Toast KEY_CALORIES Tried many solution that failed and
* can't seem to grasp retrieving a single item from the database.
* Appreciate your help
*/
SQLcon.open();
Cursor c = SQLcon.readData();
c.moveToFirst();
while (!c.isAfterLast()) {
String cal= c.getString(c.getColumnIndex(DBhelper.KEY_CALORIES));
Toast.makeText(getBaseContext(), cal+ "", Toast.LENGTH_LONG)
.show();
c.moveToNext();
}
SQLcon.close();
// closing database
}
First you need access to your adapter in order to get the selected string, so I would declare the aa1 adapter as a class field.
When you do that, you can access your adapter from the onItemSelected method:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
String your_selected_item=(String)aa1.getItem(pos);
Toast.makeText(getApplicationContext(),
your_selected_item, Toast.LENGTH_SHORT).show();
}
But I think your approach is not right... If you are listing DB-stored data, you should take a look at the CursorAdapter ;)

Delete a row from SQLite database by taking id from the populated listview

Individual rows in the database are populated in a custom listview. the id of the row is also displayed in the listview. All I want is to delete a particular row by clicking on the corresponding list.
Here is the code I used to display the contents of the database:
class NoteAdapter extends CursorAdapter {
public NoteAdapter(Cursor c) {
super(Reccuring.this, c);
}
#Override
public void bindView(View row, Context ctxt, Cursor c) {
NoteHolder holder = (NoteHolder) row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row1, parent, false);
NoteHolder holder = new NoteHolder(row);
row.setTag(holder);
return row;
}
}
static class NoteHolder {
private TextView name = null;
private TextView number = null;
private TextView idtext = null;
NoteHolder(View row) {
name = (TextView) row.findViewById(R.id.noteText);
number= (TextView) row.findViewById(R.id.noteText1);
idtext = (TextView) row.findViewById(R.id.noteText3);
}
void populateFrom(Cursor c, NoteHelper helper) {
name.setText(helper.getNote(c));
number.setText(helper.getNote1(c));
idtext.setText(helper.getNote2(c));
}
}
And here's my database:
public class NoteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Test.db";
private static final int SCHEMA_VERSION = 1;
public NoteHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Notes (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, num TEXT, sDate TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
public void insert(String note, String amt, String sDate) {
ContentValues cv = new ContentValues();
cv.put("note", note);
cv.put("num", num);
cv.put("sDate", sDate);
getWritableDatabase().insert("Notes", "notes", cv);
}
public String getNote(Cursor c) {
return (c.getString(1));
}
public String getNote1(Cursor c) {
return (c.getString(2));
}
public String getNote2(Cursor c) {
return (c.getString(0));
}
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, note, num, sDate FROM Notes", null));
}
}
}
How can I select the rows in the listview and delete the corresponding rows in the database.
First get the value at position which is clicked by method onItemClickListener() of list view:
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
LinearLayout linearLayout = (LinearLayout) view;// The main layout which contains your child views in which value is displayed
TextView name = (TextView)linearLayout.getChildAt(0);// get child textview 1
String nametext = name.getText().toString();// get String out of those textview
deleteOldData(nametext)
}
Then go to your database class and write this code:
public void deleteOldData(String nametext) {
_sqliteDB.delete(tablename, " note = '" + nametext + "'", null);
}
This way you can delete your table particular row.
If you are not able to do with this or may be notes column in database are same so use unique Id to set in text view of listview, extract it in this form and then pass that value to the database code and then delete it.

Inserting checked values from listView multiple choice

I've one listView with multiple choice and checkbox.
I get the values from listview executing a query in sqlite3.
When i click a button, I need to insert the selected items in another table but i don't know how can i do it.
Before doing insert i'm trying to know if it works showing one console log (Log.v). in this code there is not insert statement.
Any suggestions? Thanks in advance and sorry about my english,
Alex.
I paste the code:
public class productos extends Activity {
SQLiteDatabase db;
Spinner prodSpinner;
ArrayAdapter<String> prodAdapter;
Spinner catSpinner;
ArrayAdapter<String> catAdapter;
Cursor catCursor;
Cursor prodCursor;
String Value2;
String valor2;
SparseBooleanArray sp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productos);
Bundle extras = getIntent().getExtras();
//final String Value = extras.getSerializable("Lista").toString();
//final String Value2 = extras.getSerializable("Super").toString();
Button CatText2 = (Button) findViewById(R.id.textCategoria);
CatText2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.v("valor4:", "AAAAA");
recCatSpinner();
}
});
Button btSelecciona = (Button) findViewById(R.id.btSelecciona);
btSelecciona.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
Toast.makeText(getBaseContext(),"AAAA",Toast.LENGTH_SHORT).show();
}
});
Button btComanda = (Button) findViewById(R.id.btComanda);
btComanda.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
EscriuComanda();
}
private void EscriuComanda() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
int count = 0;
//
sp = new SparseBooleanArray();
//SparseBooleanArray sp=prodSpinner.getCheckedItemPositions();
sp.clear();
sp = prodSpinner.getCheckedItemPositions();
for(int i = 0; i < sp.size(); i++)
{
if ( sp.valueAt(i)==true)
{
Log.v("400", "SI: " + valor2);
}
else
{
Log.v("500", "No: " + valor2);
}
}
}
});
//Toast.makeText(getBaseContext(),Value2,Toast.LENGTH_SHORT).show();
recCatSpinner();
}
public class UsuariosSQLiteHelper extends SQLiteOpenHelper {
public UsuariosSQLiteHelper(Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
public void onCreate(SQLiteDatabase db) {
Log.v("OnClickV", "1");
}
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
Log.v("OnClickV", "1");
}
}
public Cursor recuperaCategoria()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "Categorias";
String[] columns = {"_id","Nombre"};
return db.query(tableName, columns, null, null, null, null, null);
}
public Cursor recuperaProductos()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "ArtSuperV";
String[] columns = {"_id","NombreA"};
String where = "NombreC='" + valor2 + "'";
return db.query(tableName, columns, where, null, null, null, null);
}
public void recCatSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
catCursor = recuperaCategoria();
catCursor.moveToPosition(1);
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); //.simple_list_item_multiple_choice);// .simple_spinner_item);
catAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(catAdapter);
if (catCursor.moveToFirst()) {
do {
catAdapter.add(catCursor.getString(1));
}
while (catCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),catCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(catCursor);
catCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
recProdSpinner();
}
});
}
public void recProdSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
prodCursor = recuperaProductos();
prodCursor.moveToPosition(1);
prodAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice); //.simple_list_item_multiple_choice);// .simple_spinner_item);
prodSpinner.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
prodAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(prodAdapter);
if (prodCursor.moveToFirst()) {
do {
prodAdapter.add(prodCursor.getString(1));
}
while (prodCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),prodCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(prodCursor);
prodCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
}
});
}
}
Cant figure out some of the code flow due to language issue.But scheme should be:1. Set the adapters for both the lists (even if the lists are empty on launch, set the adapter with the empty but initialised array lists and make the array list as the global variables of the class so that they can be accessed from anywhere in the activity.) 2. Now select the items from the list1 and get their index in the first list.3. Add those items in the second array list. 4. Call the "notifyDataSetChanged()" for the adapter of the second list view.Link to know about proper use of "notifyDataSetChanged()" are notifyDataSetChanged example

Categories

Resources