I have a listview that is sourced by an sqlite db. I call fillData() at several different points to update the listview.
private void fillData() {
readDatabase.open();
Cursor itemsCursor = readDatabase.fetchAllItems();
startManagingCursor(itemsCursor);
String[] from = new String[] { DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_UNITCOST, DatabaseHandler.KEY_QUANTITY,
DatabaseHandler.KEY_TOTAL };
int[] to = new int[] { R.id.itemtext, R.id.costtext, R.id.quantitytext,
R.id.totaltext };
SimpleCursorAdapter items = new SimpleCursorAdapter(this,
R.layout.rowincart, itemsCursor, from, to);
setListAdapter(items);
}
Whole code of class is added here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.cartactivity);
readDatabase = new DatabaseHandler(this);
// readDatabase.open();
loadwidget();
fillData();
ListView lv = getListView();
this.registerForContextMenu(lv);
}
private void loadwidget() {
Bundle extras = getIntent().getExtras();
cost = extras.getInt("Cost");
quantity = extras.getInt("quantity");
product = extras.getString("product");
Log.i("Hello Testing", cost + " and " + quantity + " " + product);
}
#SuppressWarnings("deprecation")
private void fillData() {
readDatabase.open();
itemsCursor = readDatabase.fetchAllItems();
startManagingCursor(itemsCursor);
String[] from = new String[] { DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_UNITCOST, DatabaseHandler.KEY_QUANTITY,
DatabaseHandler.KEY_TOTAL };
int[] to = new int[] { R.id.itemtext, R.id.costtext, R.id.quantitytext,
R.id.totaltext };
SimpleCursorAdapter items = new SimpleCursorAdapter(this,
R.layout.rowincart, itemsCursor, from, to);
setListAdapter(items);
}
#Override
protected void onDestroy() {
super.onDestroy();
itemsCursor.close();
readDatabase.close();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("SMARTAWAY");
menu.add(0, DELETE_ID, 1, "Delete Item");
menu.add(0, UPDATE_ID, 1, "Change Quantity");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
readDatabase.deleteItem(info.id);
fillData();
return true;
case UPDATE_ID:
final AdapterContextMenuInfo info1 = (AdapterContextMenuInfo) item
.getMenuInfo();
final Dialog dialog = new Dialog(Cartactivity.this);
dialog.setContentView(R.layout.dialog);
final EditText edit0 = (EditText) dialog
.findViewById(R.id.quantity);
edit0.setText(String.valueOf(Quantity));
Button ok = (Button) dialog.findViewById(R.id.ok);
dialog.setTitle(" Add More Items ");
dialog.setCancelable(true);
Button inc = (Button) dialog.findViewById(R.id.inc);
inc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = Integer.parseInt(Quantity);
c = c + 1;
Quantity = String.valueOf(c);
edit0.setText(Quantity);
}
});
Button dec = (Button) dialog.findViewById(R.id.dec);
dec.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = Integer.parseInt(Quantity);
c = c - 1;
Quantity = String.valueOf(c);
edit0.setText(Quantity);
}
});
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
row1 = info1.id;
flag = 1;
int b = Integer.parseInt(Quantity);
int total = cost * b;
_total = String.valueOf(total);
_cost = String.valueOf(cost);
_quantity = String.valueOf(b);
_item = product;
Log.i(row1+" id"+_total +" total"+ _cost +" cost"+ _quantity+" quant", "Hello updated database");
readDatabase.updateItem(row1, _item, _cost, _quantity, _total);
fillData();
dialog.dismiss();
}
});
Button cancel = (Button) dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
return true;
}
return super.onContextItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long thisID) {
super.onListItemClick(l, v, position, thisID);
l.showContextMenuForChild(v);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
Quantity = cursor.getString(cursor
.getColumnIndex(DatabaseHandler.KEY_QUANTITY));
/*Total = cursor.getString(cursor
.getColumnIndex(DatabaseHandler.KEY_TOTAL));*/
}
All the things are going good here, but I found some errors in Logcat ie close() were not called explicitly on database something like this. The error doesnt stop my working anywhere but problem looks wierd. I think I have to close cursor but not sure about that. I have closed database on Destroy but not sure about cursor. Please help.
Same problem is mentioned here but didnt get the actual solution
Thanks in Advance
Colse your cursor every time after using then your problem will bo solved
itemsCursor.close()
As you are not closing this, resources of the cursor is not released for that reason when you close your db you are getting that error.
Make Your cursor as global variable then on your onDestroy
#Override
protected void onDestroy() {
super.onDestroy();
itemsCursor.close();
db.close();
}
And as you are now adding close statement as a last statement of filldata method, the Adapter of listview doesn't get any data as cursor is already released for that reason you are not getting any data in listview.
You should close your cursor object and the database object in the onDestroy() method,
if (itemsCursor!=null){
itemsCursor.close();
}
if (readDatabase!=null){
readDatabase.close();
}
Edit-
Have you tried closing the cursor at the end of the fillData() function,
#SuppressWarnings("deprecation")
private void fillData() {
readDatabase.open();
itemsCursor = readDatabase.fetchAllItems();
startManagingCursor(itemsCursor);
String[] from = new String[] { DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_UNITCOST, DatabaseHandler.KEY_QUANTITY,
DatabaseHandler.KEY_TOTAL };
int[] to = new int[] { R.id.itemtext, R.id.costtext, R.id.quantitytext,
R.id.totaltext };
SimpleCursorAdapter items = new SimpleCursorAdapter(this,
R.layout.rowincart, itemsCursor, from, to);
setListAdapter(items);
if (itemsCursor!=null){
itemsCursor.close();
}
if (readDatabase!=null){
readDatabase.close();
}
}
Related
I got code from stack overflow to bring up a mesg box.
When I call up a mesga box in activty ActGetKey, it goes back to the starting acticty MainActivity, after the exit button is pressed.
mesg box code:
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
code for MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
keyDB db;
db = new keyDB(this);
db.setUp();
cPassKey mPassKey = new cPassKey("mysec","mypublic","myphase");
db.updateExchange("ted2", mPassKey);
Cursor cursor =db.selectKey("ted2");
// get keys in current pos of database
cPassKey mret=db.loadRecord(cursor);
String name;
Cursor test =db.selectKey("ted1");
name = test.getString(2);
name = test.getString(3);
cursor = db.selectRecords();
int id; String ted;
if (cursor != null)
{
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
} while (cursor.moveToNext());
cursor.close();
}
}
public void sendMessage(View view) {
// Intent intent = new Intent(this, ActGetKey.class);
Intent intent = new Intent(this, ActGetKey.class);
startActivity(intent);
}
}
code for ActGetKey Activity
public class ActGetKey extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selItem=null;
long d=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_get_key);
keyDB db;
db= new keyDB(this);
Cursor cursor=db.selectRecords();
String ted="na";
int id=0;
if (cursor != null) {
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
// fill up spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
if (cursor != null) {
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
categories.add(ted);
} while (cursor.moveToNext());
cursor.close();
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set selected item
spinner.setSelection(0);
}
}
public void Update3(View view)
{
d++;
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey=(String)temp.getText().toString();
if (isValidString(strPublicKey))
{
msbox( getString(R.string.badtext), "Text for publick key is invalid");
return;
}
temp = findViewById(R.id.publicKey);
String strPrivetKey=(String)temp.getText().toString();
temp = findViewById(R.id.publicKey);
String strKeyPhrase=(String)temp.getText().toString();
// check for bad dada
}
boolean isValidString( String test)
{
if (test==null)
return false;
return true;
}
public void Update2(View view) {
// put keys in keyclass
msbox("kkk","kjjh");
if (true)
return;
keyDB db;
db= new keyDB(this);
cPassKey mPassKey = getKeys();
db.updateExchange(selItem, mPassKey);
// pus keyclass in data base
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
selItem = parent.getItemAtPosition(position).toString();
keyDB db;
db= new keyDB(this);
Cursor cursor =db.selectKey(selItem);
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
boolean loadKeys(cPassKey mPassKey)
{
EditText temp;
temp = findViewById(R.id.publicKey);
temp.setText(mPassKey.publickKey);
temp = findViewById(R.id.secretKey);
temp.setText(mPassKey.secretKey);
temp = findViewById(R.id.phraseKey);
temp.setText(mPassKey.phraseKey);
return true;
}
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
cPassKey getKeys()
{
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey= temp.getText().toString();
temp = findViewById(R.id.secretKey);
String StrSecretKey= temp.getText().toString();
temp = findViewById(R.id.phraseKey);
String StrPhraseKey= temp.getText().toString();
cPassKey mPassKey = new
cPassKey( StrSecretKey,strPublicKey, StrPhraseKey);
return mPassKey;
}
}
public class ActGetKey extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selItem=null;
long d=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_get_key);
keyDB db;
db= new keyDB(this);
Cursor cursor=db.selectRecords();
String ted="na";
int id=0;
if (cursor != null) {
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
// fill up spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
if (cursor != null) {
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
categories.add(ted);
} while (cursor.moveToNext());
cursor.close();
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set selected item
spinner.setSelection(0);
}
}
public void Update3(View view)
{
d++;
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey=(String)temp.getText().toString();
if (isValidString(strPublicKey))
{
msbox( getString(R.string.badtext), "Text for publick key is invalid");
return;
}
temp = findViewById(R.id.publicKey);
String strPrivetKey=(String)temp.getText().toString();
temp = findViewById(R.id.publicKey);
String strKeyPhrase=(String)temp.getText().toString();
// check for bad dada
}
boolean isValidString( String test)
{
if (test==null)
return false;
return true;
}
public void Update2(View view) {
// put keys in keyclass
msbox("kkk","kjjh");
if (true)
return;
keyDB db;
db= new keyDB(this);
cPassKey mPassKey = getKeys();
db.updateExchange(selItem, mPassKey);
// pus keyclass in data base
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
selItem = parent.getItemAtPosition(position).toString();
keyDB db;
db= new keyDB(this);
Cursor cursor =db.selectKey(selItem);
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
boolean loadKeys(cPassKey mPassKey)
{
EditText temp;
temp = findViewById(R.id.publicKey);
temp.setText(mPassKey.publickKey);
temp = findViewById(R.id.secretKey);
temp.setText(mPassKey.secretKey);
temp = findViewById(R.id.phraseKey);
temp.setText(mPassKey.phraseKey);
return true;
}
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
cPassKey getKeys()
{
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey= temp.getText().toString();
temp = findViewById(R.id.secretKey);
String StrSecretKey= temp.getText().toString();
temp = findViewById(R.id.phraseKey);
String StrPhraseKey= temp.getText().toString();
cPassKey mPassKey = new
cPassKey( StrSecretKey,strPublicKey, StrPhraseKey);
return mPassKey;
}
}
That is because of the finish() method inside the onClickListener. Finish() doesn't cancel the dialog, it finishes the activity. Use dismiss() if you are trying to hide the dialog
I'm new in Android. I have the same problem as described here...I am trying to manage a simple list in an Android application. The contents of the list are maintained in a SQLite database. When the user selects and holds on a specific row, a context menu appears with a "Open/Delete" option. When they select "Delete", the row is deleted from the database, but the view does not refresh. When I back out of the application and get back in, the appropriate row has been removed. So, I know the row is deleted, it's just the ListView that doesn't refresh. The same with adding new item to the database. I searched solution, but not yet find. Appreciate any help.
Activity class:
public class ProjectsActivity extends Activity {
private RMProject rmProject = null;
private RMProjectDBHelper projectDBHelper = null;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rmProject = new RMProject();
projectDBHelper = new RMProjectDBHelper(this);
final ListView lv = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<>(this, R.layout.list_item, getProjectNames());
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProjectsActivity.this);
builder.setTitle("What to do with project?");
builder.setPositiveButton("Open", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ProjectsActivity.this, OpenProjectActivity.class);
//todo: send project information as parameter
startActivity(intent);
}
});
//**!!!Here I delete project item from database!!!**
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selected = ((TextView) view.findViewById(R.id.list_textView)).getText().toString();
int projId = projectDBHelper.findIdByName(selected);
projectDBHelper.deleteProject(projId);
Toast toast=Toast.makeText(getApplicationContext(), "Project "+selected+" deleted", Toast.LENGTH_SHORT);
toast.show();
//**call getProjectNames and notifydataSetChanged**
getProjectNames();
adapter.notifyDataSetChanged();
}
});
builder.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_item) {
final Dialog dialog = new Dialog(ProjectsActivity.this);
dialog.setContentView(R.layout.add_proj);
dialog.setTitle("Введите название проекта:");
dialog.setCancelable(false);
Button okBtn = (Button) dialog.findViewById(R.id.btn_create_proj);
Button cancelBtn = (Button) dialog.findViewById(R.id.btn_cancel_proj);
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editProjName = (EditText) dialog.findViewById(R.id.edit_proj_name);
String projName = editProjName.getText().toString();
if (rmProject == null) {
rmProject = new RMProject();
}
rmProject.setName(projName);
if (projectDBHelper == null) {
projectDBHelper = new RMProjectDBHelper(ProjectsActivity.this);
}
projectDBHelper.addProject(rmProject);
dialog.dismiss();
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
private String[] getProjectNames() {
LinkedList<RMProject> projects = (LinkedList<RMProject>) projectDBHelper.getAllProjects();
String[] names = new String[projects.size()];
int i = 0;
for (RMProject p : projects) {
names[i++] = p.getName();
}
return names;
}
}
Fragment with custom DbHelper class:
public class RMProjectDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "RM_DB";
private static final String TABLE_PROJECT = "PROJECT";
private static final String[] COLUMNS = {"id_project", "project_name"};
private static final int DB_VERSION = 1;
public RMProjectDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//.....some code...
public void deleteProject(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PROJECT, "id_project = ?", new String[]{String.valueOf(id)});
db.close();
Log.d("deleteProject with id: ", Integer.toString(id));
}
public int findIdByName(String name){
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT PROJECT.id_project FROM PROJECT WHERE PROJECT.project_name = '"+name+"'";
Cursor cursor = db.rawQuery(selectQuery,null);
int id=-1;
while (cursor.moveToNext()){
id = cursor.getInt(cursor.getColumnIndex("id_project"));
Log.i("LOGGING:"," FIND ID BY NAME: ID="+id);
}
return id;
}
on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work
I'm using the following code to show data from sqlite in listView
public class AndroidSQLite extends Activity {
ListView listContent;
private SQLiteAdapter mySQLiteAdapter;
Button addZekr;
EditText zekrTxtEditor;
String[] items;
boolean[] itemsChecked ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_sqlite);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
mySQLiteAdapter.insert(getResources().getString(R.string.zekr1));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr2));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr3));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr4));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr5));
// Open the same SQLite database and read all it's content.
mySQLiteAdapter = new SQLiteAdapter(this);
setDataInList();
Button addZekr = (Button) findViewById(R.id.addZekrBtn);
addZekr.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
zekrTxtEditor = (EditText)findViewById(R.id.zekr_text);
String newZekr = zekrTxtEditor.getText().toString();
System.out.println("newZekr: "+newZekr);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.insert(newZekr);
setDataInList();
}
});
mySQLiteAdapter.close();
listContent.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parentView, View childView,
int position, long id) {
// TODO Auto-generated method stub
String itemPostion = listContent.getItemAtPosition(position).toString();
System.out.println("in Long Press itemPostion: "+itemPostion);
return false;
}
});
listContent.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView, View childView,
int position, long id) {
// TODO Auto-generated method stub
String itemPostion = listContent.getItemAtPosition(position).toString();
System.out.println("in Normal Press itemPostion: "+itemPostion);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Dialog with simple text");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < items.length; i++) {
if (itemsChecked[i]) {
Toast.makeText(getBaseContext(), items[i] + " checked!", Toast.LENGTH_LONG).show();
}
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_LONG).show();
}
});
builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(), items[which] + (isChecked ? "checked!" : "unchecked!"), Toast.LENGTH_SHORT).show();
}
});
builder.create();
builder.show();
}
break;
}
return true;
}
public void setDataInList(){
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
items = new String[]{SQLiteAdapter.KEY_CONTENT};
int[] to = new int[]{R.id.text};
String myContent = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT)).toString().trim();
// long id = cursor.getLong(cursor.getColumnIndex(SQLiteAdapter.KEY_ID));
System.out.println("itemssss: "+myContent);
itemsChecked = new boolean[items.length];
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.row, cursor, items, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
}
}
what I want to to is to get the data of KEY_CONTENT column and put them in an array to show them in the AlertDialog
So I putted this line
String myContent = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT)).toString().trim();
but it gives me this Exception:
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5
any help?
The exception mean that the cursor is positioned before the first row, as it is the case when it is created. You should move it to the first row using moveToFirst()
for example :
if (moveToFirst()) {
String myContent = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT)).toString().trim();
...
} else {
// no data
}
Alternatively you may use moveToNext(), in a loop for example.
Hi i want to remove the checked items from the listview and in database.Iam using menus for that.If delete is selected from the menu then i want to remove the selected items from the listview and in the database.If select all is clicked in the menu i want to set all the checkbox of the listitems checked and then delete all the values from the listview and to delete all the records in the database.Iam using the following code to populate the data from the database in the listview with checkbox.Please help me if anybody knows.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.senthistory);
lvhistory = (ListView) findViewById(android.R.id.list);
PopulateSentList();
}
public void PopulateSentList() {
String strquery = "SELECT * FROM sent_history";
Cursor Cursor = (MainscreenActivity.JEEMAAndroSMSDB).rawQuery(
strquery, null);
MyAdapter adapter = new MyAdapter(SentHistoryActivity.this, Cursor);
setListAdapter(adapter);
lvhistory.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
SQLiteCursor selectedValue = (SQLiteCursor) getListAdapter()
.getItem(position);
String id1 = selectedValue.getString(0);
System.out.println("DATA-->>>" + id1);
Intent intent = new Intent(getApplicationContext(),
Historydisplay.class);
intent.putExtra("Id", id1);
final int result = 1;
startActivityForResult(intent, result);
}
});
}
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(SentHistoryActivity.this,
MainscreenActivity.class);
startActivity(intent);
finish();
}
private void CreateMenu(Menu menu) {
menu.setQwertyMode(true);
MenuItem mnu1 = menu.add(0, 0, 0, "Delete");
{
mnu1.setAlphabeticShortcut('D');
}
MenuItem mnu2 = menu.add(0, 0, 0, "Select All");
{
mnu2.setAlphabeticShortcut('S');
}
}
private boolean MenuChoice(MenuItem item) throws Exception {
switch (item.getItemId()) {
case 0:
int count = (int) getListAdapter().getCount();
for (int i = 1; i <= count; i++) {
if (this.lvhistory.isItemChecked(i)) {
listItems.remove(i);
adapter.notifyDataSetChanged();
MainscreenActivity.JEEMAAndroSMSDB.delete(
MainscreenActivity.Table_SentHistory, "_id=" +i, null);
finish();
Intent intent = new Intent(getApplicationContext(),
SentHistoryActivity.class);
startActivity(intent);
}
}
return true;
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
return MenuChoice(item);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private class MyAdapter extends ResourceCursorAdapter {
public MyAdapter(Context context, Cursor cur) {
super(context, R.layout.dummy, cur);
}
#Override
public View newView(Context context, Cursor cur, ViewGroup parent) {
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return li.inflate(R.layout.dummy, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cur) {
TextView tvListText = (TextView)view.findViewById(R.id.Mobile);
final CheckBox chkBox = (CheckBox)view.findViewById(R.id.check);
tvListText.setText(cur.getString(cur.getColumnIndex(MainscreenActivity.COL_Mobile)));
chkBox.setTag(cur.getString(cur.getColumnIndex(MainscreenActivity.COL_Sent_id)));
chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Log.v("Checked", chkBox.getTag().toString());
}
});
}
}
For removing checked items you can use isChecked() method for CheckBox. In your code you can use in following manner.
chkBox.setOnClickListener(new new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox)v;
if(cb.isChecked() == true)
{
String getStrinValue = cb.getTExt().toString(); // here you will get the value of selected CheckBox
// And now you have to perform your deletion operation as usual.
}
}
Ok, i'll give an overview of how to accomplish. This is what i did for my application.
First you need to have a model class for the list item which has a property to maintain the state(checked), then whenever you are getting the items from the database create list of items, such as arraylist.
Then whenever the check box get checked change the state property of the particular list item. Finally when you click the delete from the menu, there would be three steps
Get the checked items from the arraylist
Remove items from the adapter
Remove items from the database
I think this would make sense
EDIT
Have you tried this previous SO question? BTW this will help only to remove the items from the adapter. You have to find a way to remove the items from the database.
Here's how i did. I found this to be the easiest solution to always match the right ID. Because the adapter and the cursor will always have the same counting and position. Both have a starting index at 0.
This is what's inside my case for the menu item.
I also added an alert dialog as a safety step.
if (mListView.getCount() == 0 || mListView.getCheckedItemCount() == 0) {
Toast.makeText(this, "Select an item by holding", Toast.LENGTH_SHORT).show();
return false;
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you want to delete these items?");
builder.setCancelable(true);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SparseBooleanArray selection = mListView.getCheckedItemPositions();
Cursor data = mDBHandler.getAllIDs(); // "SELECT " + COLUMN_ID + " FROM " + TABLE_NAME;
int itemID;
int itemCount = arrayAdapter.getCount();
for (int i=itemCount-1; i >= 0; i--) {
if (selection.get(i)) {
data.moveToPosition(i);
itemID = data.getInt(data.getColumnIndexOrThrow("id")); // COLUMN_ID = "id"
mDBHandler.deleteItem(itemID);
}
}
selection.clear();
updateListView();
dialog.cancel();
}
});
builder.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDelete = builder.create();
alertDelete.show();
return true;
public void updateListView() {
mListView.setAdapter(arrayAdapter);
Cursor data = mDBHandler.getItems();
arrayList.clear();
while (data.moveToNext()) {
arrayList.add(data.getString(1));
}
arrayAdapter.notifyDataSetChanged();
}
I have a spinner that show my data list from a database SQLite.. I want to remove a row from Spinner and db when selected then clicked button btn. How can I do this? Thanks
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_wf2);
mDB = new MyDatabase(getApplicationContext());
mDB.open();
spin = (Spinner)findViewById(R.id.wf_spinner);
c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
spinnerPos = pos;
mRowId = id; // database row id
}
});
//fillSpinner(spin);
Button btn = (Button)findViewById(R.id.button11);
btn.setText("Rimuovi");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDB.delete_byID(mRowId);
c.requery();
}
});
/*
Spinner spin = (Spinner)findViewById(R.id.wf_spinner);
Cursor cur = mDB.fetchWfs();
startManagingCursor(cur);
String[] from = new String[] { WfMetaData.WF_NAME_KEY };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter spinAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cur, from, to);
spinAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(spinAdapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Cursor c = (Cursor)parent.getItemAtPosition(pos);
mSpinnerWF = c.getInt(c.getColumnIndexOrThrow(WfMetaData.WF_NAME_KEY));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});*/
//mDB.close();
}
My delete method is this:
public boolean delete_byID(long rowId) {
return mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "=" + rowId, null) > 0;
CharSequence text = "Il Workflow "+ n +" è stato rimosso con successo!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
I don't find any delete method from ID. Is this a db method?
I've modified my app like this:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_wf2);
mDB = new MyDatabase(getApplicationContext());
mDB.open();
spin = (Spinner)findViewById(R.id.wf_spinner);
c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
spinnerPos = pos;
mRowId = id; // database row id
}
});
//fillSpinner(spin);
mDB.close();
Button btn = (Button)findViewById(R.id.button11);
btn.setText("Rimuovi");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.getItem(spinnerPos);
mDB.delete_byName((String)adapter.getItem(spinnerPos));
c.requery();
}
});
but I get this error in LogCat(Cast exception):
05-10 15:46:38.586: D/RadioSignalLevel(1758): Gsm Radio Signal level: 4
05-10 15:46:38.586: D/StatusBarPolicy(1758): ERI alert sound is disabled.
05-10 15:46:38.606: D/NetworkService(1939): handle message:800
05-10 15:46:38.606: D/NetworkService(1939): getRawGPRSRegistrationState
05-10 15:46:38.616: I/TransactionService(29090): MMS-STATUS - start transaction service, app version=STABLE4.5.user.4.5.2A-74_OLE-31.2.3.4.Blur_Version.45.31.0.MB860.TIM.en.IT.Thu Sep 22 04:02:02 CST 2011 (log=false) (apn=false) (config=false)
05-10 15:46:38.626: I/SmsReceiverService(29090): MMS-STATUS - start sms receiver service, app version=STABLE4.5.user.4.5.2A-74_OLE-31.2.3.4.Blur_Version.45.31.0.MB860.TIM.en.IT.Thu Sep 22 04:02:02 CST 2011 (log=false) (apn=false) (config=false)
05-10 15:46:38.636: I/TelephonyRegistry(1610): notifyDataConnection: state=0 isDataConnectivityPossible=false reason=nwTypeChanged interfaceName=null networkType=10
05-10 15:46:38.636: I/SYS_MPP(1965): WebtopStatusHandler updateDataIcon()
05-10 15:46:38.646: D/NetworkService(1939): handle message:800
05-10 15:46:38.646: D/NetworkService(1939): getRawGPRSRegistrationState
05-10 15:46:38.646: I/CBStartup(1939): onServiceStateChanged
05-10 15:46:38.656: I/CBSettings(1939): Reading database: KEY_NAME= db_key_language
05-10 15:46:38.656: I/CBSettings(1939): Reading database: KEY_NAME= db_key_channel
public class MyDatabase {
SQLiteDatabase mDb;
DbHelper mDbHelper;
Context mContext;
private static final String DEBUG_TAG = "WFListDatabase";
private static final String DB_NAME="WFListdb";//nome del db
private static final int DB_VERSION=1; //numero di versione del nostro db
public MyDatabase(Context ctx) {
mContext = ctx;
mDbHelper = new DbHelper(ctx, DB_NAME, null, DB_VERSION); //quando istanziamo questa classe, istanziamo anche l'helper (vedi sotto)
}
public void open(){ //il database su cui agiamo è leggibile/scrivibile
mDb=mDbHelper.getWritableDatabase();
}
public void close(){ //chiudiamo il database su cui agiamo
mDb.close();
}
public void insertWf(String name,String cls){ //metodo per inserire i dati
ContentValues cv=new ContentValues();
cv.put(WfMetaData.WF_NAME_KEY, name);
cv.put(WfMetaData.WF_CLASS_KEY, cls);
mDb.insert(WfMetaData.WF_TABLE, null, cv);
}
/*public void removeWf(String name,String cls){ //metodo per inserire i dati
ContentValues cv=new ContentValues();
cv.remove(WfMetaData.WF_NAME_KEY);
cv.remove(WfMetaData.WF_CLASS_KEY);
mDb.(WfMetaData.WF_TABLE, null, cv);
}*/
public Cursor fetchAllWfs(){ //metodo per fare la query di tutti i dati
return mDb.query(WfMetaData.WF_TABLE, new String[]{WfMetaData.WF_NAME_KEY, WfMetaData.WF_CLASS_KEY},null,null,null,null,null);
}
static class WfMetaData { // i metadati della tabella, accessibili ovunque
static final String WF_TABLE = "wfs";
static final String ID = "_id";
static final String WF_NAME_KEY = "name";
static final String WF_CLASS_KEY = "class";
}
private static final String WF_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " //codice sql di creazione della tabella
+ WfMetaData.WF_TABLE + " ("
+ WfMetaData.ID+ " integer primary key autoincrement, "
+ WfMetaData.WF_NAME_KEY + " text not null, "
+ WfMetaData.WF_CLASS_KEY + " text not null);";
public Cursor fetchWfs(){ //metodo per fare la query di tutti i dati
return mDb.query(WfMetaData.WF_TABLE, null,null,null,null,null,null);
}
public void delete_byName(String n){
mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "='" +n + "'", null);
//mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "=?", new String[] { n });
CharSequence text = "Il Workflow "+ n +" è stato rimosso con successo!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
public void delete_byID(long rowId) {
mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "=" + rowId, null);
CharSequence text = "Il Workflow è stato rimosso con successo!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
private class DbHelper extends SQLiteOpenHelper { //classe che ci aiuta nella creazione del db
public DbHelper(Context context, String name, CursorFactory factory,int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase _db) { //solo quando il db viene creato, creiamo la tabella
_db.execSQL(WF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(DEBUG_TAG, "Upgrading database. Existing contents will be lost. ["
+ oldVersion + "]->[" + newVersion + "]");
_db.execSQL("DROP TABLE IF EXISTS " + WF_TABLE_CREATE);
onCreate(_db);
}
}
public boolean isEmpty(){
boolean isEmpty = true;
Cursor cursor = mDb.query(WfMetaData.WF_TABLE, new String[] { WfMetaData.WF_NAME_KEY }, null, null, null, null, null);
if (cursor != null && cursor.getCount() > 0)
{
isEmpty = false;
}
return isEmpty;
}
}
public class RemoveWorkflow2 extends Activity {
private EditText nameEditText;
private EditText classEditText;
//private EditText idEditText;
//private int mSpinnerWF;
Spinner spin;
WorkflowChoice wf = new WorkflowChoice();
MyDatabase mDB;
SimpleCursorAdapter adapter;
private long mRowId;
private int spinnerPos;
private String delString;
Cursor c;
//MyDatabase mDB = wf.getDb();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_wf2);
mDB = new MyDatabase(getApplicationContext());
mDB.open();
spin = (Spinner)findViewById(R.id.wf_spinner);
c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Cursor c = (Cursor)(parent.getAdapter().getItem(pos));
delString = c.getString(c.getColumnIndex(mDB.);
//spinnerPos = pos;
//mRowId = id; // database row id
}
});
//fillSpinner(spin);
Button btn = (Button)findViewById(R.id.button11);
btn.setText("Rimuovi");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDB.delete_byID(mRowId);
mDB.delete_byName(delString);
c.requery();
}
});
}
private void fillSpinner(Spinner s){
Cursor c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
s.setAdapter(adapter);
}
}
I have a problem in method:
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Cursor c = (Cursor)(parent.getAdapter().getItem(pos));
delString = c.getString(c.getColumnIndex(mDB.);
//spinnerPos = pos;
//mRowId = id; // database row id
}
How can I set delString? I don't have YOUR_COLUMN_ID.. How can I resolve it? THANKS
I'm assuming the button is outside the spinner...
You don't really need the position. Set a class variable:
private int spinnerPos;
private long mRowId;
Add this for your spinner:
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
spinnerPos = pos;
mRowId = id; // database row id
}
});
Then for your button:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code to get the string from the adapter
mDB.delete_byName(yourString);
c.requery();
});
By the way, you should leave your DB open until you are exiting the app.
I see you asking a question about deleting by id. In your database class you would have something like this:
public boolean delete(long rowId) {
return mDb.delete(TABLE_NAME, TABLE_ROWID + "=" + rowId, null) > 0;
}
Hope this helps!
EDIT
Better method:
Private String delString;
Add this for your spinnerListener
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Cursor c = (Cursor) (parent.getAdapter().getItem(pos));
delString = c.getString(c.getColumnIndex(YourDB.YOUR_COLUMN_ID)); }
});
Button:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDB.delete_byName(delString);
c.requery();
});
EDIT 2
First Method for delete (by RowId):
public boolean delete_byID(long rowId) {
return mDb.delete(WfMetaData.WF_TABLE, WfMetaData.ID + "=" + rowId, null) > 0;
}
Second Method for delete (by name):
public boolean delete_byName(String name) {
return mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "= '" + name + "'", null) > 0;
}