Unable to refresh database after deleting a row - android

I am using SQLiteDatabase in android. I am not able to refersh my listview after deleting a row.
My code is as follows:
public void delete(String i) {
// TODO Auto-generated method stub
String [] columns= new String[]{KEY_ROW_ID,KEY_FHR,KEY_ID,KEY_NAME,KEY_AGE};
Cursor c= our_db.query(KEY_TABLE, columns, null, null,null, null, null);
our_db.delete(KEY_TABLE, KEY_NAME+ "="+"\'"+i+"\'", null) ;
c.requery();
}
I call it from a viewholder in efficientadapter. Below is the code where I call it:
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
}
});
Can anyone help me finding out the problem. It doesn't give any error. it just deleted the row but doesn't update the view.
Here is the adapter i used:
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
private Bitmap mIcon4;
Context c;
int window;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.c=context;
// Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);
mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.del1);
mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.drawable.edit);
}
public int getCount() {
return DATA.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
//int i=0;
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.del=(ImageView)convertView.findViewById(R.id.icon1);
holder.edit=(ImageView)convertView.findViewById(R.id.icon2);
window=position;
holder.text.setOnClickListener(new OnClickListener() {
private int pos=position;
//private int pos = position;
public void onClick(View v) {
System.out.println(window);
sql_get db = new sql_get(c);
db.open();
String ret_id= db.getid(DATA[pos]);
String ret_name = db.getname(DATA[pos]);
String ret_age= db.getage(DATA[pos]);
String ret_fhr= db.getfhr(DATA[pos]);
String[] result = {ret_id,ret_name,ret_age,ret_fhr};
db.close();
Bundle b=new Bundle();
b.putStringArray("key",result);
Intent i =new Intent(c,Tabs.class);
i.putExtras(b);
c.startActivity(i) ;
Toast.makeText(c, getItemId(position)+""+" Click- text " +pos+" "+ret_name, Toast.LENGTH_SHORT).show();
}
});
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
Toast.makeText(c, "deleting " + DATA[pos], Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
holder.del.setImageBitmap(mIcon3);
holder.edit.setImageBitmap(mIcon4);
return convertView;
static class ViewHolder {
ImageView del;
TextView text;
ImageView icon;
ImageView edit;
}
}

You need to delete the row also from the object holding the data for the list view..

I think you also have to remove the same data from adapter and then use your_adapter.notifyDataSetChanged() method. That worked for me...

I found the solution. As said above, I had to change the DATA object.
I used the following commands to achieve it.
db.open();
db.delete(DATA[pos]);
DATA=db.getdata();
DATA_NAME=db.getname();
DATA_AGE=db.getage();
DATA_FHR=db.getfhr();
db.close();

Related

ListView won't refresh using notifyDataSetChanged

I'm trying to refresh the listview from the adapter class ( non activity class) I tried notifyDataSetChanged() but it wont work , I also tried to call the displayListView() in the adapter class but it crashes as well
this is my displayListView() Method in The ActivityClass
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[]{
DBAdapter.qty,
DBAdapter.price,
DBAdapter.PRODUCT_NAME
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.qtyL,
R.id.priceL,
R.id.PRODUCT_NAMEL
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.country_inf,
cursor,
columns,
to,
0);
HorizontalListView listView = (HorizontalListView) findViewById(R.id.cartCeckOutList);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
And this is the Adapter Class I use
package com.abdullahadhaim.finegrillresturant.adater;
public class CustomListAdapter extends BaseAdapter {
Context c;
// DBHelper myDataBaseHelper ;
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
DBAdapter myADapterDB;
WaiterActivity waiterAct;
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
final TextView title = (TextView) convertView.findViewById(R.id.title);
TextView price = (TextView) convertView.findViewById(R.id.rating);
// myDataBaseHelper=new DBHelper(activity, "CDB", null, 1);
myADapterDB = new DBAdapter(activity);
myADapterDB.open();
waiterAct = new WaiterActivity();
// getting movie data for the row
final Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// price
price.setText("Price: " + "SR " + String.valueOf(m.getPrice()));
Button add = (Button) convertView.findViewById(R.id.button1);
Button plus = (Button) convertView.findViewById(R.id.plus_butt);
Button minus = (Button) convertView.findViewById(R.id.minus_butt);
final EditText qty = (EditText) convertView
.findViewById(R.id.editText1);
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String the_qty = qty.getText().toString();
int my_qty = Integer.parseInt(the_qty) + 1;
qty.setText(my_qty + "");
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String the_qty = qty.getText().toString();
int my_qty = Integer.parseInt(the_qty) - 1;
qty.setText(my_qty + "");
}
});
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int myQTY = Integer.parseInt(qty.getText().toString());
String myTitle = m.getTitle().toString();
String myCategory = m.getCategory().toString();
int myCategoryN = m.getOrderNum();
double myPrice = m.getPrice() * myQTY;
if (myQTY == 0)
Toast.makeText(activity, "Orders Must be 1 Atleast",
Toast.LENGTH_SHORT).show();
else {
myADapterDB.checkIfExcist(activity, "productName", myTitle,
myQTY, myPrice, m.getPrice(), myTitle, myCategory,
myCategoryN + "", myQTY);
myADapterDB.deleteZeroOrLessValues();
}
}
});
return convertView;
}
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
}
take a look at Loaders. I think this is the prefered way to load data from datebase into views. With Loaders you get callbacks if the data has changed and the view is updated for you.
http://developer.android.com/guide/components/loaders.html
Here is a good tutorial I think:
http://code.tutsplus.com/tutorials/android-fundamentals-properly-loading-data--mobile-5673

ListView disappears after reloading it again

I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}
It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.
Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);

setting text view according its position of the row a listview filled by SimpleCursorAdapter database with click on the row

setting the text view according its position in of the row a list view filled from SimpleCursorAdapter from database on the click of the onlistitemclicked
my custom list view has an image& textview for a name and another invisible text view which will be visible and be setting with a different number on the row clicked only but the problem is that when i clicked any row the text appeared on the view at the first row only whatever the row i clicked
and I tried to use the set and get methods but i found its used for the Base Adapter.
and the textview which will visible is not from data base
can some one tell me how to do it please
here is a part of the code
public class Select_players_two extends ListActivity
{
protected static class RowViewHolder
{
public TextView tvOne;
public TextView tvTwo;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
public class CustConAdpterSelect extends SimpleCursorAdapter
{
int i = 0;
int count;
private int layout;
LayoutInflater inflator;
final SQLiteConnector sqlCon = new SQLiteConnector(mContext);
private ImageButton editBtn;
private ImageButton delBtn;
int id ;
TextView txt_select;
CharSequence txt_char;
static final String KEY_No = "playerNo";
public CustConAdpterSelect(Context context, int layout, Cursor c,
String[] from, int[] to, int flags)
{
super(context, layout, c, from, to,0);
this.layout = layout;
inflator= LayoutInflater.from(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.lv_name_photo, parent, false);
RowViewHolder holder = new RowViewHolder();
holder.tvOne = (TextView) retView.findViewById(R.id.name);
holder.tvTwo = (TextView) retView.findViewById(R.id.txt_number);
// holder.tvOne.setOnClickListener(tvOneLapOnClickListener);
retView.setTag(holder);
return retView;
}
#Override
public void bindView(View v, final Context context, Cursor c)
{
editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
if( editBtn.getVisibility() == View.VISIBLE )
editBtn.setVisibility(View.INVISIBLE);
else
editBtn.setVisibility(View.INVISIBLE);
//set delete button invisble
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
if( delBtn.getVisibility() == View.VISIBLE )
delBtn.setVisibility(View.INVISIBLE);
else
delBtn.setVisibility(View.INVISIBLE);
//final int
id = c.getInt(c.getColumnIndex(Contacts.ID));
final String name = c.getString(c.getColumnIndex(Contacts.NAME));
final String phone = c.getString(c.getColumnIndex(Contacts.PHONE));
final String email = c.getString(c.getColumnIndex(Contacts.MAIL));
final String fb = c.getString(c.getColumnIndex(Contacts.FB));
final byte[] image = c.getBlob(c.getColumnIndex(Contacts.IMAGE));
ImageView iv = (ImageView) v.findViewById(R.id.photo);
if (image != null)
{
if (image.length > 3)
{
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
}
}
TextView tname = (TextView) v.findViewById(R.id.name);
tname.setText(name);
TextView tphone = (TextView) v.findViewById(R.id.phone);
tphone.setText(phone);
TextView temail = (TextView) v.findViewById(R.id.email);
temail.setText(email);
txt_select=(TextView)v.findViewById(R.id.txt_number);
// final SQLiteConnector sqlCon = new SQLiteConnector(context);
//for( i = 0; i <=4; i++)
/*
v.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//onitem clicked
txt_char = txt_select.getText();
{
if (txt_char != null)
{
int txt_int = Integer.parseInt(txt_char.toString());
int count = txt_int;
Log.d("count1",String.valueOf(count));
count++;
txt_select.setText(String.valueOf(count));
Log.d("count",String.valueOf(count));
if( txt_select.getVisibility() == View.INVISIBLE )
txt_select.setVisibility(View.VISIBLE);
else
txt_select.setVisibility(View.INVISIBLE);
Log.d("number", String.valueOf(i));
}
/* if( txt_select.getVisibility() == View.INVISIBLE )
txt_select.setVisibility(View.VISIBLE);
else
txt_select.setVisibility(View.INVISIBLE);
i++;
Log.d("number", String.valueOf(i));*/
/* }
}
});
*/
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final View view = super.getView(position, convertView, parent);
final TextView textView = (TextView)view.findViewById(R.id.txt_number);
/* textView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.i("Click", "TextView clicked on row " + position);
// textView.setTag(position);
txt_char = txt_select.getText();
Log.d("txt", txt_char.toString());
if (txt_char != null)
{
int txt_int = Integer.parseInt(txt_char.toString());
Log.d("txt2", txt_char.toString());
int count = txt_int;
Log.d("count1",String.valueOf(count));
count++;
txt_select.setText(String.valueOf(count));
CharSequence txt_char2 = txt_select.getText();
Log.d("ttxt", txt_char2.toString());
Log.d("count",String.valueOf(count));
if( txt_select.getVisibility() == View.INVISIBLE )
txt_select.setVisibility(View.VISIBLE);
else
txt_select.setVisibility(View.INVISIBLE);
Log.d("number", String.valueOf(i));
i++;
}
}*/
// }); // TODO Auto-generated method stub
return view;
}
private OnClickListener tvOneLapOnClickListener = new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// get the RowViewHolder
RowViewHolder holder = new RowViewHolder();
// Get the holder for the row
holder = (RowViewHolder) ((View) v.getParent()).getTag();
if (holder.tvOne.getVisibility() == View.INVISIBLE)
holder.tvOne.setVisibility(View.VISIBLE);
else
holder.tvOne.setVisibility(View.INVISIBLE);
}
};
}
}
that is the database class "SQLiteConnector"
public class SQLiteConnector
{
private SQLiteDatabase db;
private SQLiteHelper sqlHp,sqlhpc;
private Cursor cur,curc;
public SQLiteConnector(Context context)
{
sqlHp = new SQLiteHelper(context, Contacts.DB_NAME, null, 1);
sqlhpc = new SQLiteHelper(context, Contacts.DB_NAME, null, 1);
}
// insert new player in the list//
public void insertContact(String name, String phone, String mail,String fb,byte[] blob) {
ContentValues cv = new ContentValues();
cv.put(Contacts.NAME, name);
cv.put(Contacts.PHONE, phone);
cv.put(Contacts.MAIL, mail);
cv.put(Contacts.FB, fb);
cv.put(Contacts.IMAGE,blob);
db = sqlHp.getWritableDatabase();
db.insert(Contacts.TABLE, null, cv);
db.close();
}
// insert the score sheet //
public void insertContact_score(String score, String num_call, String num_collection ,String shape_type,
String score_sec, String num_call_sec, String num_collection_sec ,String shape_type_sec,
String score_third, String num_call_third, String num_collection_third ,String shape_type_third,
String score_forth, String num_call_forth, String num_collection_forth ,String shape_type_forth)
{
ContentValues cvscore = new ContentValues();
cvscore.put(Contacts.SCORE_st, score);
cvscore.put(Contacts.NUM_CALL_st, num_call);
cvscore.put(Contacts.NUM_COLLECTION_st, num_collection);
cvscore.put(Contacts.SHAPE_CALL_st, shape_type);
cvscore.put(Contacts.SCORE_sec, score_sec);
cvscore.put(Contacts.NUM_CALL_sec, num_call_sec);
cvscore.put(Contacts.NUM_COLLECTION_sec, num_collection_sec);
cvscore.put(Contacts.SHAPE_CALL_sec, shape_type_sec);
cvscore.put(Contacts.SCORE_third, score_third);
cvscore.put(Contacts.NUM_CALL_third, num_call_third);
cvscore.put(Contacts.NUM_COLLECTION_third, num_collection_third);
cvscore.put(Contacts.SHAPE_CALL_third,shape_type_third);
cvscore.put(Contacts.SCORE_forth, score_forth);
cvscore.put(Contacts.NUM_CALL_forth, num_call_forth);
cvscore.put(Contacts.NUM_COLLECTION_forth, num_collection_forth);
cvscore.put(Contacts.SHAPE_CALL_forth,shape_type_forth);
//cvscore.put(Contacts.IMAGE,blob);
db = sqlhpc.getWritableDatabase();
db.insert(Contacts.TABLESCORE, null, cvscore);
db.close();
}
public void updateContact_score(long id,String score, String num_call, String num_collection ,String shape_type,
String score_sec, String num_call_sec, String num_collection_sec ,String shape_type_sec,
String score_third, String num_call_third, String num_collection_third ,String shape_type_third,
String score_forth, String num_call_forth, String num_collection_forth ,String shape_type_forth)
{
ContentValues cvscore = new ContentValues();
cvscore.put(Contacts.SCORE_st, score);
cvscore.put(Contacts.NUM_CALL_st, num_call);
cvscore.put(Contacts.NUM_COLLECTION_st, num_collection);
cvscore.put(Contacts.SHAPE_CALL_st, shape_type);
cvscore.put(Contacts.SCORE_sec, score_sec);
cvscore.put(Contacts.NUM_CALL_sec, num_call_sec);
cvscore.put(Contacts.NUM_COLLECTION_sec, num_collection_sec);
cvscore.put(Contacts.SHAPE_CALL_sec, shape_type_sec);
cvscore.put(Contacts.SCORE_third, score_third);
cvscore.put(Contacts.NUM_CALL_third, num_call_third);
cvscore.put(Contacts.NUM_COLLECTION_third, num_collection_third);
cvscore.put(Contacts.SHAPE_CALL_third,shape_type_third);
cvscore.put(Contacts.SCORE_forth, score_forth);
cvscore.put(Contacts.NUM_CALL_forth, num_call_forth);
cvscore.put(Contacts.NUM_COLLECTION_forth, num_collection_forth);
cvscore.put(Contacts.SHAPE_CALL_forth,shape_type_forth);
//cvscore.put(Contacts.IMAGE,blob);
db = sqlhpc.getWritableDatabase();
db.update(Contacts.TABLESCORE, cvscore, Contacts.ID+"="+ id, null);
db.close();
}
public void updateContact(long id,String name, String phone, String mail,String fb,byte[] blob) {
ContentValues cv = new ContentValues();
cv.put(Contacts.NAME, name);
cv.put(Contacts.PHONE, phone);
cv.put(Contacts.MAIL, mail);
cv.put(Contacts.FB, fb);
cv.put(Contacts.IMAGE,blob);
db = sqlHp.getWritableDatabase();
db.update(Contacts.TABLE, cv, Contacts.ID+"="+ id, null);
db.close();
}
public Cursor getAllContacts() {
db = sqlHp.getReadableDatabase();
cur=db.query(Contacts.TABLE,null, null,null, null, null, "name");
return cur;
}
public Cursor getAllScores() {
db = sqlhpc.getReadableDatabase();
curc=db.query(Contacts.TABLESCORE,null, null,null, null, null, "score_st");
return curc;
}
public void deletescore(long id) {
System.out.println("DELETE ");
db = sqlhpc.getWritableDatabase();
db.delete(Contacts.TABLESCORE, "_id="+id , null);
db.close();
}
public Cursor getOneContact(long id) {
db = sqlHp.getReadableDatabase();
cur=db.query(Contacts.TABLE, null, "_id="+ id, null, null, null,null);
return cur;
}
public void deleteContact(long id) {
System.out.println("DELETE ");
db = sqlHp.getWritableDatabase();
db.delete(Contacts.TABLE, "_id="+id , null);
db.close();
}
}
I believe what you need to do is use the Tag facility of the row view container to identify the textview it contains and then retrieve it in the listener to identify the correct textview. The way I've done it is to use a holder for the row contained views, so you can access any that you need. For example:
protected static class RowViewHolder {
public TextView tvOne;
public TextView tvTwo;
}
Then in your newView method, populate the holder and set the Tag to it:
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
RowViewHolder holder = new RowViewHolder();
holder.tvOne = (TextView) retView.findViewById(R.id.name);
holder.tvTwo = (TextView) retView.findViewById(R.id.txt_number);
retView.setTag(holder);
return retView;
}
In your listener then you can access the correct textview:
public void onClick(View v) {
ListView lv = (ListView) v.getParent();
final int position = lv.getPositionForView((View) v.getParent());
// get the RowViewHolder
RowViewHolder holder = new RowViewHolder();
holder = (RowViewHolder) ((View) v.getParent()).getTag();
if(holder.tvOne.getVisibility() == View.INVISIBLE ) {
holder.tvOne.setVisibility(View.VISIBLE);
}
else
{
holder.tvOne.setVisibility(View.INVISIBLE);
}
}
Apologies, but I've not been able to test this code but I hope it gives you a pointer to the process. You shouldn't need the RowViewHolder but I've included it so you or others can see how to access multiple views within the row.
You may find the this video helpful The World of ListView I think you'll find the relevant discussion at about 4:10 in which describes how the views are res-used and how index, position etc. relate.
I also found one of the answers to this question helpful Android: ListView elements with multiple clickable buttons
There are multiple ways of doing this. The way I was suggesting assumes you have a single code module for the activity containing the CustConAdpterSelect class. So the structure looks something like this.
package com.example.totastest;
// imports
public class Copy_2_of_MainActivity extends Activity {
protected static class RowViewHolder
{
public TextView tvOne;
public TextView tvTwo;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class CustConAdpterSelect extends SimpleCursorAdapter
{
// ...
public CustConAdpterSelect(Context context, int layout, Cursor c, String[] from, int[] to)
{
super(context, layout, c, from, to, 0);
// ...
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.lv_name_photo, parent, false);
RowViewHolder holder = new RowViewHolder();
holder.tvOne = (TextView) retView.findViewById(R.id.name);
holder.tvTwo = (TextView) retView.findViewById(R.id.txt_number);
holder.tvOne.setOnClickListener(tvOneLapOnClickListener);
retView.setTag(holder);
return retView;
}
#Override
public void bindView(View v, final Context context, Cursor c)
{
// ...
}
#SuppressWarnings("unchecked")
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// ...
}
private OnClickListener tvOneLapOnClickListener = new OnClickListener() {
#Override
// When the tvOne button is clicked, execute this code
public void onClick(View v) {
// get the RowViewHolder
RowViewHolder holder = new RowViewHolder();
// Get the holder for the row
holder = (RowViewHolder) ((View) v.getParent()).getTag();
if (holder.tvOne.getVisibility() == View.INVISIBLE)
holder.tvOne.setVisibility(View.VISIBLE);
else
holder.tvOne.setVisibility(View.INVISIBLE);
}
};
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
// ...
}
}

Custom BaseAdapter wont add new Data - Android

I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.

Custom ListView with CheckBox

I know there are lots of questions related to Custom ListView with CheckBox but still i am getting some problem in retrieving all checked items.
What i am doing is :
Displaying Custom ListView from Database (List of All Sent SMSs).
Allow user to check various list items.
When user presses the Delete Button i want to delete all the checked items (From the database as well as the view portion)
Problem :
When i go to my Activity for the first time and check some items, and delete it, it works fine.
But when i again check some items just after pressing delete button, some items gets checked and some gets unchecked and again some other items are deleted..
I think i am not able to bind id and list item perfectly..
Coding done so far:
row.xml contains
ImageView
TextView
TextView
TextView
CheckBox
In my Activity Class :
Uri uriSms = Uri.parse("content://sms/sent");
Cursor cursor = context.getContentResolver().query(uriSms, null,null,null,null);
String[] from={"address","body"};
int[] to={R.id.contactName,R.id.msgLine};
ssa=new SentSmsAdapter(context,R.layout.inbox_list_item,cursor,from,to,2);
smsList.setAdapter(ssa);
deleteSms.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ArrayList<Boolean> list=SentSmsAdapter.itemChecked;
Uri path=Uri.parse("content://sms/");
for(int i=0;i<list.size();i++)
{
if(list.get(i))
getContentResolver().delete(path,"_id="+ssa.getItemId(i),null);
}
ssa.notifyDataSetChanged();
}
I have custom SimpleCursorAdapter.
public class SentSmsAdapter extends SimpleCursorAdapter{
Cursor dataCursor;
LayoutInflater mInflater;
Context context;
int layoutType;
ArrayList<String> arrayList;
public static HashMap<String,Long> myList=new HashMap<String,Long>();
public static ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public static ArrayList<Long> itemIds=new ArrayList<Long>();
public SentSmsAdapter(Context context, int layout, Cursor dataCursor, String[] from,
int[] to,int type) {
super(context, layout, dataCursor, from, to);
layoutType=type;
this.context=context;
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
arrayList=new ArrayList<String>();
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.inbox_list_item, null);
holder = new ViewHolder();
holder.checkBox=(CheckBox) convertView.findViewById(R.id.checkMsg);
holder.checkBox.setTag(position);
holder.cName=(TextView)convertView.findViewById(R.id.contactName);
holder.icon=(ImageView)convertView.findViewById(R.id.msgImage);
holder.msg=(TextView)convertView.findViewById(R.id.msgLine);
holder.time=(TextView)convertView.findViewById(R.id.msgTime);
convertView.setTag(holder);
holder.checkBox.setTag(itemChecked.get(position));
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) view.findViewById(R.id.checkMsg);
int pos=Integer.parseInt(holder.checkBox.getTag());
itemChecked.set(position, cb.isChecked());
/*if (cb.isChecked()) {
itemChecked.set(position, true);
Log.i("WhenChecked",Boolean.toString(itemChecked.get(position)));
// do some operations here
}
else if (!cb.isChecked()) {
itemChecked.set(position, false);
Log.i("WhenNotChecked",Boolean.toString(itemChecked.get(position)));
// do some operations here
}
*/
}
});
dataCursor.moveToPosition(position);
String id=Integer.toString(dataCursor.getInt(dataCursor.getColumnIndexOrThrow("_id")));
itemIds.add(Long.parseLong(id));
String msgText=dataCursor.getString(dataCursor.getColumnIndexOrThrow("body"));
holder.msg.setText(msgText);
Long time=dataCursor.getLong(dataCursor.getColumnIndexOrThrow("date"));
holder.time.setText(Long.toString(time));
String address=dataCursor.getString(dataCursor.getColumnIndexOrThrow("address"));
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
Cursor cs= context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
if(cs.getCount()>0)
address=cs.getString(cs.getColumnIndex(PhoneLookup.DISPLAY_NAME));
cs.close();
holder.cName.setText(address);
if(layoutType==1)holder.checkBox.setVisibility(View.GONE);
else
{
holder.checkBox.setVisibility(View.VISIBLE);
}
arrayList.add(id+","+address+","+msgText+","+Long.toString(time));
return convertView;
}
static class ViewHolder
{
ImageView icon;
CheckBox checkBox;
TextView cName;
TextView msg;
TextView time;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return itemIds.get(position);
}
}
Try something like this.
add this code in getView()
holder.checkBox.seTag(position);
holder.checkBox.setOnCheckedChangedListener(this);
implement this outside getView().
public void onCheckedChanged(CompoundButton view,boolean isChecked) {
if(isChecked)
{
itemChecked.add(view.getTag());
}
else
{
if(itemChecked.cantains(view.getTag()))
//remove from itemChecked.
}
}
When deleting delete all the elements from the list whose index is available in itemChecked.
Thanks and N-JOY.
If you use threads when checking, uncheking and deleting your items, they will work properly.

Categories

Resources