Listview shows one item multiple times - android

I am trying to create a List for Android with a SQLite DB. While creating a new Item works without a problem, after it returns to the list activity, the Items are showed various times. Still in my DB only one new Item is inserted (as should), and when I restart the App and load the list, each Item is showed once. So here is my main activity, as I said DBHandler should be ok.
public class MainActivity extends Activity {
List<FavImages> FavImages = new ArrayList<FavImages>();
ListView favImageListView;
final Context context = this;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mEditor;
//label logs
private static String logtag = "CameraApp";
//use main camera
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public Uri imagePath = Uri.parse("android.resource://com.adrian/drawable/no_picture.png");
DataBaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<FavImages> favImagesAdapter;
private static final int EDIT = 0, DELETE = 1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
favImageListView = (ListView) findViewById(R.id.listView);
dbHandler = new DataBaseHandler(getApplicationContext());
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
mEditor = mPrefs.edit();
//enter an Item
registerForContextMenu(favImageListView);
//maybe without long
favImageListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//position of Item
longClickedItemIndex = position;
return false;
}
});
populateList();
//Button Action
Button cameraButton = (Button)findViewById(R.id.button_camera);
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener(){
public void onClick(View v){
takePhoto(v);
}
};
//launch native camera app
private void takePhoto(View v){
final Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//save Image and create file
// in Progress
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
final EditText input1 = (EditText) textEntryView.findViewById(R.id.pictureName);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
//create Dialog
alert
.setTitle("Bitte bennenen Sie Ihr Bild!")
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
/* User clicked OK so do some stuff */
String inputText = input1.getText().toString();
mEditor.putString("pictureName", inputText);
mEditor.commit();
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), replaceChars(mPrefs.getString("pictureName", "picture")) + ".jpg");
//access information of file
imageUri = Uri.fromFile(photo);
//save image path information
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//for favImages
imagePath = imageUri;
mEditor.putString("picturePath", imagePath.toString());
mEditor.commit();
//
startActivityForResult(intent, TAKE_PICTURE);
//
Log.e("Dateipfad", imagePath.toString());
FavImages favImages = new FavImages(dbHandler.getFavCount(), mPrefs.getString("pictureName", "Bild"), imagePath);
dbHandler.createFav(favImages);
FavImages.add(favImages);
//favImagesAdapter.notifyDataSetChanged();
populateList();
List<FavImages> addableFavs = dbHandler.getAllFav();
int favCount = dbHandler.getFavCount();
for(int i = 0; i < favCount; i++){
FavImages.add(addableFavs.get(i));
}
if (!addableFavs.isEmpty())
populateList();
}
});
//show Dialog
alert.show();
}
public String replaceChars (String inputText){
inputText = inputText.replace("ä","ae");
inputText = inputText.replace("ö","oe");
inputText = inputText.replace("ü","ue");
inputText = inputText.replace("ß","ss");
return inputText;
}
//deal with output
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
//user hits ok button (picture accepted)
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageUri;
//communication between apps
getContentResolver().notifyChange(selectedImage, null);
/*get Image
ImageView imageView = (ImageView)findViewById(R.id.image_camera);
//hold Image data
ContentResolver cr = getContentResolver();
Bitmap bitmap;
//get bitmap data
try {
bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
//set Image
imageView.setImageBitmap(bitmap);
//notify user of success
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
}catch (Exception e){ //catch exceptions along the way
Log.e(logtag, e.toString());
} */
}
}
//
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Favorit bearbeiten");
menu.add(Menu.NONE, DELETE, menu.NONE, "Favorit löschen");
}
public boolean onContextItemSelected (MenuItem item){
switch (item.getItemId()){
case EDIT:
//TODO: edit Favorites
break;
case DELETE:
//
dbHandler.deleteFav(FavImages.get(longClickedItemIndex));
FavImages.remove(longClickedItemIndex);
favImagesAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private void populateList(){
//ArrayAdapter<FavImages> adapter = new favImagesListAdapter();
//favImageListView.setAdapter(adapter);
favImagesAdapter = new favImagesListAdapter();
favImageListView.setAdapter(favImagesAdapter);
}
//Constructor for List Items
private class favImagesListAdapter extends ArrayAdapter<FavImages>{
public favImagesListAdapter(){
super (MainActivity.this, R.layout.listview_item, FavImages);
}
#Override
public View getView (int position, View view, ViewGroup parent){
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
FavImages currentFav = FavImages.get(position);
TextView favName = (TextView) view.findViewById(R.id.favName);
favName.setText(currentFav.getImageName());
ImageView ivFavsImage = (ImageView) view.findViewById(R.id.favImage);
ivFavsImage.setImageURI(currentFav.getImagePath());
return view;
}
}
So to sum it up, what am I doing wrong, that my Items are loaded various times.
EDIT:
as requested here is my DBHandler class:
<!-- language: lang-java -->
public class DataBaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "favoritesManager",
TABLE_FAVS = "favorites",
KEY_ID = "id",
KEY_IMGName = "name",
KEY_IMGPATH = "imagePath";
//standard DB method
public DataBaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//standard DB method
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE_FAVS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_IMGName + " TEXT, " + KEY_IMGPATH + " TEXT)");
}
//standard DB method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABL IF EXISTS" + TABLE_FAVS);
onCreate(db);
}
public void createFav(FavImages favImages){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMGName, favImages.getImageName());
values.put(KEY_IMGPATH, favImages.getImagePath().toString());
db.insert(TABLE_FAVS, null, values);
db.close();
}
public void deleteFav(FavImages favImages){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_FAVS, KEY_ID + "=?", new String[]{String.valueOf(favImages.getId())});
db.close();
}
public int getFavCount(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVS, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public List<FavImages> getAllFav(){
List<FavImages> favImages = new ArrayList<FavImages>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVS, null);
if (cursor.moveToFirst()){
do {
favImages.add(new FavImages(Integer.parseInt(cursor.getString(0)), cursor.getString(1), Uri.parse(cursor.getString(2))));
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return favImages;
}

Hi you need to use the view holder pattern see link provided below:
http://ricston.com/blog/optimising-listview-viewholder-pattern/

Ok after a fresh look on the code I found my mistake myself, I am adding multiple times the same Item to the List. Stupid mistake I know but now it works fine.
Still, thanks for your Help.

Related

How to update ListView in Activity after updating database in other Activity?

public class SettingsActivity extends AppCompatActivity {
private Context context;
private DogDatabaseHelper dbHelper;
private ListView mListView;
private ArrayList<String> names = new ArrayList<String>();
private AdapterForNames namesAdapter;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.settings);
mListView = (ListView)findViewById(R.id.listforall);
context = this;
namesAdapter = new AdapterForNames(this,names);
mListView.setAdapter(namesAdapter);
DogDatabaseHelper dbHelper = new DogDatabaseHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select name from dog",null);
if(cursor != null && cursor.moveToFirst()){
do{
names.add(cursor.getString(cursor.getColumnIndex("name")));
namesAdapter.notifyDataSetChanged();
}while (cursor.moveToNext());
}
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(SettingsActivity.this,SetupActivity.class);
intent.putExtra("name",names.get(position));
startActivity(intent);
}
});
}
public class AdapterForNames extends ArrayAdapter<String> {
private ArrayList<String> names;
AdapterForNames(Context context, ArrayList<String> names){
super(context,R.layout.settingsname,names);
this.names = names;
}
public void refresh(ArrayList<String> names){
this.names= names;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater setLayout = LayoutInflater.from(getContext());
View customView = setLayout.inflate(R.layout.settingsname,parent,false);
String setItem = names.get(position);
TextView nameText = (TextView)customView.findViewById(R.id.settingsname);
nameText.setText(setItem);
return customView;
}
}
public class SetupActivity extends AppCompatActivity {
private Context context;
static String extra = "values";
ListView mListView;
private String name;
final String[] setItems = {"name","birthday","size","sex"};
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.setuplist);
mListView = (ListView)findViewById(R.id.listview);
context = this;
Intent intent =getIntent();
name = intent.getStringExtra("name");
setResult(RESULT_OK,intent);
showView();
}
private void showView(){
DogDatabaseHelper dbHelper= new DogDatabaseHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from dog where name = ?",new String[]{name});
//Cursor cursor = db.query("Dog",null,null,null,null,null,null,null);
if(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String birthday = cursor.getString(cursor.getColumnIndex("birthday"));
String size = cursor.getString(cursor.getColumnIndex("size"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
final String[] setValues = {name,birthday,size,sex};
ListAdapter listAdapter = new CustomAdapter(this,setItems,setValues);
mListView.setAdapter(listAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String setupItemValue = setValues[position];
String setupItem = setItems[position];
Intent intent;
if(setupItem.equals("name")){
intent = new Intent(SetupActivity.this,ChangeName.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,1);
} else if(setupItem.equals("birthday")){
intent = new Intent(SetupActivity.this,ChangeBirthday.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,2);
}else if(setupItem.equals("size")){
intent = new Intent(SetupActivity.this,ChangeType.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,3);
}else{
intent = new Intent(SetupActivity.this,ChangeSex.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,4);
}
}
});
}
cursor.close();
}
private void updateView(){
DogDatabaseHelper dbHelper= new DogDatabaseHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Dog",null,null,null,null,null,null,null);
if(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String birthday = cursor.getString(cursor.getColumnIndex("birthday"));
String size = cursor.getString(cursor.getColumnIndex("size"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
final String[] setValues = {name,birthday,size,sex};
ListAdapter listAdapter = new CustomAdapter(this,setItems,setValues);
mListView.setAdapter(listAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String setupItemValue = setValues[position];
String setupItem = setItems[position];
Intent intent;
if(setupItem.equals("name")){
intent = new Intent(SetupActivity.this,ChangeName.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,1);
} else if(setupItem.equals("birthday")){
intent = new Intent(SetupActivity.this,ChangeBirthday.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,2);
}else if(setupItem.equals("size")){
intent = new Intent(SetupActivity.this,ChangeType.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,3);
}else{
intent = new Intent(SetupActivity.this,ChangeSex.class);
intent.putExtra(extra,setupItemValue);
startActivityForResult(intent,4);
}
}
});
}
cursor.close();
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
DogDatabaseHelper dbHelper= new DogDatabaseHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Dog",null,null,null,null,null,null,null);
switch (requestCode){
case 1:
if (resultCode == RESULT_OK){
ContentValues cv = new ContentValues();
cv.put("name",data.getStringExtra("return_name"));
db.update("dog",cv,"id=?",new String[]{"1"});
}
break;
case 2:
if(resultCode == RESULT_OK){
ContentValues cv = new ContentValues();
cv.put("birthday",data.getStringExtra("return_birthday"));
db.update("dog",cv,"id=?",new String[]{"1"});
}
break;
case 3:
if(resultCode == RESULT_OK){
ContentValues cv = new ContentValues();
cv.put("size",data.getStringExtra("return_type"));
db.update("dog",cv,"id=?",new String[]{"1"});
}
break;
case 4:
if(resultCode == RESULT_OK){
ContentValues cv = new ContentValues();
cv.put("sex",data.getStringExtra("return_sex"));
db.update("dog",cv,"id=?",new String[]{"1"});
}
break;
}
db.close();
updateView();
}
}
public class DogDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_DOG = "create table dog ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "birthday text,"
+ "size text,"
+ "sex text,"
+ "count integer)";
private Context context;
public DogDatabaseHelper(Context context){
super(context,"Dog.db",null,1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_DOG);
}
#Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
db.execSQL("drop table if exists Dog");
onCreate(db);
}
public ArrayList<String> getAllNames(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> names = new ArrayList<String>();
Cursor cursor = db.query("Dog",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndex("name"));
names.add(name);
}while (cursor.moveToNext());
}
cursor.close();
return names;
}
}
I can get data from database and I'm able to update data after clicking the name in the ListView, but when I return to this Activity, I don't know how to update the ListView, cause notifyDataSetChanged() didn't work.
Have no idea what went wrong, Anyone can help?
Use startActivityForResult() instead of startActivity() to start your SetupActivity:
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(SettingsActivity.this, SetupActivity.class);
intent.putExtra("name", names.get(position));
startActivityForResult(intent, REQUEST_SETUP);
// REQUEST_SETUP is just a private int constant in SettingsActivity
}
Override onActivityResult() in SettingsActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_SETUP:
dataChanged();
break;
// other request codes (if any)
}
}
}
The dataChanged() method:
private void dataChanged() {
// fetch the new data from the DB into your ArrayList
names.clear();
names.addAll(dbHelper.getAllNames());
// update the ListView with the new data
namesAdapter.notifyDataSetChanged();
}
The getAllNames() method in DogDatabaseHelper:
public ArrayList<String> getAllNames() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> names = new ArrayList<>();
Cursor cursor = db.query(TABLE_DOG, new String[]{COLUMN_NAME},
null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
names.add(name);
} while (cursor.moveToNext());
}
cursor.close();
return names;
}
And finally, when you finished your stuff in SetupActivity and inserted/updated the data in the DB, set the result to RESULT_OK and return to SettingsActivity by calling finish():
setResult(RESULT_OK);
finish();
NOTE: for better performance, you could pass the ID(s) of the inserted/updated record(s) from SetupActivity to SettingsActivity in the Intent, so instead of querying all rows by calling getAllNames(), you could just fetch the modified record(s).
I think the easiest and quicker way for you would be to put all this code:
DogDatabaseHelper dbHelper = new DogDatabaseHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select name from dog",null);
// Edit: to reload all data you must first clear the list
names.clear();
if (cursor != null && cursor.moveToFirst()) {
do {
names.add(cursor.getString(cursor.getColumnIndex("name")));
} while (cursor.moveToNext());
// Note: move this out of the bucle to avoid calling it in every iteration
namesAdapter.notifyDataSetChanged();
}
in your MainActivity's onResume() method, so every time you come back you refresh the data.
EDIT: since reloading the data each time the activity calls onResume, I would suggest you also use a flag for the MainActivity to know if there have been changes. Something like:
#Override
protected void onResume() {
super.onResume();
if (thereWereChanges) {
realoadDataSet();
}
}

Listview gets popuplated from the database everytime I start the activity

I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}

Nullpointer exception while using SQLite

I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,
Error in this line
if (c1 != null & c1.getCount() != 0) {
MAinActivity.java
public class MainActivity extends Activity {
private ListView upcominglist;
private ListView todays;
private ListView eventhistory;
private ImageView addnewevent;
public ArrayList<ContactListItems> contactList;
public ContactListItems contactListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upcominglist=(ListView)findViewById(R.id.listview_upcoming);
todays=(ListView)findViewById(R.id.listview_todays);
eventhistory=(ListView)findViewById(R.id.listview_eventhistory);
addnewevent=(ImageView)findViewById(R.id.addneweventbutton);
addnewevent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
startActivity(intent);
}
});
contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
else
{
c1.close();
}
c1.close();
String first=contactListItems.getSlno();
System.out.println("First" + first);
String second=contactListItems.getNameofevent();
System.out.println("SEcond"+second);
String third=contactListItems.getDtofevent();
System.out.println("Third"+third);
String fourth=contactListItems.getTimeofevent();
System.out.println("Fourth"+fourth);
String fifth=contactListItems.getDuration();
System.out.println("Fifth"+fifth);
}
Addnewevent.java
public class AddNewEvent extends Activity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
static final int TIME_PICKER_ID = 11111;
int flag = 0;
private ImageView addnewdata;
private LinearLayout lnr;
private Button submit;
private EditText edtnmofevent;
private EditText edtdtofevent;
private EditText edttmofevent;
private EditText edtdurationofevent;
SqlHandler sqlHandler;
private ImageView datepicks;
private ImageView timepicks;
private Calendar cal;
private int hour;
private int min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_event);
sqlHandler = new SqlHandler(getApplicationContext());
addnewdata = (ImageView) findViewById(R.id.addnewdata);
submit = (Button) findViewById(R.id.btnsubmit);
edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);
datepicks = (ImageView) findViewById(R.id.calndrdat);
timepicks = (ImageView) findViewById(R.id.timepickrs);
cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(TIME_PICKER_ID);
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
.append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
try {
testDate1 = sdf123.parse(abs1);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
edtdtofevent.setText(DateFormat);
edtdtofevent.setFocusable(false);
edtdtofevent.setInputType(InputType.TYPE_NULL);
datepicks.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
addnewdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AddNewEvent.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
lnr = (LinearLayout) findViewById(R.id.addnewlinear);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(25, 0, 0, 0);
TextView valueTV = new TextView(AddNewEvent.this);
// valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
valueTV.setText(userInput.getText());
valueTV.setLayoutParams(lp);
valueTV.setTextSize(18);
valueTV.setTextColor(Color.parseColor("#2d6cae"));
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(25, 0, 25, 0);
lp1.height = 50;
EditText edtvalues = new EditText(AddNewEvent.this);
edtvalues.setBackgroundResource(R.drawable.rect_edt);
edtvalues.setLayoutParams(lp1);
lnr.addView(valueTV);
lnr.addView(edtvalues);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
startActivity(intent);
String nameofevent = edtnmofevent.getText().toString();
String dtofevent = edtdtofevent.getText().toString();
String timeofevent = edttmofevent.getText().toString();
String duration = edtdurationofevent.getText().toString();
String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
+ nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
sqlHandler.executeQuery(query);
System.out.println("Querys" + query);
}
});
}
SQL
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "nameofevent";
public static final String COLUMN3 = "dtofevent";
public static final String COLUMN4 = "timeofevent";
public static final String COLUMN5 = "duration";
/* public static final String COLUMN6 = "dlabl";
public static final String COLUMN7 = "dedt";*/
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + COLUMN1
+ " integer primary key autoincrement, " + COLUMN2
+ " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:
if (c1 != null & c1.getCount() != 0)
You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.
There is too much here to explain it all, so I will give you the flaws causing a null pointer exception.
I can see your method of programming is coming from worrying too much about closing things and clearing up
resources to a point, it's causing problems.
contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
// Move to the first entry.
c1.moveToFirst();
//if (c1.moveToNext()) {
// do {
// Continue while it has not passed the last entry.
while (!cursor.isAfterLast())
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
// Move the cursor along to the next entry.
cursor.moveToNext();
}
}
// Close cursor after while and within if (so you know it is not null).
c1.close();
}
else
{
// You can't close c1 if it is Null. This will throw and error. Lose the else.
c1.close();
}
// Move this to within your if statment.
c1.close();
From your code you provided in the chat.
Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.
public static Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (sqlDatabase.isOpen()) {
// You are closing the database.
sqlDatabase.close();
}
sqlDatabase = dbHelper.getWritableDatabase();
c1 = sqlDatabase.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.

How to check if database is empty in SQLite Android with DatabaseConnector class

I have a DatabaseConnector class where I want to check if the database is empty and then show an alert and a click on it will close the activity.
This is my DatabaseConnector class
public class DatabaseConnector {
// Declare Variables
private static final String DB_NAME = "MyNotes";
private static final String TABLE_NAME = "tablenotes";
private static final String TITLE = "title";
private static final String ID = "_id";
private static final String NOTE = "note";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase database;
private DatabaseHelper dbOpenHelper;
public static final String MAINCAT = "maincat";
public static final String SUBCAT = "subcat";
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseHelper(context, DB_NAME, null,
DATABASE_VERSION);
}
// Open Database function
public void open() throws SQLException {
// Allow database to be in writable mode
database = dbOpenHelper.getWritableDatabase();
}
// Close Database function
public void close() {
if (database != null)
database.close();
}
// Create Database function
public void InsertNote(String title, String note , String maincat, String subcat) {
ContentValues newCon = new ContentValues();
newCon.put(TITLE, title);
newCon.put(NOTE, note);
newCon.put(MAINCAT, maincat);
newCon.put(SUBCAT, subcat);
open();
database.insert(TABLE_NAME, null, newCon);
close();
}
// Update Database function
public void UpdateNote(long id, String title, String note) {
ContentValues editCon = new ContentValues();
editCon.put(TITLE, title);
editCon.put(NOTE, note);
open();
database.update(TABLE_NAME, editCon, ID + "=" + id, null);
close();
}
// Delete Database function
public void DeleteNote(long id) {
open();
database.delete(TABLE_NAME, ID + "=" + id, null);
close();
}
// List all data function
//String selection = dbOpenHelper.MAINCAT + " = 'quiz'"
// +" AND " + dbOpenHelper.SUBCAT + " = 'test'";
// public Cursor ListAllNotes() {
// return database.query(TABLE_NAME, new String[] { ID, TITLE }, null,
// null, null, null, TITLE);
// }
public Cursor ListAllNotes(String selection) {
return database.query(TABLE_NAME, new String[] { ID, TITLE }, selection,
null, null, null, TITLE);
}
// Capture single data by ID
public Cursor GetOneNote(long id) {
return database.query(TABLE_NAME, null, ID + "=" + id, null, null,
null, null);
}
And here is the ListActivity wherein I want to close the Activity with an alert
public class dbMainactivty extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t.setScreenName("dbMainactivty");
t.send(new HitBuilders.AppViewBuilder().build());
// Locate ListView
noteListView = getListView();
// setContentView(R.layout.list_note);
//noteListView = (ListView) findViewById(R.id.listview);
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[] { TITLE };
int[] to = new int[] { R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(dbMainactivty.this,
R.layout.list_note, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(dbMainactivty.this, ViewNote.class);
// Pass the ROW_ID to ViewNote activity
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStop(this);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent2);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
//i.putExtra(Intent.EXTRA_TEXT, feed.getItem(pos).getTitle().toString()+ " to know the answer download http://developer.android.com/index.html");
i.setType("text/plain");
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
};
// GetNotes AsyncTask
private class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(dbMainactivty.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes("maincat LIKE 'quiz' AND subcat LIKE 'test'");
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
dbConnector.close();
}
}
#Override
protected void onStart() {
super.onStart();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Please check your Internet Connection.")
.setTitle("tilte")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
Cursor cursor = noteAdapter.getCursor();
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
//do your action
//Fetch your data
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
Toast.makeText(getBaseContext(), "Yipeee!", Toast.LENGTH_SHORT).show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"oops nothing pinned yet! ....")
.setTitle("title")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
}
}
}
}
I am trying to check
cursor != null && cursor.getCount()>0 and if it turns false then show the alert that
nothing has been pinned yet
Should show up however even though if the cursor returns data the alert still shows up.
First step, take a look at the lifecycle of your activity: http://www.android-app-market.com/wp-content/uploads/2012/03/Android-Activity-Lifecycle.png
As you can see onResume() is called after onStart() which means that checking the cursor on the onStart() can not work.
Secondly you are starting an AsyncTask (GetNotes) on the onResume() method which means you are running a parallel thread at this point and can't check for the result after calling new GetNotes().execute((Object[]) null);
Your problem is you need to check the emptiness of your cursor (cursor != null && cursor.getCount()>0) AFTER the data is loader which mean after the AsyncTask has completed. In other words, move the check for emptiness on your cursor inside the onPostExecute(Cursor result) method.

Delete a row from SQLite DataBase doesn't work

I'm showing data from a database in a list view and I want to delete one entry when the user do a longclick in one row and then selects "yes" in a Dialog. I have all the code and it compiles but it isn't deleting anything. Any suggestion? Thanks
That's the code of the listview:
public class Consult extends FragmentActivity {
private ListView list;
private SQLiteDatabase db;
private int id = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.consult);
list = (ListView)findViewById(R.id.list);
this.getIntent();
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
db = apeironsdb.getWritableDatabase();
String[] campos = new String[]{"_id", "name", "kind_place", "score"};
Cursor c = db.query("Apeirons", campos, null, null, null, null, null);
c.moveToFirst();
String[] from = new String[]{"name", "kind_place", "score"};
int [] to = new int[] {R.id.Titulo, R.id.SubTitulo};
//#SuppressWarnings("deprecation")
MyListAdapter myadapter = new MyListAdapter (this,
R.layout.entrys, c, from, to);
list.setAdapter(myadapter);
list.setLongClickable(true);
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
saveID(index);
//db.delete("Apeirons", "_id=" + String.valueOf(index), null);
Log.d("ONCLICK", String.valueOf(index));
Log.d("ONCLICK", String.valueOf(id));
callDialog();
return false;
}
});
}
public void callDialog(){
Log.d("DIALOG", String.valueOf(id));
FragmentManager fragmentmanager = getSupportFragmentManager();
SimpleDialog dialog = new SimpleDialog();
dialog.saveIndex(id);
//SimpleDialog.newInstance(id);
dialog.show(fragmentmanager, "tag");
Log.d("erase", "salgo del callDialog");
}
public void saveID(int ID){
id = ID;
}
And that's the code of the Dialog:
public class SimpleDialog extends DialogFragment {
private SQLiteDatabase dbs;
int ID;
#Override
public Dialog onCreateDialog (Bundle savedInstanceState){
//ID = getArguments().getInt("id");
ApeironsSQLiteHelper apeironsdbs = new ApeironsSQLiteHelper(getActivity(),
"DBApeirons.DB", null, 1);
dbs = apeironsdbs.getWritableDatabase();
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.EraseDialogMessage);
builder.setTitle(R.string.app_name);
builder.setPositiveButton(R.string.EraseDialogPButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String args = String.valueOf(ID);
Log.d("Yes BUTTON", args);
/*String sql = "DELETE FROM Apeirons WHERE _id=" + args;
dbs.execSQL(sql);*/
//int prueba = dbs.delete("Apeirons", " _id = ?" + args, null);
int prueba = dbs.delete("Apeirons", "_id = ?", new String[] { "" + args });
Log.d("RETORNO DELETE", String.valueOf(prueba));
}
});
builder.setNegativeButton(R.string.EraseDialogNButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
public void saveIndex(int index){
ID = index;
}
}
I fixed!!! The problem was that I was using the id of the listview and it isn't the same in the database. Now I recover first the _id of the database and works perfect. Thank you for all the answers. The code to recover the _id of database below (maybe is useful to someone):
list.setLongClickable(true);
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
c.moveToPosition(index);
int id = c.getInt(c.getColumnIndex("_id"));
saveID(id);
Log.d("ONCLICK", String.valueOf(index));
Log.d("ONCLICK", String.valueOf(id));
callDialog();
return false;
}
});
You can try
private SQLiteDatabase dbs;
String args = String.valueOf(ID);
Delete query:
Method 1:
dbs = apeironsdbs.getWritableDatabase();
String deleteQuery = "DELETE FROM Apeirons where _id='"+ args +"'";
dbs .execSQL(deleteQuery);
Or you can use
Method 2:
ApeironsSQLiteHelper apeironsdb = new ApeironsSQLiteHelper(this, "DBApeirons.DB", null, 1);
apeironsdb .delete(Apeirons, _id+"="+ID, null); // ID is int value
Try change this line:
int prueba = dbs.delete("Apeirons", " _id = ?" + args, null);
into
int prueba = dbs.delete("Apeirons", " _id = \"" + args + "\"", null);

Categories

Resources