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.
Related
i have a listview . in which item come from database listview has also checkbox . listview work fine . now i put a edittext on listview i wana filter my listview i try a lot . i do some thing like this.i use custom adapter.
this is my list data code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(DataListActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(DataListActivity.this);
a_builder.setMessage("Do You Want To Close This App !!!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("EXIT", true);
startActivity(intent);
//finish();
}
})
.setNegativeButton("No" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert !!!");
alert.show();
// Toast.makeText(
// MainMenu.this,
// "You Clicked : " + item.getTitle(),
// Toast.LENGTH_SHORT
// ).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
final DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),
"dish name is : " + name, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView) row
.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView) row
.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView) row
.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView) row
.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView) row
.findViewById(R.id.text_dish_sugar);
layoutHandler.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie
.setText(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}
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
Im setting up a main activity with a ListView object, however, the ListView will not respond to touch, onItemClick and onContextItemSelected are not reachable, i have set up setOnItemClickListener and registerForContextMenu, and i dont see my error, here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener {
long selectedMovieId;
DbHandler dbhandler;
Movie selectedMovie;
MovieAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_setting = (Button) findViewById(R.id.page_main_setting);
Button btn_add = (Button) findViewById(R.id.page_main_add);
ListView lv = (ListView) findViewById(R.id.list);
btn_add.setOnClickListener(this);
btn_setting.setOnClickListener(this);
lv.setOnItemClickListener(this);
dbhandler = new DbHandler(this);
registerForContextMenu(lv);
Cursor c = dbhandler.queryAll();
startManagingCursor(c);
adapter = new MovieAdapter(this, c);
lv.setAdapter(adapter);
}
#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_options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_options_exit:
finish();
return true;
case R.id.main_option_delete_all:
dbhandler.deleteAll();
refresh();
return true;
}
return false;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.d("context menu", "clicked");
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
selectedMovieId = info.id;
switch (item.getItemId()) {
case R.id.main_context_edit:
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_CONTEXT, selectedMovie+"");
startActivity(intent);
return true;
case R.id.main_context_delete:
dbhandler.deleteMovie(selectedMovieId);
refresh();
return true;
}
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.page_main_setting:
openOptionsMenu();
break;
case R.id.page_main_add:
DialogInterface.OnClickListener listenerInternet = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),
InternetEditActivity.class);
startActivity(intent);
}
};
DialogInterface.OnClickListener listenerManual = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),AddEditActivity.class);
intent.putExtra(DbConstants.MANUAL, DbConstants.MANUAL);
startActivity(intent);
}
};
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Please choose an adding method")
.setCancelable(false).setNegativeButton("Cancel", null)
.setNeutralButton("via internet", listenerInternet)
.setPositiveButton("Manual", listenerManual).create();
dialog.show();
break;
}
}
class MovieAdapter extends CursorAdapter /*implements OnTouchListener*/ {
public MovieAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// inflate the view:
return getLayoutInflater().inflate(R.layout.main_list_layout,
parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// bind the data
// get the data from the cursor
String subject = cursor.getString(cursor.getColumnIndex(DbConstants.DB_SUBJECT));
String body = cursor.getString(cursor.getColumnIndex(DbConstants.DB_BODY));
String internal_location = cursor.getString(cursor.getColumnIndex(DbConstants.DB_INTERNAL_LOCATION));
int year = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_YEAR));
int status = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_STATUS));
int rating = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_RATING));
TextView subjectText = (TextView) view.findViewById(R.id.list_main_subject);
TextView bodyText = (TextView) view.findViewById(R.id.list_main_body);
TextView yearText = (TextView) view.findViewById(R.id.list_main_year);
TextView statusText = (TextView) view.findViewById(R.id.list_main_status);
ImageView image = (ImageView) view.findViewById(R.id.list_main_imgae);
//RatingBar ratingBar = (RatingBar) view.findViewById(R.id.list_main_ratingBar1);
//ratingBar.setOnTouchListener(this);
subjectText.setText(subject);
bodyText.setText(body);
yearText.setText(String.valueOf(year));
//ratingBar.setRating(rating);
Log.d("status in main", status+"");
Log.d("rating in main", rating+"");
if (status==0){
statusText.setText("watched");
} else if (status==1){
statusText.setText("Not watched");
}
Log.d("ternal loction", internal_location+"!");
if (internal_location!=null){
File imgFile = new File(internal_location);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
}
}
/*#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}*/
} //Movie Adapter close
public void refresh(){
Cursor newCursor = dbhandler.queryAll();
Cursor oldCursor = adapter.getCursor();
adapter.changeCursor(newCursor);
startManagingCursor(newCursor);
stopManagingCursor(oldCursor);
oldCursor.close();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long id) {
Log.d("list menu", "clicked");
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_LISTVIEW, id);
startActivity(intent);
}
} //Main Activity close
it has to be somthing to do with the layout of the list, a simple list inserted next to it worked
OnItemClick event is now intercepted by RatingBar.
Add onTouchEvent listener to your RatingBar and return false to say to system that RatingBar does not handle this events.
#Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(MotionEvent event)
return false;
}
Edit: above answer is for subclassing RatingBar.
But you already have onTouchEvent just return false instead of true.
The problem was that there was a Scroll view object in the layout of the adapter, remove it and the problem will be fixed
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();
}
}
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();
}