How to get value from edittext in gridview - android

I have used grid view in my project
My activity layout file
<GridView
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start"
android:numColumns="1"
android:stretchMode="spacingWidth"
android:layout_below="#+id/spinner1"
android:layout_marginLeft="20dip"
android:layout_marginRight="10dip"
android:layout_marginTop="20dip"
android:visibility="visible" >
</GridView>
My grid layout(grid_change_prices.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="320dp"
android:layout_height="match_parent"
android:clickable="false"
>
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#ff0000" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dip"
android:background="#ffffff"
android:paddingTop="0dip" >
<TextView
android:id="#+id/cplabel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:paddingLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/cpprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_price"
android:layout_marginTop="0dp"
android:textSize="12dp"
android:inputType="number" />
</TableRow>
</TableLayout>
</RelativeLayout>
My Output from emulator
check this URL
http://i.stack.imgur.com/Uc6cs.png
My code file
public void fillgrid(int categoryid,String car){
gridView = (GridView) findViewById(R.id.gridView);
final DatabaseClass2 db = new DatabaseClass2(this);
db.openDataBase();
Cursor c = db.getprice(categoryid);
startManagingCursor(c);
String[] fromColumns = {"_id",DatabaseClass2.colPrice};
int[] toViews = {R.id.cplabel, R.id.cpprice};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.grid_change_prices, c, fromColumns, toViews);
//c.moveToNext();
gridView.setAdapter(adapter); }
Now my query is
When i click modify button, I want to update my database with the new values
i tried to get values from edit text by using .gettext() .
but it only returns value from first edittext
How i got the values from other edittexts, with the row id as well
so that i update database with new price of same design..?

Why are you using a GridView for such simple work?
better if you use ListView and it would be easier to populate the list and getting values from other EditText's.
I can give you an idea... just see this code what I'm doing in this :
public class RecordExpenseAdapter extends ArrayAdapter<HashMap<String, String>>
{
Intent intent;
Context context;
int layoutResourceId;
ArrayList<HashMap<String, String>> RecordList = new ArrayList<HashMap<String, String>>();
public RecordExpenseAdapter(Context context, int layoutResourceId,ArrayList<HashMap<String, String>> RecordList)
{
super(context, layoutResourceId, RecordList);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.RecordList = RecordList;
this.intent = new Intent(context, ScanReceipt.class);
//Log.d("ASD:","comp intialize");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
try{
if(row == null)
{
Log.d("ASD:","insdie getview");
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.categoryName = (TextView)row.findViewById(R.id.textView1);
holder.date = (TextView)row.findViewById(R.id.textView2);
holder.amount = (TextView)row.findViewById(R.id.textView3);
holder.record_rid = (TextView)row.findViewById(R.id.ridRecord);
holder.cid=(TextView)row.findViewById(R.id.cid);
holder.vendor=(TextView)row.findViewById(R.id.vendor);
holder.description=(TextView)row.findViewById(R.id.desc);
holder.attachURL=(TextView)row.findViewById(R.id.userFile);
holder.attachImage=(ImageView)row.findViewById(R.id.attachment);
holder.scanReceipt = (ImageView)row.findViewById(R.id.imageView2);
row.setTag(holder);
holder.scanReceipt.setTag(position);
holder.scanReceipt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Log.e("Scan Receipt Button List", "1");
ImageView iv = (ImageView) v;
Log.e("Scan Receipt Button List", "2");
int pos = (Integer) iv.getTag();
Log.e("Scan Receipt Button List", "3");
ScanReceipt.rid = RecordList.get(pos).get("rid").toString();
Log.e("Scan Receipt Button List", "4");
//Toast.makeText(context, "Button Clicked", Toast.LENGTH_LONG).show();
RecordExpenseAdapter.this.doIt();
}catch(Exception e){
Log.e("Error on click on Scan Receipt Button List", e.getMessage().toString());
}
}
});
// if(picture.get("userfile")=="no")
// {
// holder.attachImage.setVisibility(View.INVISIBLE);
// }
// else
// {
// holder.attachImage.setVisibility(View.VISIBLE);
// }
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
HashMap<String, String> picture = RecordList.get(position);
holder.categoryName.setText(picture.get("category_name"));
holder.date.setText(picture.get("date"));
holder.amount.setText(picture.get("amount"));
holder.record_rid.setText(picture.get("rid"));
holder.cid.setText(picture.get("cid"));
holder.vendor.setText(picture.get("vendor"));
holder.description.setText(picture.get("description"));
holder.attachURL.setText(picture.get("image"));
Log.e("Record Expense Adapter 0 : IMAGE", picture.get("image").toString());
Log.e("RID : " + position, picture.get("rid").toString());
// Log.e("error value", picture.get("userfile"));
//Log.e("error value", "value is error");
// if(picture.get("userfile")=="no")
// {
// holder.attachImage.setVisibility(View.INVISIBLE);
// }
//
// else
// {
// holder.attachImage.setVisibility(View.VISIBLE);
// }
if(picture.get("image").toString().trim().equalsIgnoreCase("no")){
holder.scanReceipt.setVisibility(View.VISIBLE);
holder.attachImage.setVisibility(View.INVISIBLE);
}else{
holder.scanReceipt.setVisibility(View.GONE);
holder.attachImage.setVisibility(View.VISIBLE);
}
}
catch(Exception e){
}
return row;
}
public void doIt(){
Log.e("Adapter 0", "In do It");
context.startActivity(intent);
}
static class ImageHolder
{
TextView categoryName;
TextView date;
TextView amount;
TextView record_rid;
TextView vendor;
TextView cid;
TextView description;
TextView attachURL;
ImageView attachImage,scanReceipt;
}
}
in above code, I have implemented the click listener on ImageView scanReceipt. It's the same imageview each time i.e. the same layout is inflated for each row, which means the same id is inflated for all the rows but still this click event will perform a different task for different row.
what you need to do is : simply use the EditText as I'm using the ImageView. Implement the TextWatcher as I'm implementing the click listener.
you have to use custom list for that say this-
List<CustomClass> list = new ArrayList<CustomClass>();
in this custom class, put the public variables so that you can access those by object of CustomClass and add that object to this above created list.
Once you get the values in this list, you can use it any way you want.
I hope it would help... :)

#Prakash
thanxx for idea dude
Now, I attached textwatcher to edittext field and managed to get rowid
with the help of this
price_text.setTag(c.getPosition());
And retreive that position in afterTextChanged
price_text.getTag()
But now how could i save that values Like you said in above post....

Related

Is it possible to add different items into android listview

i have a ListView in my application, i fetch contacts from user phonebook then displays them into ListView, now what i want to do is to add different child views into ListView item based on some condition like my application check each phonebook contact for it's availability on server database and what i want to achieve is to add voice/video call buttons for that particular contact and add invite button for all other contacts that are not available in database.
My condition applies on these three child's of ListView item, voice call button, video call button and invite button and my condition is if user is available in database then i only want to display voice/video call button and hide invite button but if the user is not available then i wan to display invite button and hide audio/video call buttons
ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/contacts_listview"/>
</RelativeLayout>
ListView Item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:minHeight="?android:attr/listPreferredItemHeight"
android:padding="16dp">
<ImageView
android:id="#+id/contact_item_icon"
android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/contact_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Feel The Light" />
<TextView
android:id="#+id/contact_item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home" />
</LinearLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_audio_call_dark"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_video_call_dark"/>
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Invite"
android:background="#drawable/selector_button_green_oval"
android:textColor="#color/white"/>
</LinearLayout>
ContactsFragment
public class ContactsAdapter extends ArrayAdapter<ContactItem> {
private static final String LOG_TAG = ContactsAdapter.class.getSimpleName();
public ContactsAdapter(Activity context, List<ContactItem> contactItems) {
super(context, 0, contactItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactItem contactItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.contact_list_item, parent, false);
}
ImageView contactImage = (ImageView) convertView.findViewById(R.id.contact_item_icon);
contactImage.setImageResource(contactItem.contactImage);
TextView contactName = (TextView) convertView.findViewById(R.id.contact_item_name);
contactName.setText(contactItem.contactName);
TextView contactNumber = (TextView) convertView.findViewById(R.id.contact_item_number);
contactNumber.setText(contactItem.contactNumber);
return convertView;
}
}
ContactsFragment
public class ContactsListFragment extends Fragment {
private ContactsAdapter contactsAdapter;
public static ContactsListFragment newInstance() {
return new ContactsListFragment();
}
public ContactsListFragment() {
}
ArrayList<String> contactName = new ArrayList<>();
ArrayList<String> contactNumber = new ArrayList<>();
ArrayList<ContactItem> contactsAvailable = new ArrayList<>();
ArrayList<ContactItem> contactsInvite = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null
);
String currentNumber = "";
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
number = number.replaceAll(" ", "");
char c = number.charAt(0);
char c1 = number.charAt(1);
String s = Character.toString(c)+Character.toString(c1);
if (s.equals("00")) {
number = number.replaceAll("00", "+");
}
if (number.length() == 12) {
number = "+" + number;
}
if (number.length() == 13) {
if (!currentNumber.equals(number)) {
contactName.add(name);
contactNumber.add(number);
}
}
currentNumber = number;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_contacts_list, container, false);
QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
pagedRequestBuilder.setPage(1);
pagedRequestBuilder.setPerPage(50);
QBUsers.getUsersByLogins(contactNumber, pagedRequestBuilder, new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
for (int i = 0; i < qbUsers.size(); i++) {
ContactItem contactItem = new ContactItem(qbUsers.get(i).getFullName(), qbUsers.get(i).getLogin(), R.drawable.ic_launcher);
contactsAvailable.add(contactItem);
}
contactsAdapter = new ContactsAdapter(getActivity(), contactsAvailable);
ListView listView = (ListView) rootView.findViewById(R.id.contacts_listview_available);
listView.setAdapter(contactsAdapter);
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
Try this:
Add a boolean flag isAvailableInDB in your ContactItem.java class.
Get contact list from your phonebook and check one by one with your server database.
If a contactItem exist in your database just set flag isAvailableInDB as true oterwise false for that contactItem.
After that add contactItem to ArrayList
Create ContactsAdapter and set it to ListView
Finally, add a condition in your adapter's getView() method to check the contactItem flag isAvailableInDB. If true, show voice/video call button & hide invite button and if false, show invite button & hide voice/video call button.
Give an id to XML button's:
<ImageButton
android:id="#+id/button_voice_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_audio_call_dark"/>
<ImageButton
android:id="#+id/button_video_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user_video_call_dark"/>
<Button
android:id="#+id/button_invite"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Invite"
android:background="#drawable/selector_button_green_oval"
android:textColor="#color/white"/>
In your adapter's getView() method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactItem contactItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.contact_list_item, parent, false);
}
ImageView contactImage = (ImageView) convertView.findViewById(R.id.contact_item_icon);
contactImage.setImageResource(contactItem.contactImage);
TextView contactName = (TextView) convertView.findViewById(R.id.contact_item_name);
contactName.setText(contactItem.contactName);
TextView contactNumber = (TextView) convertView.findViewById(R.id.contact_item_number);
contactNumber.setText(contactItem.contactNumber);
ImageButton buttonVoiceCall= (ImageButton) convertView.findViewById(R.id.button_voice_call);
ImageButton buttonVideoCall= (ImageButton) convertView.findViewById(R.id.button_video_call);
Button buttonVoiceCall= (Button) convertView.findViewById(R.id.button_invite);
if(contactItem.getIsAvailableInDB())
{
buttonVoiceCall.setVisibility(View.VISIBLE);
buttonVideoCall.setVisibility(View.VISIBLE);
buttonInvite.setVisibility(View.GONE);
}
else
{
buttonVoiceCall.setVisibility(View.GONE);
buttonVideoCall.setVisibility(View.GONE);
buttonInvite.setVisibility(View.VISIBLE);
}
return convertView;
}
Hope this will help you~
You could add a flag on the ContactItem class and set it true or false, if it is available in the Database and then set the visibility of the buttons in the adapter according to this flag.

Alternate CheckTextBox becoming visible on click

I am trying to make a specific (selected by user) row of a ListView checkbox to become visible. But the problem is,I have dynamically added 10 rows in my list view using class that extends ArrayAdapter and when I select the 1st row then along with my 1st row , 3rd , 5th and so on check box is becoming visible. Similar with 2nd, 4th and so on row.
I just want that particular row (eg position 0) that I selected to show up the check box and rest shoulb be invisible.
public class LazyAdapter extends ArrayAdapter<RowItem> {
Context context;
public LazyAdapter(Context context, int resourceId, List<RowItem> items){
super(context, resourceId, items);
this.context = context;
}
public class ViewHolder{
CheckedTextView checkbox;
TextView title;
TextView description;
LinearLayout card;
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.card = (LinearLayout) convertView.findViewById(R.id.card);
holder.checkbox = (CheckedTextView)convertView.findViewById(R.id.deliverychecktext);
holder.title = (TextView)convertView.findViewById(R.id.title);
holder.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(holder);
} else
holder = (ViewHolder)convertView.getTag();
//holder.image.setImageResource(rowItem.getImageId());
holder.title.setText(rowItem.getTitle());
holder.description.setText(rowItem.getDesc());
Animation animation = AnimationUtils.loadAnimation(context, R.anim.card_animation);
holder.card.startAnimation(animation);
return convertView;
}
}
MainActivity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Intialize and set the Action Bar to Holo Blue
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33b5e5" )));
ListView lv = (ListView) findViewById(R.id.myList);
rowItems = new ArrayList<RowItem>();
String[] titles = {"Address1","Address2","Address3","Address4","Address5","Address6","Address7","Address8"};
String[] descriptions = {"First Address","Second Address","Third Address","Fourth Address","Fifth Address",
"Sixth Address","Seventh Address","Eighth Address"};
//Populate the List
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem("Delivery Address :", descriptions[i]);
rowItems.add(item);
}
// Set the adapter on the ListView
LazyAdapter adapter = new LazyAdapter(getApplicationContext(), R.layout.list_row, rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
CheckedTextView check = (CheckedTextView) view.findViewById(R.id.deliverychecktext);
if (check.getVisibility() == 4)
check.setVisibility(1);
else
check.setVisibility(4);
Toast.makeText(getApplicationContext(), "h u clicked : "+position,
Toast.LENGTH_LONG).show();
}
});
list_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/card_no_border"
android:orientation="vertical"
android:padding="2dp"
android:id="#+id/card">
<CheckedTextView
android:id="#+id/deliverychecktext"
android:layout_width="fill_parent"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_height="wrap_content"
android:checkMark="#drawable/ic_launcher"
android:visibility="invisible"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Dog Tag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#040404"
android:textStyle="bold"
android:typeface="sans" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e5e5e5">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Saved Address"
android:textSize="20sp"
android:padding="5dp"/>
<ListView
android:id="#+id/myList"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:divider="#android:color/transparent"
android:dividerHeight="10dp"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="1dip"/>
</LinearLayout>
First one RowItem as class varible to store the selected items.
private RowItem mSelectedItem = null;
ex
public class LazyAdapter extends ArrayAdapter<RowItem> {
Context context;
private RowItem mSelectedItem = null;
After that add the below listener to your LazyAdapter adapter class.
/**
* On Click Listener for the view.
*/
protected class OnViewClickListener implements
android.view.View.OnClickListener {
private RowItem mItem;
public OnViewClickListener(RowItem item) {
mItem = item;
}
#Override
public void onClick(View v) {
mSelectedItem = mItem;
notifyDataSetChanged();
}
}
call this listener from your getView method in LazyAdapter before return view and add logic for the show and hid the view.
ex :
if(mSelectedItem != null && mSelectedItem == rowItem) {
holder.checkbox.setVisibility(View.VISIBLE);
} else {
holder.checkbox.setVisibility(View.INVISIBLE);
}
convertView.setOnClickListener(new OnViewClickListener(rowItem));
return convertView;
}
And remove click lister in ur activity.
on your activity its working because while rendering the adapter view it will reuse the object, so it was happening like that. Now we are checking and updating every time while view rendering.

Android getView : Why getView not called?

I add two buttons (add and delete) to control the list view, when I delete an item, the item won't immediately disappear in the listview, only when I slide on the listview, the new item disappears. The getView() in my adapter won't be called after I delete an item unless I touch the screen or slide on the listview. can someone tell me why?
My xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/locationlist_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >"
<RelativeLayout
android:id="#+id/locationlisttitle_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:background="#ADD8E6">
<ImageView
android:id="#+id/iv_menu2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:src="#drawable/img_menu" />
<TextView
android:id="#+id/txtv_locationmanagetitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Manage Location List"
android:textSize="20sp" />
<ImageView
android:id="#+id/iv_addlocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/txtv_locationmanagetitle"
android:src="#drawable/addlocation" />
<ImageView
android:id="#+id/iv_deletelocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/iv_addlocation"
android:src="#drawable/deletelocation" />
</RelativeLayout>
<ListView
android:id="#+id/lv_locations"
android:layout_height="500dp"
android:layout_width="fill_parent" />
</LinearLayout>
My button click event handler
ivbtn_deleteLocation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//remove selected items from the locationList
Collections.sort(listStr);
for (int i = listStr.size()-1; i >= 0; i--) {
Log.i("zhijianw", "remove"+listStr.get(i));
Log.i("zhijianw", "remove"+locationList.get(Integer.parseInt(listStr.get(i))).get("txtv_locationitem"));
String remLocation = locationList.get(Integer.parseInt(listStr.get(i))).get("txtv_locationitem").toString();
locationList.remove(Integer.parseInt(listStr.get(i)));
removeLocation(remLocation);
}
listStr = new ArrayList<String>();
locationsAdapter.notifyDataSetChanged();
}
});
My Adapter
public MyAdapter(Context context, List<HashMap<String, Object>> list, int resource, String[] from, int[] to) {
this.context = context;
this.list = list;
keyString = new String[from.length];
idValue = new int[to.length];
System.arraycopy(from, 0, keyString, 0, from.length);
System.arraycopy(to, 0, idValue, 0, to.length);
inflater = LayoutInflater.from(context);
init();
Log.i("zhijianw", "my adapter called");
}
public void init() {
isSelected = new HashMap<Integer, Boolean>();
for (int i = 0; i < list.size(); i++) {
isSelected.put(i, false);
}
}
#Override
public int getCount() {
Log.i("zhijianw", "get count called");
return list.size();
}
#Override
public Object getItem(int arg0) {
Log.i("zhijianw", "get item called");
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
init();
Log.i("zhijianw", "get view called");
ViewHolder holder = null;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.location_item, null);
holder.tv = (TextView) view.findViewById(R.id.txtv_locationitem);
holder.cb = (CheckBox) view.findViewById(R.id.cb_locationitem);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
HashMap<String, Object> map = list.get(position);
if (map != null) {
itemString = (String) map.get(keyString[0]);
holder.tv.setText(itemString);
}
holder.cb.setChecked(isSelected.get(position));
return view;
}
}
Set listview adapter
lv_menu = (ListView) menu_view.findViewById(R.id.lv_menu);
lv_menu.setAdapter(new ArrayAdapter<String>(this, R.layout.menu_item, R.id.txtv_menuItem, menuChoices));
The locationsAdapter does not appear to be getting set to the same adapter used by lv_menu.setAdapter() so that locationsAdapter.notifyDataSetChanged() is not invalidating lv_menu. Try lv_menu.invalidate() directly in your onClick() function.
I personally reload my list adapters from scratch whenever deleting items, especially when CheckBox items are involved, in order to keep things from getting out of sync.
Please check that the parameter transfered to the inflater (in the getView method) refer to the same parameter which was used when the adapter was intiated. In the case that they are not the same the getView will not be called without any further notification.
Zohar

ListView item can not clicked, not any other listeners getting called

I have made one custom ListView but it is not calling any onclick listener or context menu that I have registered.
Here is my custom adapter:
class AdapterContactsActivity extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> rowdata;
private static LayoutInflater inflater = null;
public ArrayList<String> checkedContacts = new ArrayList<String>();
public AdapterContactsActivity(Activity a,
ArrayList<HashMap<String, String>> d) {
activity = a;
rowdata = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return rowdata.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(R.layout.item_listview_contacts,
null);
final ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.chkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
final HashMap<String, String> row = rowdata.get(position);
// Setting all values in listview
holder.txtTitle.setText(row.get(EmsContactsActivity.KEY_TITLE));
final String contact_id = row.get(EmsContactsActivity.KEY_ID);
convertView.setTag(contact_id);
holder.txtTitle.setTag(contact_id);
if (checkedContacts.contains(contact_id))
holder.chkBox.setChecked(true);
else
holder.chkBox.setChecked(false);
holder.chkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (!holder.chkBox.isChecked()
&& checkedContacts.contains(contact_id))
checkedContacts.remove(contact_id);
else {
checkedContacts.add(contact_id);
}
}
});
return convertView;
}
static class ViewHolder {
public TextView txtTitle;
public CheckBox chkBox;
}
}
Also my row's item view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/checkBox1"
android:padding="5dp"
android:textAppearance="#android:style/TextAppearance.Large"
android:textColor="#android:color/white" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="5dp" />
</RelativeLayout>
Now I have added all contacts to the adapter but the on click of ListView item I can not even get logcat notification also so on click event I not called.
ListView Code :
Cursor allContacts = getAllContacts();
if (allContacts != null && allContacts.getCount() > 0) {
txtEmptyText.setVisibility(View.GONE);
registerForContextMenu(listViewContacts);
listViewContacts.setVisibility(View.VISIBLE);
listViewContacts.setFastScrollEnabled(true);
listViewContacts.setTextFilterEnabled(true);
listViewContacts.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewContacts.setBackgroundColor(Color.TRANSPARENT);
searchList = new ArrayList<HashMap<String, String>>();
searchList = getArrayListWithContacts(allContacts);
txtTotalContacts.setText("Displaying " + allContacts.getCount()
+ " contacts");
// Wrap your adapter within the SimpleSectionAdapter
searchAdapter = new AdapterContactsActivity(this, searchList);
// Set the adapter to your ListView
listViewContacts.setAdapter(searchAdapter);
listViewContacts.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long arg3) {
// TODO Auto-generated method stub
Log.i("CLICKED", position + " clicked");
}
});
} else // No Contacts Found
{
String text = "<div>You don't have any contacts to display.<br /><br />"
+ "To add a contacts, <b>Menu</b> and touch:<br /><br />"
+ "• <b style='color:#FFFFFF;'>Accounts</b> to add or configure and account with contacts you can sync to the phone<br /><br />"
+ "• <b>New Contact</b> to create a new contact from scratch<br /><br />"
+ "• <b>Import/Export</b></div>";
txtEmptyText.setVisibility(View.VISIBLE);
listViewContacts.setVisibility(View.GONE);
txtEmptyText.setText(Html.fromHtml(text));
editSearchContacts.setEnabled(false);
}
Set the focusable property on the CheckBox to false:
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="5dp"
android:focusable="false" />
Also, you may want to inflate the row layout like this:
convertView = inflater.inflate(R.layout.item_listview_contacts, parent, false);
Your CheckBox has onClickListener so it can grab listview's click events.
Are you using OnItemClickListener on your ListView when you try to handle click events ( listView.setOnItemClickListener(...)) ?
If You are creating any custom row layout for the list item then.
Inside Row.xml
In Parent Linear Layout Or Relative LAyout you should put the one line
android:descendantFocusability="blocksDescendants"
This is working fine for me.

Android - empty list in Custom List view

Here is my custom List view layout.
I've added an "empty list" text view with id "android:empty", but the 'empty text' view is not displayed when the list is empty.
Any advice please.
UPDATE - updated the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight"
android:paddingLeft="5dip" android:paddingRight="5dip"
android:paddingTop="15dip" android:paddingBottom="15dip"
android:cacheColorHint="#color/match_bg2" android:background="#color/match_bg">
<ImageView android:id="#+id/flag_left" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="#drawable/flag"
android:src="#drawable/flag_default" />
<LinearLayout android:orientation="vertical"
android:padding="10dip" android:layout_width="0dip" android:gravity="center"
android:layout_weight="1" android:layout_height="fill_parent">
<TextView android:id="#+id/item_match_label"
android:layout_width="wrap_content" android:layout_height="0dip"
android:layout_weight="1" android:gravity="center"
android:textColor="#color/match_fg" android:textStyle="bold"
android:singleLine="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
/>
</LinearLayout>
<ImageView android:id="#+id/flag_right" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="#drawable/flag"
android:src="#drawable/flag_default" />
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
Here is my Listview Activity
public class LatestMatchesListActivity extends ListActivity {
...
private void createMatchList() {
/*
Log.i(MY_DEBUG_TAG, "Checking Match store size before passing it to custom adapter: "+mStore.size());
if(mStore.size() == 0){
Log.i(MY_DEBUG_TAG, "Got Empty match store, so checking connectivity..");
Match m = new Match();
if(isOnline()){
Log.i(MY_DEBUG_TAG, "Internet is accessible, so adding no matches object: ");
m.setId(-1);
} else{
Log.i(MY_DEBUG_TAG, "No Internet accessible, so adding mo caonnectivity match object: ");
m.setId(-2);
}
mStore.add(m);
} else {
Log.e(MY_DEBUG_TAG, "Match store is not empty ");
}
*/
//mStore.clear();
Log.i(MY_DEBUG_TAG, "Passing match list to custom adapter: "+mStore.toString());
this.mAdapter = new MatchAdapter(this, R.layout.list_matches, mStore);
this.setListAdapter(this.mAdapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setBackgroundDrawable(null);
lv.setBackgroundResource(0);
}
and the custom ArrayAdapter
public class MatchAdapter extends ArrayAdapter<Match> {
private ArrayList<Match> items;
private final String MY_DEBUG_TAG = "MatchAdapter";
public MatchAdapter(Context context, int textViewResourceId, ArrayList<Match> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_matches, null);
}
Match m = items.get(position);
if (m != null) {
TextView itemLabel = (TextView) v.findViewById(R.id.item_match_label);
ImageView imageFlagLeft = (ImageView) v.findViewById(R.id.flag_left);
ImageView imageFlagRight = (ImageView) v.findViewById(R.id.flag_right);
if(m.getId() == -1){
itemLabel.setText("No Live Matches.");
imageFlagLeft.setVisibility(View.INVISIBLE);
imageFlagRight.setVisibility(View.INVISIBLE);
} else if(m.getId() == -2){
itemLabel.setText("No Intenet connectivity.");
imageFlagLeft.setVisibility(View.INVISIBLE);
imageFlagRight.setVisibility(View.INVISIBLE);
} else {
itemLabel.setText(m.getTeam1() + " v/s " + m.getTeam2());
imageFlagLeft.setImageResource(getFlagResource(m.getTeam1()));
imageFlagRight.setImageResource(getFlagResource(m.getTeam2()));
}
}
return v;
}
private int getFlagResource(String teamName) {
Log.i(MY_DEBUG_TAG, "Getting the flag of " + teamName);
String flagString = "flag_" + teamName.replace(" ", "_").toLowerCase();
int resId = getContext().getResources().getIdentifier(flagString, "drawable", "com.itflux.DroidChirp");
if (resId != 0) {
return resId;
}
return R.drawable.flag_default;
}
}
You have your ListView fit the screen, and in LinearLayout your TextView is displayed under that ListView so it's not visible (it would be, if you'd use a ScrollView).
You need to use as the root element of your layout a RelativeLayout for instance, to have the TextView on top of the ListView.
Seems like the question is still unsolved. So here is how I solved it. I triggered a function which will basically refresh the list layout whenever the data changes as below:
ListView lv = getListView();
lv.requestLayout();
if(aa.arrayValue.size() > 0) {
lv.setVisibility(ListView.VISIBLE);
setListAdapter(new Adaptor(this, R.layout.main_list_item, aa.arrayValue));
}
else {
lv.setVisibility(ListView.INVISIBLE);
TextView tv = (TextView) findViewById(android.R.id.empty);
tv.requestLayout();
tv.setVisibility(TextView.VISIBLE);
}
Hope this helps you out!
Use #+id in empty and #id in list : android:id="#+id/android:empty"
Your problem is with the ListView height property. Set it to wrap_content.

Categories

Resources