Hide items in GridView if two items have same images using Android - java

i am developing a project using GridView where i need to hide items if a user click such two items having same images then both item should be hide.
First time when project will load it will have one Question Marks image on all item.
when user click item the background image will show then if he click another item having the same picture then both item should be hide if not, it again show the Question Marks image.
How this is possible?
here is my MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
GridViewContent adapter;
List<Integer> pictures;
boolean flage=false;
int img1=-1,img2=-1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
shuffleArray();
adapter= new GridViewContent(this);
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures= new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++)
{
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
public class GridViewContent extends BaseAdapter {
private Context context;
//abstract change();
public int pictureArray[]={
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
};
public GridViewContent(Context c){
context=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureArray.length);
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureArray[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
convertView=LayoutInflater.from(context).inflate(R.layout.main, null);
final ImageView myimage=new ImageView(context);
myimage.setImageResource(pictureArray[position]);
//myimage.setImageResource(pictures.get(pictureArray[position]));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// int post1,post2;
myimage.setImageResource(pictures.get(position));
if(flage==false)
{
img1=pictures.get(position);
flage=true;
}else if(flage==true){
//post2=position;
img2=pictures.get(position);
checkResult();
//notifyDataSetChanged();
flage=false;
}
//else if(f)
}
});
return myimage;
}
}
public void checkResult() {
if(img1==img2)
{
//pictures.remove(post2);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainActivity.this, "Sorry!!!!", Toast.LENGTH_LONG).show();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
}
}

You could try and remember the index of a GridView item you clicked. When a second click occurs, check the remembered index. If it is populated (meaning the user already clicked on an arbitrary image once), extract both drawables from the adapter and check if they are equal. If they are, remove them from the adapter and update it. Do not forget to reset the remembered index.
In code, this might look something like this:
int firstClickIndex = -1;
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView <? > parent, View view, int position, long id) {
if (-1 == firstClickIndex) {
firstClickIndex = position;
} else {
final int fstDrawable = adapter.get(firstClickIndex);
final int sndDrawable = adapter.get(position);
if (fstDrawable == sndDrawable) {
// Remove stuff, then reset firstClickIndex.
} else {
// Reset firstClickIndex.
}
}
}
});

Related

Need help in Multiplying the edit text value with a text view value from a custom list view in android

I have created a custom list view with a image view, 2 text view,one edit text one is for displaying brand names a string value another for displaying loyalty points, edit text for entering the quantity by the user which will be multiplied with loyalty point from text view.I have tried to multiplying the user entered value in each list item (from edit text)with the text view loyalty points value,I have implemented my own logic for multiplying it but it is not working, I have posted my code here for your reference correct me if any thing wrong in the code
MainActivity.java
public class MainActivity extends Activity {
ListView lv;
Context context;
static TextView ttv;
ArrayList prgmName;
public static int [] prgmImages={R.drawable.images,R.drawable.images1,R.drawable.images2,R.drawable.images3,R.drawable.images4,R.drawable.images5,R.drawable.images6,R.drawable.images7,R.drawable.images8};
public static String [] prgmNameList={"Britania","Rin","Goodrej","ITC","Nestle","Wheel","Ariel","Tide"};
public static String [] loyal_pts={"10","5","15","25","20","18","30","32"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
ttv= (TextView) findViewById(R.id.tot_point);
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages,loyal_pts));
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter{
String [] result;
String [] Pts;
Context context;
int [] imageId;
int total_points;
String con_pts;
int lyl_pts;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages, String[] loyal_pts) {
// TODO Auto-generated constructor stub
result=prgmNameList;
Pts=loyal_pts;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
TextView tv1;
ImageView img;
EditText etxt;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
// final int total_points,con_pts,lyl_pts;
rowView = inflater.inflate(R.layout.item_list, null);
try{
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.etxt= (EditText) rowView.findViewById(R.id.edit_txt);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.tv1= (TextView) rowView.findViewById(R.id.textView2);
holder.tv.setText(result[position]);
holder.tv1.setText(" " + Pts[position] + "pts");
holder.img.setImageResource(imageId[position]);
System.out.println("total points"+total_points);
holder.etxt.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) {
try {
lyl_pts = Integer.parseInt(String.valueOf(Pts[position]));
con_pts = holder.etxt.getText().toString().trim();
total_points = lyl_pts * Integer.parseInt(con_pts);
Toast.makeText(context,total_points,LENGTH_LONG).show();
System.out.println("heyy"+total_points);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
catch(Exception e){
e.printStackTrace();
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Toast.makeText(context, "You Clicked " + result[position], LENGTH_LONG).show();
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
});
return rowView;
}
}
getView() is called whenever a new item is displayed on screen. at the initial phase nothing will be in your EditText so that you are not getting expected result from this line in getView() method.
con_pts=holder.etxt.getText().toString().trim();
I suggest either putting some initial value at etxt Or moving the logic in afterTextChanged like here
#Override
public void afterTextChanged(Editable s) {
lyl_pts=Integer.parseInt(String.valueOf(Pts[position]));
con_pts=holder.etxt.getText().toString().trim();
total_points = lyl_pts * Integer.parseInt(con_pts);
System.out.println("total points"+total_points);
}

not getting selected contacts to a listview

I need to get the selected contacts from the SelectContactsActivity and display those selected contacts in ContactListActivity. But i am not getting the contacts which i selected.
my SelectContactsActivity.java
public class SelectContactsActivity extends Activity{
private ListView select_listView;
private EditText search_edt;
private List<ContactBean> list = new ArrayList<ContactBean>();
private ContanctAdapter objAdapter;
//private boolean UpdateAB;
private String groupName;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_selectcontacts);
select_listView = (ListView) findViewById(R.id.select_contacts_listView);
search_edt = (EditText) findViewById(R.id.inputSearch);
Intent intent = getIntent();
groupName = intent.getStringExtra("group_name");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
objAdapter = new ContanctAdapter(SelectContactsActivity.this, R.layout.select_contacts_list_item, list, updateAB);
select_listView.setAdapter(objAdapter);
objAdapter.setEditMode(true);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
} else {
showToast("No Contact Found!!!");
}
select_listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View v,
int position, long id) {
// TODO Auto-generated method stub
objAdapter.setChecked(position, v);
objAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
});
/**
* Enabling Search Filter
* */
// Capture Text in EditText
search_edt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search_edt.getText().toString().toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void showToast(String msg) {
// TODO Auto-generated method stub
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
objAdapter.setEditMode(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions_select_contacts_list, menu);
MenuItem item = null;
if (select_listView.getCount() > 0) {
if(objAdapter.isCheckItem()){
menu.findItem(R.id.action_done).setEnabled(true).setVisible(true);
item = menu.add(Menu.NONE, R.id.action_done, Menu.NONE,R.string.done);
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
Log.v(this.getClass().getName(), "Check update..."+objAdapter.isCheckItem());
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_done:
StringBuilder _itemBuilder = new StringBuilder();
objAdapter.saveSelected(groupName);
invalidateOptionsMenu();
finish();
break;
}
return true;
}
Handler updateAB = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
invalidateOptionsMenu();
Log.v(SelectContactsActivity.this.getClass().getName(), "Check invalidate cal;l");
}
};
}
My ContanctAdapter.java
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
public Context mcontext;
private List<ContactBean> items;
private ContactBean objBean;
private boolean isEdit;
private ArrayList<ContactBean> arraylist;
public boolean[] contactCheckArray;
private LayoutInflater inflater;
public ContanctAdapter(Activity act, int row, List<ContactBean> items, Handler handler) {
super(act, row, items);
this.mcontext = act;
inflater = LayoutInflater.from(act);
this.items = items;
this.arraylist = new ArrayList<ContactBean>();
this.arraylist.addAll(items);
contactCheckArray = new boolean[items.size()];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View view = null==convertView?inflater.inflate(R.layout.select_contacts_list_item, null):convertView;
ViewHolder holder = null;
if (null == view.getTag()) {
holder = new ViewHolder();
holder.tvname = (TextView) view.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
holder.iv = (ImageView)view.findViewById(R.id.contacts_imageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
objBean = items.get(position);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
&& objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
if (isEdit) {
holder.iv.setVisibility(View.VISIBLE);
} else {
holder.iv.setVisibility(View.GONE);
}
return view;
}
public void setEditMode(boolean isEdit) {
this.isEdit = isEdit;
}
public boolean isCheckItem () {
for (boolean value : contactCheckArray) {
if (value)
return true;
}
return false;
}
public void setChecked(final int pos, final View row) {
if (!contactCheckArray[pos]) {
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check);
contactCheckArray[pos] = true;
notifyDataSetChanged();
} else {
contactCheckArray[pos] = false;
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check_box_bg);
notifyDataSetChanged();
}
}
public class ViewHolder {
public ImageView iv;
public TextView tvname, tvPhoneNo;
}
public void saveSelected(String groupName){
StringBuilder _itemBuilder = new StringBuilder();
ProfilesDatabaseHelper DbHelper = new ProfilesDatabaseHelper(mcontext);
for (int i = 0; i < arraylist.size(); i++) {
if (contactCheckArray[i]) {
_itemBuilder.append("'"+ arraylist.get(i).getPhoneNo() + "'" + ",");
//Toast.makeText(mcontext, "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
DbHelper.executeSQL("INSERT INTO GroupsTable (GroupName, ContactName, PhoneNumber) VALUES ('"+groupName+"', '"+arraylist.get(i).getName()+"','"+ arraylist.get(i).getPhoneNo()+ "')");
}
}
if (_itemBuilder.length() > 0) {
_itemBuilder.deleteCharAt(_itemBuilder.length() - 1);
Log.v(getClass().getName(), "Check..selected contactss :"+ _itemBuilder.toString());
//Toast.makeText(getApplicationContext(), "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
// This will clear the buffer
_itemBuilder.delete(0, _itemBuilder.length());
}
}
public void filter(String charText ) {
// TODO Auto-generated method stub
charText = charText.toLowerCase(Locale.getDefault());
items.clear();
if (charText.length() == 0) {
items.addAll(arraylist);
}else {
for (ContactBean ob : arraylist) {
if (ob.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
items.add(ob);
}
}
}
notifyDataSetChanged();
}
}
And if i click on the first item in SelectContactsList activity automatically my 9th and 17th and 25th, 33.... contacts also selected and its returning one contact which i didn't select to the Contactslist activity. And i am not getting any errors. Any one help me to solve this issue.
Your issue is with this line in the first snippet, in your listener.
objAdapter.setChecked(position, v);
POSITION is different from ID. A ListView only renders the number of items that it needs to show. The position is the position in the rendered list.
Change it to id.
See this post as well for a better explanation of this with in-depth examples: Create a ListView with selectable rows/change background color of ListView rows when clicked

Can not identify the cause of Application crash

I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#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 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}
yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)

Change GridView images on item click at run time in android

i am using GridView in application. and i wants that when i click on item it should replace on another array picture. actually i used two array when application run first time, the GridView will show the first array picture , after that when i click on item it should replace by the second array picture according to its position.
i did try but did't solve. so any one help me..
GridViewContent.java
public class GridViewContent extends BaseAdapter {
private Context context;
public int pictureArray[]={
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
};
public GridViewContent(Context c){
context=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureArray.length);
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureArray[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView myimage=new ImageView(context);
myimage.setImageResource(pictureArray[position]);
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
return myimage;
}
}
MainActivity.java
public class MainActivity extends Activity {
Context ctx;
GridViewContent grid1 = new GridViewContent(ctx);
// GridView grid;
/*
* static final int[] numbers = new int[] {
* R.drawable.question,R.drawable.question
* ,R.drawable.question,R.drawable.question
* ,R.drawable.question,R.drawable.question, R.drawable.question,
*
* };
*/
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
// grid.setOnItemClickListener(itemClickListener);
grid.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
ImageView pictImage = new ImageView(ctx);
int imgView = OriginalArray[id];
pictImage.setImageResource(imgView);
}
});
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_memory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
thanks in advance....
You need to do some little changes as below:
public class GridViewContent extends BaseAdapter {
private Context context;
public int pictureArray[]={
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
};
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, };
public GridViewContent(Context c){
context=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureArray.length);
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureArray[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView myimage=new ImageView(context);
myimage.setImageResource(pictureArray[position]);
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myimage.setImageResources(Original[arg2]);
}
});
return myimage;
}
}
Implement onitemclicklistener for gridview.Refer this site http://www.mkyong.com/android/android-gridview-example/. write your changing logic inside this and call adapter.notifydatasetChanged(). http://stackoverflow.com/questions/6201884/how-can-i-change-image-on-gridview-runtime

filter text in listview android

I have a one EditText and one ListView. Item in ListView contains two TextView's. I need to filter ListView if the user enters something in EditText. My adapter:
public class AdapterUserIsp extends ArrayAdapter{
public static ArrayList<ItemUserIsp> data = new ArrayList<ItemUserIsp>();
Context context;
int ch = 0;
public static TextView header4;
#SuppressWarnings("unchecked")
public AdapterUserIsp(Context context, int textViewResourceId, ArrayList<ItemUserIsp> arr) {
super(context, textViewResourceId, arr);
if (arr != null) {
data = arr;
}
this.context = context;
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int num) {
// TODO Auto-generated method stub
return data.get(num);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#SuppressLint("NewApi")
#Override
public View getView(int i, View someView, ViewGroup arg2) {
LayoutInflater inflater = LayoutInflater.from(context);
if (someView == null) {
someView = inflater.inflate(R.layout.item_user_isp, arg2, false);
}
TextView header1 = (TextView) someView.findViewById(R.id.tvUserNameIsp);
TextView header2 = (TextView) someView.findViewById(R.id.tvUserPositionIsp);
header1.setText(data.get(i).header1);
header2.setText(data.get(i).header2);
return someView;
}
}
My activity:
final ListView lv = (ListView)findViewById(R.id.users);
final AdapterUserIsp adapter = new AdapterUserIsp(this,R.id.users,data);
final EditText search= (EditText)findViewById(R.id.search);
search_isp.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
adapter.getFilter().filter(s);
lv.invalidateViews();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
But it don't work. Why? Thanks!
You have to update your adapter.
If you just add some new items to your list arr you have to call:
adapter.notifyDataSetChanged();
If you want to redraw all items you could set the adapter again:
lv.setAdapter(adapter);
Hope this will help you :)
insert the following line after lv.invalidateViews(); on onTextChanged method.
adapter.notifyDataSetChanged();
and also you have to implement your adapter class from Filterable if you want to override the filter method.
if adapter.notifyDataSetChanged(); doesn't work, do not use final for adapter, get adapter inside the onTextChanged and after filter your text.
YourAdapterOrWhateverAdapter adapter = (YourAdapterOrWhateverAdapter) listView.getAdapter();
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
NOTE: This is just guess..

Categories

Resources