How to update row in CursorAdapter properly - android

I have a trouble with my CursorAdapter data updating.
When I press on the "star" img of listview row item i needs to get changes in DB column "isFav" (0 to 1 and vice versa) and show completed star or free star(favorite checkbox e.g.).
But when I pressing on the star - current row star is not updating, but last of showed rows get affected, like as I press on it. Screenshot: http://tinypic.com/r/2eph8uf/5
The following code is placing below:
private class MyAdapter extends CursorAdapter {
private LayoutInflater mLayoutInflater;
public MyAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
}
News tmp = new News(0,0,null,null,0,0);
#Override
public void bindView(View v, Context context, Cursor c) {
tmp.setName(c.getString(c.getColumnIndexOrThrow(dbHelper.NAME)));
tmp.setDescr(c.getString(c.getColumnIndexOrThrow(dbHelper.DESCRIPTION)));
tmp.setPubdate(c.getLong(c.getColumnIndexOrThrow(dbHelper.DATE)));
tmp.setGuid(c.getInt(c.getColumnIndexOrThrow(dbHelper.UID)));
tmp.setIsFav(c.getInt(c.getColumnIndexOrThrow(dbHelper.IS_FAV)));
tmp.setIsRead(c.getInt(c.getColumnIndexOrThrow(dbHelper.IS_READ)));
TextView title_text = (TextView) v.findViewById(R.id.text);
if (title_text != null) {
title_text.setText(tmp.getName() + " " + convertLongToDate(tmp.getPubdate()));
}
title_text.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent _intent = new Intent(getActivity(), ItemActivity.class);
_intent.putExtra("title", tmp.getName() + " " + Long.toString(tmp.getPubdate()));
_intent.putExtra("desc", tmp.getDescr());
startActivity(_intent);
if (tmp.getIsRead() == 1)
return;
tmp.setIsRead(1);
//working wrong!
ContentValues cv = getContValues(tmp);
loader.update(dbHelper.DATABASE_NAME, cv, dbHelper.UID + "=" + cv.getAsInteger("_id"), null);
// db.UpdateItem(db.getWritableDatabase(), tmp);
// getLoaderManager().initLoader(0, null, mCallbacks);
}
});
final ImageView fav_img = (ImageView) v.findViewById(R.id.image);
if (fav_img != null)
{
if (tmp.getIsFav() != 0) {
fav_img.setImageResource(R.drawable.fav);
}
else fav_img.setImageResource(R.drawable.unfav);
}
fav_img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (tmp.getIsFav() == 1)
{
tmp.setIsFav(0);
fav_img.setImageResource(R.drawable.unfav);
}
else
{
tmp.setIsFav(1);
fav_img.setImageResource(R.drawable.fav);
}
Log.d("fav:", Integer.toString(tmp.getIsFav()) + " id: " + Integer.toString(tmp.getGuid()));
// db.UpdateItem(db.getWritableDatabase(), tmp);
// getLoaderManager().restartLoader(0, null, mCallbacks);
//Working wrong!
ContentValues cv = getContValues(tmp);
loader.update(dbHelper.DATABASE_NAME, cv, dbHelper.UID + "=" + cv.getAsInteger("_id"), null);
}
});
LinearLayout lay = (LinearLayout) v.findViewById(R.id.item_layout);
if (tmp.getIsRead() != 0)
lay.setBackgroundColor(Color.GRAY);
else lay.setBackgroundColor(Color.YELLOW);
}
private ContentValues getContValues(News tmp)
{
ContentValues cv = new ContentValues();
cv.put("_id", tmp.getGuid());
cv.put("title", tmp.getName());
cv.put("pubdate", tmp.getPubdate());
cv.put("description", tmp.getDescr());
cv.put("isRead", tmp.getIsRead());
cv.put("isFav", tmp.getIsFav());
return cv;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mLayoutInflater.inflate(R.layout.list_item, parent, false);
return v;
}
private String convertLongToDate(long value)
{
Locale l = new Locale("ru");
//if (l.getCountry())
Date d = new Date(value);
SimpleDateFormat df = new SimpleDateFormat("d M", l);
return new String(df.format(d));
}
}

Just do this adjustments:
final ImageView fav_img = (ImageView) v.findViewById(R.id.image);
Boolean is_favourite = false;
if (fav_img != null)
{
if (tmp.getIsFav() != 0) {
fav_img.setImageResource(R.drawable.fav);
}
else fav_img.setImageResource(R.drawable.unfav);
}
fav_img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (is_favourite) // if your row is already favourite
{
is_favourite=false;
fav_img.setImageResource(R.drawable.unfav);
}
else
{
is_favourite= true;
fav_img.setImageResource(R.drawable.fav);
}
//Log.d("fav:", Integer.toString(tmp.getIsFav()) + " id: " + Integer.toString(tmp.getGuid()));
// db.UpdateItem(db.getWritableDatabase(), tmp);
// getLoaderManager().restartLoader(0, null, mCallbacks);
//Working wrong!
ContentValues cv = getContValues(tmp);
loader.update(dbHelper.DATABASE_NAME, cv, dbHelper.UID + "=" + cv.getAsInteger("_id"), null);
}
});

Related

Merging cursor only gives back first cursor in clickEvent

Passing the cursor of position clicked but when doing so log is showing me I am getting only the first row no matter where I click.
holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallback != null) {
mCallback.onTopListClick(cursor);
notifyDataSetChanged();
Log.i("FROMCLICK", DatabaseUtils.dumpCursorToString(cursor));
}
}
});
The log inside the CursorAdapter onClickListener is showing only the first rows cursor even if I click 20 rows down the list.
#Override
public void onTopListClick(Cursor cursor) {
Log.i("FistClickBeforePassing", DatabaseUtils.dumpCursorToString(cursor));
BottomFragment bottomFragment = (BottomFragment) getSupportFragmentManager().findFragmentById(R.id.bottomFragment);
bottomFragment.refreshList(cursor);
}
Same thing here before passing to the BottomFragment.
public void refreshList(Cursor cursor) {
Log.i("RIGHTBEFOREREFRESH", DatabaseUtils.dumpCursorToString(cursor));
String mEmployeeNumber = cursor.getString(1);
Log.i("REFRESHLISTNUMBER", mEmployeeNumber);
dbHandler = EmployeeDBHandler.getInstance(getContext());
db = dbHandler.getReadableDatabase();
mNewBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
/*"Employee_number" + "!=" + mStartingEmployeeID + " AND " +*/
"Manager_employee_number" + "=" + mEmployeeNumber + " ORDER BY " +
"Last_name" + " ASC", null);
Log.i("THECURSOR ", DatabaseUtils.dumpCursorToString(mNewBottomCursor));
BottomListCursorAdapter bottomListCursorAdapter = new BottomListCursorAdapter(getActivity(), cursor);
bottomListCursorAdapter.swapCursor(mNewBottomCursor);
mBottomListView.setAdapter(bottomListCursorAdapter);
}
}
Get the same cursor here for the log but do not get the same employee_number the cursor has for the REFRESHLISTNUMBER log statement. That is a random number from the list.
Not sure why the cursor isnt being passed correctly. I have a details button on each row that displays info from the cursor for each row and that is displaying correctly.
Completed Top Adapter
public class TopListCursorAdapter extends CursorAdapter {
public interface TopListClickListener {
void onTopListClick(Cursor cursor);
}
private TopListClickListener mCallback;
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
if(!(context instanceof TopListClickListener)) {
throw new ClassCastException("Content must implement BottomListClickListener");
}
this.mCallback = (TopListClickListener) context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_top, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mTopCardView = (CardView) view.findViewById(R.id.mTopHomeScreenCV);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mPayrollTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mPayrollTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(cursor.getColumnIndex("Employee_number"));
String mFirstName = cursor.getString(cursor.getColumnIndex("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndex("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndex("Payroll_title"));
String mPic = cursor.getString(cursor.getColumnIndex("ThumbnailData"));
String mEmail = cursor.getString(cursor.getColumnIndex("Email"));
String mPhoneMobile = cursor.getString(cursor.getColumnIndex("Phone_mobile"));
String mPhoneOffice = cursor.getString(cursor.getColumnIndex("Phone_office"));
String mCostCenter = cursor.getString(cursor.getColumnIndex("Cost_center_id"));
String mHasDirectReports = cursor.getString(cursor.getColumnIndex("Has_direct_reports"));
String mManagerNumber = cursor.getString(cursor.getColumnIndex("Manager_employee_number"));
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Manager_employee_number", mManagerNumber);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(mIntent);
}
});
holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallback != null) {
mCallback.onTopListClick(cursor);
notifyDataSetChanged();
Log.i("FROMCLICK", DatabaseUtils.dumpCursorToString(cursor));
}
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mTopCardView;
}
}
public class TopFragment extends Fragment {
Cursor mTopCursor;
EmployeeDBHandler dbHandler;
ListView mTopListView;
TopListCursorAdapter mTopAdapter;
MatrixCursor customCursor1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_list, container, false);
String table = "employees";
dbHandler = EmployeeDBHandler.getInstance(getContext());
SQLiteDatabase db = dbHandler.getWritableDatabase();
customCursor1 = new MatrixCursor(new String[]{"_id", "Employee_number", "First_name",
"Last_name", "Payroll_title", "ThumbnailData", "Email", "Phone_mobile", "Phone_office", "Cost_center_id",
"Has_direct_reports", "Manager_employee_number"});
int mStartingEmployeeID = mStartingNumber;
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
mTopListView = (ListView) view.findViewById(R.id.mTopList);
mTopAdapter = new TopListCursorAdapter(getContext(), mTopCursor);
mTopListView.setAdapter(mTopAdapter);
return view;
}
public void update(Cursor cursor) {
if (cursor.moveToNext()) {
customCursor1.addRow(new Object[]{cursor.getInt(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(6), cursor.getString(9), cursor.getString(8), cursor.getString(4),
cursor.getString(5), cursor.getString(10), cursor.getString(7), cursor.getString(11)});
MergeCursor newCursor = new MergeCursor(new Cursor[]{mTopCursor, customCursor1});
mTopAdapter.swapCursor(newCursor);
mTopAdapter.notifyDataSetChanged();
scrollMyListToBottom();
customCursor1.close();
} cursor.moveToNext();
}
private void scrollMyListToBottom() {
mTopListView.post(new Runnable() {
#Override
public void run() {
mTopListView.setSelection(mTopAdapter.getCount() - 1);
}
});
}
}
Maybe something is happening with my MergeCursor in TopFragment that is messing with the curors? If so, not sure how to fix it or why it would be happening.
Fixed by adding a line of code to the setClickListener of the mTopCardView in the TopListCursorAdapter.
cursor.moveToPosition(position);

Android cursor return empty contacts

I need to get all contacts that have at least a phone number. Android contacts may be picked from many accounts like gmail,skype,vibe etc. I made the classes i need to get the contacts i need. My problem that it gets anyway contacts that don't have at least 1 phone number and shows just their name and avatar. Can any1 say what I am doing wrong in my code? My code source is shared below.
ContactsActivity.class
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
selectionString = edtSearch.getText().toString();
String[] selectionArgs = {"%" + selectionString + "%", selectionString + "%", "%" + selectionString};
String selection = ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=='1'";
return new CursorLoader(this,
ContactsContract.Contacts.CONTENT_URI, // URI
null, // projection fields
selection, // the selection criteria
selectionArgs, // the selection args
ContactsContract.Contacts.DISPLAY_NAME + " ASC" // the sort order
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ContactsAdapter.createCheckedContacts(data.getCount());
contactsAdapter.setCursor(data);
contactsAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
contactsAdapter.swapCursor(null);
}
ContactsAdapter.class
public class ContactsAdapter extends CursorAdapter {
static boolean status = true;
private static boolean[] checkedContacts;
private static Context context;
private static Cursor cursor;
public ContactsAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
public static void setCursor(Cursor cursor) {
ContactsAdapter.cursor = cursor;
}
public static void createCheckedContacts(int count) {
checkedContacts = new boolean[count];
}
public static void saveSelectedContacts(ClientDao contactDao) {
for (int i = 0; i < checkedContacts.length; i++) {
if (checkedContacts[i]) {
cursor.moveToPosition(i);
DatabaseHelper.getInstance().saveClient(ContactUtils.cursorToContact(cursor, context), status);
status = !status;
}
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.contact_item, parent, false);
ViewHolder holder = new ViewHolder(convertView);
convertView.setTag(holder);
return convertView;
}
#Override
public void bindView(View convertView, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) convertView.getTag();
final Contact contact = ContactUtils.cursorToContact(cursor, context);
holder.tvName.setText(contact.getDisplayName());
if (isFirst(cursor)) {
holder.tvLetter.setVisibility(View.VISIBLE);
String letter = String.valueOf(Character.toUpperCase(contact.getDisplayName().charAt(0)));
holder.tvLetter.setText(letter);
} else {
holder.tvLetter.setVisibility(View.INVISIBLE);
}
convertView.setTag(convertView.getId(), contact);
if (!TextUtils.isEmpty(contact.getPhotoUri())) {
new ImageLoaderUtils.ContactImage(contact, convertView, holder.ivUserImage, context).execute();
} else {
holder.ivUserImage.setImageResource(R.drawable.ic_profile);
}
holder.inviteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ContactInvitationActivity_.class);
intent.putExtra("contact", contact);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
});
}
private boolean isFirst(Cursor cursor) {
Contact c1 = ContactUtils.cursorToContact(cursor, context);
if (cursor.getPosition() == 0)
return true;
cursor.moveToPrevious();
Contact c2 = ContactUtils.cursorToContact(cursor, context);
if (c1.getDisplayName() == null || c2.getDisplayName() == null)
return false;
if (Character.toUpperCase(c1.getDisplayName().charAt(0)) != Character.toUpperCase(c2.getDisplayName().charAt(0)))
return true;
return false;
}
private static class ViewHolder {
TextView tvName;
TextView tvLetter;
ImageView ivUserImage;
Button inviteBtn;
RelativeLayout rlContact;
private ViewHolder(View convertView) {
tvName = (TextView) convertView.findViewById(R.id.tvContactsName);
tvLetter = (TextView) convertView.findViewById(R.id.tvLetter);
ivUserImage = (ImageView) convertView.findViewById(R.id.ivUserIcon);
inviteBtn = (Button) convertView.findViewById(R.id.inviteBtn);
rlContact = (RelativeLayout) convertView.findViewById(R.id.rlContact);
}
}
}
ContactUtil.class
public class ContactUtils {
public static Contact cursorToContact(Cursor c, Context context) {
if (c == null || c.getPosition() < 0) return null;
Contact contactObj = new Contact();
try {
contactObj.setID(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
contactObj.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contactObj.setPhotoUri(c.getString(c.getColumnIndex(ContactsContract.Contacts.PHOTO_URI)));
contactObj.setPhoneNumber("");
contactObj.setEmail("");
setPhoneNumber(c, contactObj, context);
setEmail(contactObj, context);
} catch (Exception e) {
e.printStackTrace();
}
return contactObj;
}
public static void setPhoneNumber(Cursor c, Contact contactObj, Context context) {
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactObj.getID(), null, null);
phones.moveToFirst();
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
contactObj.setPhoneNumber(phoneNumber);
phones.close();
}
}
public static void setEmail(Contact contactObj, Context context) {
Cursor emailCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactObj.getID()}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contactObj.setEmail(email);
}
emailCur.close();
}
}

How do I get the ID item in the database?

I am new to android development and must take the value of the id in the clicked item database.
Already searched several posts but not found the answer .
Below is my code Listview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleciona_jogador_act);
final BancoController bc = new BancoController(this);
final ArrayList<JogadorEntidade> jogadorEntidade = bc.arrayJogador(this);
listView = (ListView) findViewById(R.id.lvSelecionar);
final SelecionaAdapter adapter = new SelecionaAdapter(this, R.layout.adapter_seleciona, jogadorEntidade);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(background));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertInserirJogador(SelecionaJogadorAct.this);
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//I NEED THIS CODE
Context context = getApplicationContext();
CharSequence text = "ID: " + ", Posicao: " + position;
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
//bc.deletaRegistro(id_player);
Intent intent = getIntent();
SelecionaJogadorAct.this.finish();
startActivity(intent);
}
});
}
My Adapter:
public class SelecionaAdapter extends ArrayAdapter<JogadorEntidade> {
Context context;
int layoutID;
ArrayList<JogadorEntidade> alJogador;
public SelecionaAdapter(Context context, int layoutID, ArrayList<JogadorEntidade> alJogador){
super(context, layoutID, alJogador);
this.context = context;
this.alJogador = alJogador;
this.layoutID = layoutID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlayerHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutID, parent, false);
holder = new PlayerHolder();
holder.txtNome = (TextView)row.findViewById(R.id.txtNomeSelecionar);
holder.txtVitorias = (TextView)row.findViewById(R.id.txtVitóriasSelecionar);
holder.txtDerrotas = (TextView)row.findViewById(R.id.txtDerrotasSelecionar);
row.setTag(holder);
}else {
holder = (PlayerHolder)row.getTag();
}
JogadorEntidade jogadorEntidade = alJogador.get(position);
holder.txtNome.setText(jogadorEntidade.getNome());
holder.txtVitorias.setText("V: " + jogadorEntidade.vitórias);
holder.txtDerrotas.setText("D: " + jogadorEntidade.derrotas);
return row;
}
static class PlayerHolder{
TextView txtNome;
TextView txtVitorias;
TextView txtDerrotas;
}
JogadorEntidade:
public class JogadorEntidade {
public String nome;
public Integer id_jogador;
public String vitórias;
public String derrotas;
public Integer getId_jogador() {
return id_jogador;
}
public void setId_player(int id_player) {
this.id_jogador = id_player;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getVitórias() {
return vitórias;
}
public void setVitórias(String vitórias) {
this.vitórias = vitórias;
}
public String getDerrotas() {
return derrotas;
}
public void setDerrotas(String derrotas) {
this.derrotas = derrotas;
}
public JogadorEntidade(String nome, String vitórias, String derrotas){
super();
this.nome = nome;
this.vitórias = vitórias;
this.derrotas = derrotas;
}
public JogadorEntidade(){}
public void insereJogador(JogadorEntidade jogadorEntidade) {
db = banco.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(banco.NOME_JOGADOR, jogadorEntidade.getNome());
values.put(banco.VITORIAS, jogadorEntidade.getVitórias());
values.put(banco.DERROTAS, jogadorEntidade.getDerrotas());
db.insert(CriaBanco.TABELA_JOGADOR, null, values);
db.close();
}
public Cursor carregaJogador() {
Cursor cursor;
String[] campos = {banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
db = banco.getReadableDatabase();
cursor = db.query(banco.TABELA_JOGADOR, campos, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
db.close();
return cursor;
}
public void deletaRegistro(int id){
String where = CriaBanco.ID_JOGADOR + "=" + id;
db = banco.getReadableDatabase();
db.delete(CriaBanco.TABELA_JOGADOR, where, null);
db.close();
}
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
JogadorEntidade jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
First you need to request the id when making the query (if the id is the one created in the database the column mame is _id or you can use tablename._id or whatever you need):
String[] campos = {"_id", banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
Then you need to add the id to the object when you read the cursor:
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
JogadorEntidade jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
Anyway this is not the way to go in android. You should read all the list and then show it. You should use the viewholder pattern and only load the player when you are going to show it. Also instead of using a list you should move to recyclerviews. Listviews can be consider deprecated at this point. See the tutorial: http://developer.android.com/training/material/lists-cards.html

How to delete a row in SQLiteDatabase - Android Content Provider

I’m struggling to write a method that deletes a row from the SQLiteDatabase. I have a list of songs in a gridview where when a user clicks one of the items from the list the app will take them to my SongDetailFragment activity which contains more information about the song and a star button where if a song in in the database the star button is “switched on”, conversely if the item is NOT in the database the star button is “switched-off”
When a user click the star button I'm able to add a song successfully in the database and my star button is “switched-on”. Now I want to press the same button again and call deleteFromDB() to delete the song that was added to the database. So I have the following code in my onClick:
public void onClick(View v)
{
if (mIsFavourite) {
deleteFromDB();
}
else {
insertData();
mIsFavourite = true;
}
The problem is deleteFromDB() method is not working correctly as I can see that the song is not deleting from the database. I’m not sure what is the correct syntax to fix it.
Here is my method:
private void deleteFromDB() {
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.SongEntry.CONTENT_URI,
SongContract.SongEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
//switch off button
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
Here is my delete method snippet from my ContentProvider class:
#Override
public int delete(Uri uri, String selection, String[] selectionArgs){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int numDeleted;
switch(match){
case SONG:
numDeleted = db.delete(
SongContract.SongEntry.TABLE_NAME, selection, selectionArgs);
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
SongContract.SongEntry.TABLE_NAME + "'");
break;
case SONG_WITH_ID:
numDeleted = db.delete(SongContract.SongEntry.TABLE_NAME,
SongContract.SongEntry._ID + " = ?",
new String[]{String.valueOf(ContentUris.parseId(uri))});
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
SongContract.SongEntry.TABLE_NAME + "'");
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
return numDeleted;
}
Here is my SongDetailFragment:
public class SongDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private Song song;
private static final int CURSOR_LOADER_ID = 0;
ImageButton imgViewFavButton;
Boolean mIsFavourite = false;
// private final Context mContext;
public SongDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.song_fragment_detail, container, false);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra("song")) {
song = intent.getParcelableExtra("song");
//display title
((TextView) rootView.findViewById(R.id.detail_title_textview))
.setText(song.getTitle());
((TextView)rootView.findViewById(R.id.detail_description_textview))
.setText(song.getDescription());
((TextView)rootView.findViewById(R.id.song_releasedate_textview))
.setText(song.getReleaseDate());
double dRating = song.getVoteAverage();
String sRating = String.valueOf(dRating);
((TextView)rootView.findViewById(R.id.song_rating_textview))
.setText(sRating + "/10 ");
//show song poster
ImageView imageView = (ImageView) rootView.findViewById(R.id.song_detail_poster_imageview);
Picasso.with(getActivity()).load(song.getPoster()).into(imageView);
}
imgViewFavButton = (ImageButton) rootView.findViewById(R.id.imgFavBtn);
checkFavourites();
imgViewFavButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (mIsFavourite) {
deleteFromDB();
}
else {
insertData();
mIsFavourite = true;
}
}
});
return rootView;
}
// insert data into database
public void insertData(){
ContentValues songValues = new ContentValues();
songValues.put(SongContract.SongEntry.COLUMN_ID, song.getsong_id());
songValues.put(SongContract.SongEntry.COLUMN_IMAGE, song.getPoster());
songValues.put(SongContract.SongEntry.COLUMN_TITLE, song.getTitle());
songValues.put(SongContract.SongEntry.COLUMN_OVERVIEW, song.getDescription());
songValues.put(SongContract.SongEntry.COLUMN_RELEASEDATE, song.getReleaseDate());
songValues.put(SongContract.SongEntry.COLUMN_RATING, song.getVoteAverage().toString());
//Insert our ContentValues
getActivity().getContentResolver().insert(SongContract.SongEntry.CONTENT_URI,
songValues);
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
}
private void deleteFromDB() {
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.SongEntry.CONTENT_URI,
SongContract.SongEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
private void checkFavourites() {
Cursor c =
getActivity().getContentResolver().query(SongContract.SongEntry.CONTENT_URI,
null,
SongContract.SongEntry.COLUMN_ID + " = ?",
new String[]{song.getsong_id()},
null);
if (c != null) {
c.moveToFirst();
int index = c.getColumnIndex(SongContract.SongEntry.COLUMN_ID);
if (c.getCount() > 0 && c.getString(index).equals(song.getsong_id())) {
mIsFavourite = true;
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_on);
}
else{
imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
}
c.close();
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args){
return new CursorLoader(getActivity(),
SongContract.songEntry.CONTENT_URI,
null,
null,
null,
null);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
}
// Set the cursor in our CursorAdapter once the Cursor is loaded
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
// reset CursorAdapter on Loader Reset
#Override
public void onLoaderReset(Loader<Cursor> loader){
}
}
Notice this line right here:
ContentValues songValues = new ContentValues();
getActivity().getContentResolver().delete(SongContract.songEntry.CONTENT_URI,
SongContract.songEntry.COLUMN_TITLE + " = ?",
new String[]{songValues.getAsString(song.getTitle())});
You set songValues to an empty ContentValues object, and later call getAsString() which will return null since it doesn't contain any key for song.getTitle().
Just change your array to have the song title, you don't need ContentValues here:
new String[]{song.getTitle()});

reloading ListView data from Adapter class in Onclick of Button

I am trying to build up a application which has a custom adapter and all ListView row has three Button. I have onClick operation for all Button in custom adapter. I can change the data source when Button clicked however I can not reload the data from custom adapter.
public class CallListViewCustomAdapter extends ArrayAdapter<Person> {
Context context;
SQLiteDatabase sb;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private static final String SAMPLE_TABLE_NAME = "calldetails";
int layoutResourceId;
ArrayList<Person> data = new ArrayList<Person>();
public CallListViewCustomAdapter(Context context, int layoutResourceId, ArrayList<Person> data) {
super(context, layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void refresh(ArrayList<Person>list)
{
data = list;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
View row = convertView;
final int fPosition = position;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
final WeatherHolder holder = new WeatherHolder();
holder.phoneNumber = (TextView)row.findViewById(R.id.number);
holder.fname = (TextView)row.findViewById(R.id.fName);
holder.call = (Button)row.findViewById(R.id.callButton);
holder.skip = (Button)row.findViewById(R.id.skip);
holder.called = (Button)row.findViewById(R.id.called);
holder.called.setTag(position);
Person weather = data.get(position);
holder.phoneNumber.setText(weather.number);
holder.fname.setText(weather.fName);
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.called.setVisibility(View.VISIBLE);///error comes
holder.skip.setVisibility(View.VISIBLE);///error comes
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + data.get(fPosition).number));
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
});
holder.called.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//business logic for data source change
refresh(data);///I want listview change here
sb.close();
Log.v("ONMESSAGE", "HARD");
}
});
// holder.desc= (TextView)row.findViewById(R.id.txtViewDescription);
// holder.switchState = (Switch)row.findViewById(R.id.switch1);
row.setTag(holder);
}
return row;
}
static class WeatherHolder
{
TextView phoneNumber;
TextView fname;
Switch switchState;
Button call,skip,called;
}
}
Fragment where The list is used
public class NewFragment extends Fragment{
View rootView;
ProgressDialog pDialog;
private ListView listView1;
CallListViewCustomAdapter adapter;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private SQLiteDatabase sampleDB;
ArrayList<Person>list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.newfragment, container, false);
initDB();
list = new ArrayList<Person>();
new CallLogDetails().execute();
return rootView;
}
public int checkTable() {
int return_var = 0;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " + "calldetails", null);
if (cc != null){
if (cc.moveToFirst()) {
do {
return_var = cc.getInt(1);
} while (cc.moveToNext());
}
}
return return_var;
}
public void parseandStoreOpearation()
{
try{
CSVReader reader = new CSVReader(new InputStreamReader(getActivity().getAssets().open("batch2.csv")));
String [] nextLine;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
while ((nextLine = reader.readNext()) != null) {
//Log.v("ONMESSAGE", "YES");
Log.v("ONMESSAGE", "Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
if(!nextLine[0].equals("First Name"))
{
//Person newPerson = new Person(nextLine[0],nextLine[1], nextLine[2], 1);
ContentValues cv = new ContentValues();
cv.put("callNumber", nextLine[2]);
cv.put("fName", nextLine[0]);
cv.put("lName", nextLine[1]);
cv.put("callflag", 1);
sampleDB.insert("calldetails", null, cv);
//list.add(newPerson);
}
}
}
catch(Exception e)
{
Log.v("ONMESSAGE", "EXCEPTION " + e.toString());
}
}
public ArrayList<Person> getList()
{
ArrayList<Person> arr = new ArrayList<Person>();
sampleDB= getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " +"calldetails", null);
if(cc != null)
if(cc.moveToFirst()){
do
{ Log.v("Datas",cc.getString(2)+ " " +cc.getString(3) + " " + cc.getString(1) + " " + cc.getInt(4));
Person ph = new Person(cc.getString(2), cc.getString(3), cc.getString(1),cc.getInt(4),cc.getInt(0));
arr.add(ph);
}while(cc.moveToNext());
}
sampleDB.close();
Log.v("ONMESSAGE", new Integer(arr.size()).toString());
return arr;
}
private void initDB() {
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
"calldetails" +" (callid INTEGER PRIMARY KEY AUTOINCREMENT,"+ "callNumber TEXT," +
" fName TEXT," + "lName TEXT," + "callflag INTEGER);");
}
private class CallLogDetails extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Processing");
pDialog.setMessage("Loading Number List");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected void onPostExecute(Void params){
super.onPostExecute(params);
pDialog.dismiss();
if(list.size() == 0)
{
list.add(new Person("No Data", "NO Data", "No Data", 0,0));
}
Collections.reverse(list);
if(adapter != null)
adapter.clear();
adapter = new CallListViewCustomAdapter(getActivity(),
R.layout.listview_row, list);
listView1 = (ListView)getActivity().findViewById(R.id.lvAlbumList);
listView1.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete Record");
builder.setMessage("Do you want to delete the record?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(list.size() > 0){
sampleDB=getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
//sampleDB.execSQL("DELETE FROM "+ SAMPLE_DB_NAME + " " + "WHERE callDesc= " + desc);
//sampleDB.execSQL("DELETE FROM calldetails WHERE callDesc='"+desc+"';");
Toast.makeText(getActivity(), "Row Deleted", Toast.LENGTH_LONG).show();
sampleDB.close();
new CallLogDetails().execute();
}
else
Toast.makeText(getActivity(), "This is a default object. You can not delete this.", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.show();
return false;
}
});
listView1.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... arg0) {
list.clear();
if(checkTable() == 0)
{
parseandStoreOpearation();
}
list = getList();
Log.v("ONMESSAGE", "Doing");
return null;
}
}
}
For an ArrayAdapter, notifyDataSetChanged() only works if you use the add, insert, remove, and clear functions on the Adapter.
Try following code:
public void refresh(ArrayList<Person>list)
{
data.clear();
data.addAll(list);
this.notifyDataSetChanged();
}
Do something like this inside activity
CallListViewCustomAdapter thadapter=new CallListViewCustomAdapter(MainActivity.this, R.layout.list,numAl);
NumberList.setAdapter(thadapter);
#Override
public void onClick(View v) {
thadapter.notifyDataSetChanged();
}
});
Call notifyDataSetChanged() and recall adapter
Call notifyDataSetChanged() method to the ListView adapter object.

Categories

Resources