Deleting from SQL database android - android

I have a list view and when the user clicks a specific item a contextual action mode is displayed with only one item in it (that is supposed to delete it). However, when I click it, the database is not updated (the item is still on the list). Could anyone help me ?
In MainActivity:
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
protected Object mActionMode;
int catPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
List<String> all = entry.getAllCategory();
if(all.size()> 0){
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
}else{
Toast.makeText(MainActivity.this,"No items to display",Toast.LENGTH_LONG).show();
}
entry.close();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
catPos = position;
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = MainActivity.this
.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete_cat:
// shareCurrentItem();
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
entry.deleteCat(catPos);
List<String> all = entry.getAllCategory();
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
entry.close();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
in Actual Database:
public class CategoryDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
private static final String DATABASE_NAME = "DBCategory";
private static final String DATABASE_TABLE = "categoryTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public CategoryDatabase(Context c){
ourContext = c;
}
public CategoryDatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CATEGORY + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long createEntry(String category) {
ContentValues cv = new ContentValues();
cv.put(KEY_CATEGORY, category);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public List<String> getAllCategory() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
List.add(cursor.getString(1));
} while (cursor.moveToNext());
}
return List;
}
public void deleteCat(int catPos) {
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + catPos, null);
}
}

Deleting as "entry.deleteCat(catPos);" is not right. If You use Your catPos, which is the position inside the listView, it will not delete the entry from database. You made an INTEGER_PRIMARY_KEY_AUTOINCREMENT inside Your Database, so this Integer will generated automatically and can differ from Your position Integer. What You have to do is, to make a query method inside Your Database where You get even the ID from Your DB-Entry. Then You could call
entry.deleteCat(databaseId);

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

By long clicking on listview delete its contents from SQLite and listview that is clicked

Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.

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

Making a dynamic ListView clickable to change activity

My android app currently populates a ListView (in MainActivity) with the contents of a sqlite table. I would like to be able to click one of the created ListView Items and have it change activities to my EditNote activity, but also pass the database record relating to that ListView into EditNote, and populate the EditTexts.
My MainActivity is populates the ListView on load:
public class MainActivity extends ListActivity{
DatabaseHelper dbh;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DatabaseHelper(this);
dbh.open();
adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
ArrayList<String[]> searchResult = new ArrayList<String[]>();
//EditText searchTitle = (EditText) findViewById(R.id.searchC);
listItems.clear();
searchResult = dbh.fetchNotes("");
//searchResult = dbh.fetchNotes(searchTitle.getText().toString());
String title = "", note = "";
for (int count = 0 ; count < searchResult.size() ; count++) {
note = searchResult.get(count)[1];
title = searchResult.get(count)[0];
listItems.add(title);
}
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void addNote(View v){
Intent newActivity = new Intent (this, AddingNote.class);
startActivity(newActivity);
finish();
}
}
My database class used to create the table and select statement:
public class DatabaseHelper {
private static final String DATABASE_NAME = "noteDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "note";
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT NOT NULL, " +
"note TEXT NOT NULL); ";
public DatabaseHelper(Context ctx) {
this.dbContext = ctx;
}
public DatabaseHelper open() throws SQLException {
mDbHelper = new OpenHelper(dbContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createNote(String title, String note) {
ContentValues initialValues = new ContentValues();
initialValues.put("title", title);
initialValues.put("note", note);
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
public boolean updateNote(long rowId, String title, String note) {
ContentValues args = new ContentValues();
args.put("title", title);
args.put("note", note);
return mDb.update(TABLE_NAME, args, "_id=" + rowId, null) > 0;
}
public void deleteAll() {
mDb.delete(TABLE_NAME, null, null);
}
public void deleteRecord(long rowID) {
mDb.delete(TABLE_NAME, "_rowId=" + rowID, null);
}
public ArrayList<String[]> fetchNotes(String title) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"_id", "title",
"note"}, null, null,
null, null, "_id");
int titleColumn = mCursor.getColumnIndex("title");
int noteColumn = mCursor.getColumnIndex("note");
if (mCursor != null){
if (mCursor.moveToFirst()){
do {
myArray.add(new String[3]);
myArray.get(pointer)[0] = mCursor.getString(titleColumn);
myArray.get(pointer)[1] = mCursor.getString(noteColumn);
//increment our pointer variable.
pointer++;
} while (mCursor.moveToNext()); // If possible move to the next record
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "NO RESULTS";
myArray.get(pointer)[1] = "";
}
}
return myArray;
}
public ArrayList<String[]> selectAll() {
ArrayList<String[]> results = new ArrayList<String[]>();
int counter = 0;
Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "id", "forename", "surname", "age" }, null, null, null, null, "surname desc");
if (cursor.moveToFirst()) {
do {
results.add(new String[3]);
results.get(counter)[0] = cursor.getString(0).toString();
results.get(counter)[1] = cursor.getString(1).toString();
results.get(counter)[2] = cursor.getString(2).toString();
results.get(counter)[3] = cursor.getString(3).toString();
counter++;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return results;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
My list view XML (within activity_main.xml):
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/container" >
</ListView>
I'm pretty new to android development, so any help will be gratefully appreciated. Thank you.
Set an onClickListener to your ListView and start an Intent pointing to your EditNote activity which gets the data using:
getIntent().getStringExtra(...);
Example:
MainActivity:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(this, EditNote.class);
i.putExtra("listItem", listItems[position]);
startActivity(i);
}
});
EditNote:
String listItem = getIntent().getStringExtra("listItem");
Is this what you're looking for?

SQL table not found exception

i have made a table and its fields but i get error that no such row exist and if i comment them out then it is not detecting the table also showing no such table exist.Here's the code:
package com.example.ifest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper{
private static final String DB_NAME = "event_db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "_table";
private static final String EVENT_NAME = "_name" ;
private static final String EVENT_ID = "_no" ;
private static final String EVENT_TYPE = "_type" ;
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ EVENT_NAME + " TEXT NOT NULL, " + EVENT_TYPE + " TEXT NOT NULL);" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
and the code for my other acitvity is:
public class ProfileView extends ListActivity{
String e,e1;
static int p = 0;
Spinner spn ;
Button b1,b2;
EditText et;
String str1;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("Create");
openDB();
p++;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(position == 0){
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition());
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
}
}
protected void addDB(String name,int id) {
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_name",name);
if(id == 0)
cv.put("type","WIFI");
else if(id == 1)
cv.put("type","BLUETOOTH");
else if(id == 2)
cv.put("type","MEDIA");
db.insert("_table", null , cv);
db.close();
}
private void openDB() {
if(p != 0){
DBHandler handle = new DBHandler(this);
SQLiteDatabase db = handle.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+ "event_db",null);
c.moveToFirst();
while(c.moveToNext()){
list.add(c.getString(1));
Log.d("cursor", c.getString(1));
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflate = getMenuInflater();
inflate.inflate(R.menu.string_main,menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.item1:
final Dialog build = new Dialog(ProfileView.this);
build.setTitle("String Name and Details");
build.setContentView(R.layout.activity_dialog);
build.show();
spn = (Spinner)build.findViewById(R.id.spinner1_Dialog);
et = (EditText) build.findViewById(R.id.editText1_Dialog);
b2 = (Button) build.findViewById(R.id.button1_Dialog);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
build.dismiss();
list.add(et.getText().toString());
addDB(et.getText().toString(),spn.getLastVisiblePosition());
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
break;
case R.id.item2:
break;
case R.id.item3:
Intent i = new Intent("com.example.ifest.ABOUTUS");
startActivity(i);
break;
case R.id.item4:
finish();
break;
}
return true;
}
}
You are using "type" on your contentvalue but your column is named: "_type".
You are querying the event_db table which is the name of your database, not your table
Cursor c = db.rawQuery("SELECT * FROM "+ "event_db",null);
You should query the _table table
Cursor c = db.rawQuery("SELECT * FROM "+ "_table",null);
By the way it would be more clear if you name your database db (I doubt you need more than one db anyway) and your table _event (you can have many tables and you should name them accordingly to their role and not just _table)

Categories

Resources