I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview.
Now I want to delete values by position (for example, if i click listview's 4th item i would to delete full this items)
This is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
My Adapter Code:
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and my Main Java code:
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
int a;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
a = Integer.parseInt(holder.counter.getText().toString());
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
dbHelper.close();
cAdapter.notifyDataSetChanged();
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
cAdapter.notifyDataSetChanged();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
I found one example about how to delete title but it's not working.
How could I delete user by position in listview 'onclick' listener?
Any help would be great, thanks
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
You'll need to use the table name here, if all else is correct.
Related
I can make my database save images. They are display in the listView
but when i close the app, the data are erased.
DataBaseHandler.java:
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "Preguntas_y_Respuestas_Manager",
TABLE_PyR = "PreguntasYRespuestas",
KEY_ID = "id",
KEY_PREGUNTA = "pregunta",
KEY_RESPUESTA = "respuesta",
KEY_IMAGEURI = "imagen";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_PyR + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PREGUNTA + " TEXT," + KEY_RESPUESTA + " TEXT, " + KEY_IMAGEURI + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PyR);
onCreate(db);
}
public void createPregunta_y_Respuesta(PreguntasYRespuestas pYr) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PREGUNTA, pYr.getPregunta());
values.put(KEY_RESPUESTA, pYr.getRespuesta());
values.put(KEY_IMAGEURI,pYr.get_imageUri().toString());
db.insert(TABLE_PyR, null, values);
db.close();
}
public PreguntasYRespuestas getPyR(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_PyR, new String[]{KEY_ID, KEY_PREGUNTA, KEY_RESPUESTA, KEY_IMAGEURI}, KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
PreguntasYRespuestas preg_y_resp = new PreguntasYRespuestas(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Uri.parse(cursor.getString(3)));
db.close();
return preg_y_resp;
}
public void deletePregunta(PreguntasYRespuestas pyr) {
SQLiteDatabase db = getWritableDatabase();
int cant = db.delete("PreguntasYRespuestas", "id=" + KEY_ID, null);
}
public int getPreguntasCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PyR, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int UpdatePregunta(PreguntasYRespuestas pyr) {
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PREGUNTA, pyr.getPregunta());
values.put(KEY_RESPUESTA, pyr.getRespuesta());
values.put(KEY_IMAGEURI, pyr.get_imageUri().toString());
int rowsAffected = db.update(TABLE_PyR, values, KEY_ID + "=?", new String[]{String.valueOf(pyr.getId())});
db.close();
return rowsAffected;
}
public List<PreguntasYRespuestas> getAllPreguntas() {
List<PreguntasYRespuestas> pyr = new ArrayList<PreguntasYRespuestas>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_PyR, null);
if (cursor.moveToFirst()) {
do {
pyr.add(new PreguntasYRespuestas(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),Uri.parse(cursor.getString(3))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return pyr;
}
}
RegistroDePreguntas_Cuestionario.java:
public class RegistroDePreguntas_Cuestionario extends AppCompatActivity {
private static final int EDIT = 0, DELETE = 1;
public Button agregar, iniciar;
public ImageView imagen;
public EditText et_pregunta, et_respuesta;
public ListView listView_preguntas;
Uri imageUri = null;
DataBaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<PreguntasYRespuestas> preguntasAdapter;
List<PreguntasYRespuestas> mListaPreguntas = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro_de_preguntas__cuestionario);
agregar = (Button) findViewById(R.id.agregar);
et_pregunta = (EditText) findViewById(R.id.Et_pregunta);
et_respuesta = (EditText) findViewById(R.id.Et_respuesta);
imagen = (ImageView)findViewById(R.id.imageView);
iniciar = (Button) findViewById(R.id.iniciar);
listView_preguntas = (ListView) findViewById(R.id.listview_preguntas);
dbHandler = new DataBaseHandler(getApplicationContext());
TabHost tabHost = (TabHost) findViewById(R.id.tabHost_Preg_Cuest);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.Creador);
tabSpec.setIndicator("Crear");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("visualizacion");
tabSpec.setContent(R.id.Visualizacion);
tabSpec.setIndicator("Ver");
tabHost.addTab(tabSpec);
registerForContextMenu(listView_preguntas);
listView_preguntas.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
iniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegistroDePreguntas_Cuestionario.this, ActivityCuestionario.class));
}
});
agregar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PreguntasYRespuestas pyr = new PreguntasYRespuestas(dbHandler.getPreguntasCount(), String.valueOf(et_pregunta.getText()), String.valueOf(et_respuesta.getText()),imageUri);
if (!preguntaExists(pyr)) {
dbHandler.createPregunta_y_Respuesta(pyr);
mListaPreguntas.add(pyr);
preguntasAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Tu pregunta ha sido añadida", Toast.LENGTH_SHORT).show();
et_pregunta.setText("");
et_respuesta.setText("");
imageUri = null;
return;
}
Toast.makeText(getApplicationContext(), "Ya existe una pregunta igual, no pueden haber 2 preguntas iguales", Toast.LENGTH_SHORT).show();
}
});
imagen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Contact Image"),1);
}
});
et_pregunta.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
agregar.setEnabled(String.valueOf(et_pregunta.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (dbHandler.getPreguntasCount() != 0) {
mListaPreguntas.addAll(dbHandler.getAllPreguntas());
populateList();
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.edit);
//Icon made by [http://www.flaticon.com/authors/madebyoliver] from www.flaticon.com
menu.setHeaderTitle("Opciones");
menu.add(Menu.NONE, DELETE, menu.NONE, "Eliminar pregunta");
}
public void onActivityResult(int reqCode, int resCode, Intent data){
if (resCode==RESULT_OK){
if (reqCode==1){
imageUri = data.getData();
imagen.setImageURI(data.getData());
}
}
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EDIT:
dbHandler.UpdatePregunta(mListaPreguntas.get(longClickedItemIndex));
preguntasAdapter.notifyDataSetChanged();
break;
case DELETE:
dbHandler.deletePregunta(mListaPreguntas.get(longClickedItemIndex));
mListaPreguntas.remove(longClickedItemIndex);
preguntasAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean preguntaExists(PreguntasYRespuestas pyr) {
String pregunta = pyr.getPregunta();
int preguntaCount = mListaPreguntas.size();
for (int i = 0; i < preguntaCount; i++) {
if (pregunta.compareToIgnoreCase(mListaPreguntas.get(i).getPregunta()) == 0)
return true;
}
return false;
}
public void populateList() {
preguntasAdapter = new mListAdapter();
listView_preguntas.setAdapter(preguntasAdapter);
}
public class mListAdapter extends ArrayAdapter<PreguntasYRespuestas> {
public mListAdapter() {
super(RegistroDePreguntas_Cuestionario.this, R.layout.listview_item, mListaPreguntas);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
PreguntasYRespuestas currentPregunta = mListaPreguntas.get(position);
TextView tv_pregunta = (TextView) view.findViewById(R.id.tv_pregunta);
tv_pregunta.setText(currentPregunta.getPregunta());
TextView tv_respuesta = (TextView) view.findViewById(R.id.tv_respuesta);
tv_respuesta.setText(currentPregunta.getRespuesta());
ImageView imageView_Lista = (ImageView) view.findViewById(R.id.imageView_Lista);
imageView_Lista.setImageURI(currentPregunta.get_imageUri());
return view;
}
}
}
I apologize for conversation.
I am using Google Translator.
I am writing an application that displays text messages with specific numbers.
The numbers stored in the application's user.
*** My problem is that my app does not work on Android 4.4 and above.
Basically what I Should do ? thanks.
My step-by-step program :
Incoming sms:
public class IncomingSms extends BroadcastReceiver {
SmsManager smsManager = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentmessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentmessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentmessage.getDisplayMessageBody();
Log.i("payam", "senderNum=" + senderNum + " | msg=" + message);
DBAdapter db = new DBAdapter(context);
db.open();
List<sh_number> blocknumbers = db.getAllNUMBERItem();
db.close();
for (sh_number thisblocknumber : blocknumbers) {
if (senderNum.equals(thisblocknumber.getnumber())) {
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}
/*if(senderNum.equals("5554")){
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}else {
Toast.makeText(context, "senderNum="+senderNum+" | msg="+message,Toast.LENGTH_LONG).show();
}*/
}
}
}
}
NumberListAdapter :
public class NumberListAdapter extends ArrayAdapter<sh_number> {
List<sh_number> AllNumbers;
Context c;
public NumberListAdapter(Context c, List<sh_number> numbrs){
super(c, android.R.id.content, numbrs);
AllNumbers = numbrs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_number, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getname());
txt = (TextView)convertView.findViewById(R.id.Itm_number);
txt.setText(AllNumbers.get(position).getnumber());
return convertView;
}
MassageListAdapter :
public class MsgListAdapter extends ArrayAdapter<sh_msg> {
List<sh_msg> AllNumbers;
Context c;
public MsgListAdapter(Context c, List<sh_msg> msgs){
super(c, android.R.id.content, msgs);
AllNumbers = msgs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_msg, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getnumber());
txt = (TextView)convertView.findViewById(R.id.Itm_msg);
txt.setText(AllNumbers.get(position).getText());
txt = (TextView)convertView.findViewById(R.id.Itm_date);
txt.setText(AllNumbers.get(position).getDate());
return convertView;
}
Database :
public class DBAdapter {
public static final String DATABASE_NAME = "smsblkrdb";
static final int DATABASE_VERSION = 1;
static final String CREATE_MSGTABLE = "CREATE TABLE msgsTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" numberid integer(128),\n" +
"\"text\" text(128),\n" +
" date text(128)\n" +
");";
public static final String DATABASE_MSGTABLE = "msgsTable";
public static final String KEY_ID = "id";
public static final String KEY_NUMBERID = "numberid";
public static final String KEY_TEXT = "text";
public static final String KEY_DATE = "date";
static final String CREATE_NUMBERSTABLE = "CREATE TABLE numbersTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" name text(128),\n" +
" number text(128)\n" +
");";
public static final String DATABASE_NUMBERSTABLE = "numbersTable";
public static final String KEY_NAME = "name";
public static final String KEY_NUMBER = "number";
public static final String TAG = "EsfanduneLrn";
DatabaseHelper DBHelper;
final Context context;
SQLiteDatabase db;
String yek_Msgnam[] = {
KEY_ID, KEY_NUMBERID, KEY_TEXT, KEY_DATE
};
String yek_Numbernam[] = {
KEY_ID, KEY_NAME, KEY_NUMBER
};
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_MSGTABLE);
db.execSQL(CREATE_NUMBERSTABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_MSGTABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NUMBERSTABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close() {
DBHelper.close();
}
//---insert a contact into the database---
public long insertSH_MSG(sh_msg thisMsg) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisMsg.getId()));
initialValues.put(KEY_NUMBERID, thisMsg.getnumber());
initialValues.put(KEY_TEXT, thisMsg.getText());
initialValues.put(KEY_DATE, thisMsg.getDate());
return db.insert(DATABASE_MSGTABLE, null, initialValues);
}
public long insertSH_NUMBER(sh_number thisNumbr) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisNumbr.getId()));
initialValues.put(KEY_NUMBER, thisNumbr.getnumber());
initialValues.put(KEY_NAME, thisNumbr.getname());
return db.insert(DATABASE_NUMBERSTABLE, null, initialValues);
}
//---retrieves all the contacts---
public List<sh_msg> getAllMSGItem() {
Cursor cursor = db.query(DATABASE_MSGTABLE, yek_Msgnam, null, null, null, null, null);
List<sh_msg> nams = cursorToList_SHMSG(cursor);
cursor.close();
return nams;
}
private List<sh_msg> cursorToList_SHMSG(Cursor cursor) {
List<sh_msg> nams = new ArrayList<sh_msg>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_msg nam = new sh_msg();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBERID)));
nam.setText(cursor.getString(cursor.getColumnIndex(KEY_TEXT)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public List<sh_number> getAllNUMBERItem() {
Cursor cursor = db.query(DATABASE_NUMBERSTABLE, yek_Numbernam, null, null, null, null, null);
List<sh_number> nams = cursorToList_SHNUMBER(cursor);
cursor.close();
return nams;
}
private List<sh_number> cursorToList_SHNUMBER(Cursor cursor) {
List<sh_number> nams = new ArrayList<sh_number>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_number nam = new sh_number();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setname(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBER)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public void removeNumber(int numberId) {
db.delete(DATABASE_NUMBERSTABLE, KEY_ID +" == "+numberId,null);
}
I am developing an app for listing details in database. The listing is not working. but it is showing in log as fine. Why my recyclerview listling is not working. when i am using bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()) it shows error.
My codes are shown below.
SpeedDialViewActivity.java
public class SpeedDialViewActivity extends AppCompatActivity {
private List<Bean> beanList = new ArrayList<>();
private RecyclerView recyclerView;
private ViewAdapter mAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_dial_view);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ViewAdapter(beanList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareData();
}
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "speeddial";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_SPEED_DIAL = "speed_dial_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_SPEED_DIAL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
void addContact(Bean bean) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, bean.getName()); // Contact Name
values.put(KEY_PH_NO, bean.getNumber()); // Contact Phone
values.put(KEY_PH_NO, bean.getSpeeddial()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Bean getBean(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Bean bean = new Bean(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return bean;
}
public List<Bean> getAllContacts() {
List<Bean> contactList = new ArrayList<Bean>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bean contact = new Bean();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
ViewAdapter.java
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder> {
private List<Bean> beanList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, number, speeddial_number;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
number = (TextView) view.findViewById(R.id.number);
speeddial_number = (TextView) view.findViewById(R.id.speeddialNumber);
}
}
public ViewAdapter(List<Bean> beanList){
this.beanList = beanList;
}
#Override
public ViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.speeddial_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewAdapter.MyViewHolder holder, int position) {
Bean bean = beanList.get(position);
holder.name.setText(bean.getName());
holder.number.setText(bean.getNumber());
holder.speeddial_number.setText(bean.getSpeeddial());
}
#Override
public int getItemCount() {
return beanList.size();
}
}
Bean.java
public class Bean{
private int id;
private String name;
private String number;
private String speeddial;
public Bean(int id, String name, String number, String speeddial) {
this.id=id;
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean(String name, String number, String speeddial) {
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getSpeeddial() {
return speeddial;
}
public void setSpeeddial(String speeddial) {
this.speeddial = speeddial;
}
}
The error is java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.appname/com.app.appname}: java.util.ConcurrentModificationException
Please help me
You are not adding the contacts you are fetching in the list and not doing notify data set changed. Change your onPrepare() method as follows
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
this.beanList.addAll(beanList);
mAdapter.notifyDatasetChanged();
}
pass the same list in prepareData(beanList) and add items in this list. And change your method to something likeprepareData(List<Bean> beanList>).after successfully adding, simply call mAdapter.notifyDataSetChanged() method so your adapter could know that some items have been added into the list.
You have not mention android:name in application tag in manifest file.
So you simple use context object or use SpeedDialViewActivity.this
DatabaseHandler handler = new DatabaseHandler(mContext);
or
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
Thanks in advance for helping me out. This is my first time working on SQLite Database as well as creating an app.
Problem: When I click save"ImageButton" on the AddEntry.xml for some reason its not displaying on my listview which is located in my Fragment Home.xml. I found fragments to be a tad difficult since you have to change the code around in order for it to work. so please excuse if my code is all over the place.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener
{
EditText DescriptionET,CalorieET;
ImageButton Savebtn, Cancelbtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry,
container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
descriptionET.setText("");
EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
calorieET.setText("");
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER =
"section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private View v;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home,
container, false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain)getActivity()).loadSelection(1);
}
});
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView)
getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
listview = (ListView) getActivity().findViewById(R.id.listViewDB);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber -
FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new
SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
closeDataBase();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
// Constants & Data
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[]
{KEY_ROWID, KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Thanks again for helping me out. I've been stressing for the last couple of days trying to figure it out.
The delete method of my sql database doesn't remove the entry from the database. It gives a null pointer exception:
10-18 00:44:25.069: E/AndroidRuntime(17968): java.lang.NullPointerException
10-18 00:44:25.069: E/AndroidRuntime(17968): at com.weather.app.LocationDB.deleteLocation(LocationDB.java:98)
public class LocationDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "locationManager";
private static final String TABLE_LOCATIONS = "locations";
private static final String KEY_ID = "id";
private static final String KEY_LOCATION = "location";
private static final String KEY_COUNTRY = "country";
private SQLiteDatabase db;
public LocationDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_LOCATIONS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCATION
+ " TEXT, " + KEY_COUNTRY
+ " TEXT, " + " INTEGER)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
onCreate(db);
}
public void addLocation(LocationName location) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LOCATION, location.getTaskName());
values.put(KEY_COUNTRY, location.getTaskCountry());
db.insert(TABLE_LOCATIONS, null, values);
}
public List<LocationName> getAllLocations() {
List<LocationName> locList = new ArrayList<LocationName>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LOCATIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
LocationName task = new LocationName();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setTaskCountry(cursor.getString(2));
// Adding contact to list
locList.add(task);
} while (cursor.moveToNext());
}
return locList;
}
public boolean deleteLocation(long rowId) {
return db.delete(TABLE_LOCATIONS, KEY_ID + "=" + rowId, null) > 0;
}
}
Then entry is not removed even when the app is restarted, the addLocation method for adding a row works fine.
LocationSettings Activity:
public class LocationSettings extends Activity {
protected static LocationDB db;
static List<LocationName> list;
MyAdapter adapt;
private static TextView name;
private ListView listView;
private static final int DLG_EXAMPLE1 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_settings);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
db = new LocationDB(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.drawer_list_item, list);
listView = (ListView) findViewById(R.id.left_drawer);
listView.setAdapter(adapt);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
db.deleteTask(position);
adapt.remove(adapt.getItem(position));
}
}
});
listView.setOnItemClickListener(new DrawerItemClickListener());
listView.setOnTouchListener(touchListener);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
db.deleteTask(position);
adapt.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<LocationName> {
Context context;
List<LocationName> taskList = new ArrayList<LocationName>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<LocationName> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.drawer_list_item,parent, false);
name = (TextView) convertView.findViewById(R.id.text1);
}
LocationName current = taskList.get(position);
name.setText(current.getTaskName());
return convertView;
}
}
}
you forget to initialize db before calling delete method in deleteLocation.
public int deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) });
}
Using the suggested following fragment of code from #ρяσѕρєяK:
public int deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) });
}
has changed the signature of your method generating that error. I think that
public boolean deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) }) > 0;
}
will solve your problem.