How to remove selected item from all the other spinners in android - android

I am a beginner in android.I have a ListView containing a spinner,edittext and an imagebutton which is for deleting that row.The spinner is populated from a list.There is a add button which add these item to the listview when each time it clicks.If i select an item in a spinner then i need to remove that item from all the other spinner in that listview and also the items become visible when i deleted the selected spinner row or change the selected item in the spinner.Say for simplicity that my Spinners are populated with the following data:
{"data1", "data2", "data3", "data4", "data5"};
For example, if I select my first ListView's Spinner value to be "data3" and then the "data3" entry disappears from all the other ListView Spinner and this will appears back only when i change the selected value in the first listview spinner or deleting that row, similarly for each ListView spinner.How to do this? Somebody please help me.Below is my code.
receipt_trans.xml:
<?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="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinLay3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtGrossAmt"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:text="Gross amount :"
android:textColor="#000" />
<EditText
android:id="#+id/edtGrossAmt"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:background="#drawable/border"
android:focusableInTouchMode="false"
android:layout_toRightOf="#+id/txtAccount" />
<Button
android:id="#+id/btnAddRow"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_marginLeft="10dp"
android:text="Add Row"
android:layout_toRightOf="#+id/edtGrossAmt" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinLay4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtFundStores"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="Fund Stores"
android:textColor="#000" />
</LinearLayout>
<ListView
android:id="#+id/lstFundStore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
</ListView>
</LinearLayout>
fundstore_row.xml:
<?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="fill_parent"
android:orientation="horizontal" >
<Spinner
android:id="#+id/spnAccount"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/textView1" />
<EditText
android:id="#+id/edtAccAmount"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:inputType="numberDecimal"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<ImageButton
android:id="#+id/imgDel"
android:layout_width="20sp"
android:layout_height="fill_parent"
android:contentDescription="delete"
android:src="#drawable/delete2" />
</LinearLayout>
ReceiptTransaction.java:
public class ReceiptTransaction extends Activity{
RestTemplate restTemplate=new RestTemplate();
String constr="http://192.168.1.14:8080/ServPro/stock/";
ListView lstFund;
Button btnAddRw;
private FundStoreAdapter adapter;
ArrayList<COAAccount> subList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.receipt_trans);
lstFund=(ListView) findViewById(R.id.lstFundStore);
btnAddRw=(Button) findViewById(R.id.btnAddRow);
setFundStore();
setDeduction();
btnAddRw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.add(new FundReceipt(subList.get(0), 0.0f));
}
});
}
public void setFundStore(){
String accList=restTemplate.getForObject(constr+"getAllCBOnly", String.class);
Gson gson = new Gson(); // Or use new GsonBuilder().create();
CoaAccountList dropCoaList = gson.fromJson(accList, CoaAccountList.class);
subList=new ArrayList<COAAccount>();
COAAccount newAccount = new COAAccount();
newAccount.setFunds(-1, -2, "Select...", "select", "SE",0.0f);
subList.add(newAccount);
ArrayList<COAAccount> listItem=(ArrayList<COAAccount>) dropCoaList.getCoaList();
for(COAAccount addCoa:listItem){
subList.add(addCoa);
}
adapter=new FundStoreAdapter(ReceiptTransaction.this, R.layout.fundstore_row, new ArrayList<FundReceipt>(),subList);
lstFund.setAdapter(adapter);
adapter.add(new FundReceipt(subList.get(0), 0.0f));
}
public void setDeduction(){
}
}
FundStoreAdapter.java:
public class FundStoreAdapter extends ArrayAdapter<FundReceipt> {
protected static final String LOG_TAG = FundStoreAdapter.class.getSimpleName();
private final Context context;
private final int resourceID;
private List<FundReceipt> items;
private ArrayList<COAAccount> list;
public FundStoreAdapter(Context context, int resource, List<FundReceipt> items, ArrayList<COAAccount> subList) {
super(context, resource,items);
this.context = context;
this.resourceID = resource;
this.items=items;
this.list=subList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FundStoreHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View rowView = inflater.inflate(resourceID, parent, false);
holder=new FundStoreHolder();
holder.fundRecpt=items.get(position);
holder.imgDeleteFund=(ImageButton) rowView.findViewById(R.id.imgDel);
holder.imgDeleteFund.setTag(holder.fundRecpt);
removeRow(holder);
holder.edtAmount=(EditText) rowView.findViewById(R.id.edtAccAmount);
setValueTextListeners(holder);
holder.spnAcct=(Spinner) rowView.findViewById(R.id.spnAccount);
setNameTextChangeListener(holder);
rowView.setTag(holder);
setupItem(holder);
return rowView;
}
private void removeRow(FundStoreHolder holder) {
holder.imgDeleteFund.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FundReceipt itemToRemove = (FundReceipt)v.getTag();
remove(itemToRemove);
}
});
}
private void setupItem(FundStoreHolder holder) {
holder.edtAmount.setText(String.valueOf(holder.fundRecpt.getAmount()));
//ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
ArrayAdapter<COAAccount> dataAdapter =new ArrayAdapter<COAAccount>(context, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spnAcct.setAdapter(dataAdapter);
holder.spnAcct.setSelection(dataAdapter.getPosition(holder.fundRecpt.getSelAcct()));
}
public static class FundStoreHolder{
FundReceipt fundRecpt;
Spinner spnAcct;
EditText edtAmount;
ImageButton imgDeleteFund;
}
private void setNameTextChangeListener(final FundStoreHolder holder) {
holder.spnAcct.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
holder.fundRecpt.setSelAcct((COAAccount) parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
private void setValueTextListeners(final FundStoreHolder holder) {
holder.edtAmount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.fundRecpt.setAmount(Float.parseFloat(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading float value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
FundReceipt.java:
public class FundReceipt implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private Float amount = 0.0f;
private COAAccount selAcct;
public FundReceipt(COAAccount selAcct, Float amount) {
this.setAmount(amount);
this.setSelAcct(selAcct);
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
public COAAccount getSelAcct() {
return selAcct;
}
public void setSelAcct(COAAccount selAcct) {
this.selAcct = selAcct;
}
}

I faced same problem but i could succeed to remove selected item from list After that i did an alter net. Selected item shown highlighted state in drop down list. I know my answer was not fulfill your question but want to share with you.
Your spinner:
<Spinner
android:id="#+id/sp_handi_cap"
style="#style/SpinnerAppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="#drawable/selector_rectangular_gray_trans_bg"
android:descendantFocusability="afterDescendants"
android:gravity="start"
android:minWidth="250dp"
android:padding="5dp"
android:singleLine="true" />
selector_rectangular_gray_trans_bg.xml
<solid android:color="#android:color/transparent" />
<stroke
android:width="1dp"
android:color="#color/gray6" />
<corners
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" /></shape>
Create layout :
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/selector_spinner_item_activited"
android:gravity="center"
android:padding="3dp"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textSize="12sp" />
selector selector_spinner_item_activited.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/selector_rectangular_black_trans_bg" android:state_activated="true"/>
<item android:drawable="#android:color/transparent"/>
</selector>
Create adapter :
ArrayAdapter objAdapter = new ArrayAdapter<String>(AddStudentActivity.this,
R.layout.layout_text_single_line_activated, getResources()
.getStringArray(R.array.arr_handicap_option));
set adapter in spinner object.
spinner.setAdapter(objAdapter);

Related

ListFragment with checkbox onListItemClick never gets called

I've read some SO questions like this and this but still couldn't figure out whats wrong with my code.
I have a ListFragment, and each row has a TextView and a CheckBox.
Clicking the CheckBox is working, but clicking on the TextView does nothing, and OnListItemClick doesn't get called. I've also tried to dynamically add an OnClickListener, which make it work, but it's not the correct way to do it, and it also lacks the GUI feedback of the click (item being "highlighted" for a sec).
This is my textview_with_checkbox.XML I'm using for each item:
<?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="wrap_content"
android:clickable="true"
android:focusable="true"
android:gravity="left"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<TextView
android:id="#+id/textview_event_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="3dp"
android:paddingTop="5dp"
android:focusable="true"
android:singleLine="false" />
<CheckBox
android:id="#+id/checkbox_for_event_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:focusable="false"
android:clickable="false" />
</LinearLayout>
now the code:
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
displayEventsLogFiles();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String chosenItem = (String) getListAdapter().getItem(position);
mCallBack.onEventItemSelected(chosenItem);
}
static class myCustomAdapterViewHolder
{
public TextView eventName;
public CheckBox eventCheckBox;
}
private class myCustomAdapter extends ArrayAdapter<String>
{
private ArrayList<String> sortedList;
private Context m_oContext;
List<String> m_oValues = null;
public myCustomAdapter(Context cont, int viewResId, List<String> objects)
{
super(cont, viewResId, objects);
m_oContext = cont;
m_oValues = objects;
sortedList = new ArrayList<String>();
for (String str : objects)
sortedList.add(str);
java.util.Collections.sort(sortedList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View l_oRowView = convertView;
myCustomAdapterViewHolder l_oInitializedViewHolder = null;
final int l_nPosition = position;
// Use convertView if possible, otherwise inflate a view:
if (l_oRowView == null)
{
LayoutInflater inflater = (LayoutInflater) m_oContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
l_oRowView = inflater.inflate(R.layout.textview_with_checkbox, parent, false);
// PlaceHolder pattern:
final myCustomAdapterViewHolder l_oViewHolder = new myCustomAdapterViewHolder();
l_oViewHolder.eventName = (TextView) l_oRowView.findViewById(R.id.textview_event_name);
l_oViewHolder.eventCheckBox = (CheckBox) l_oRowView.findViewById(R.id.checkbox_for_event_name);
l_oViewHolder.eventCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
//cb.setChecked(!cb.isChecked());
String l_sFilename = l_oViewHolder.eventName.getText().toString();
if (cb.isChecked())
{
if (!m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.add(l_sFilename);
}
else
{
if (m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.remove(l_sFilename);
}
}
});
l_oViewHolder.eventCheckBox.setFocusable(false);
//l_oViewHolder.eventCheckBox.setClickable(false);
// "Add" the viewHolder as a tag:
l_oRowView.setTag(l_oViewHolder);
l_oInitializedViewHolder = l_oViewHolder;
}
else
l_oInitializedViewHolder = (myCustomAdapterViewHolder) l_oRowView.getTag();
// By now, the rowView is initialized, just get the viewHolder and then get the views from it, to update:
//myCustomAdapterViewHolder l_oViewHolder = (myCustomAdapterViewHolder) l_oRowView.getTag();
/*l_oInitializedViewHolder.eventName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallBack.onEventItemSelected((String)getListAdapter().getItem(l_nPosition));
}
});*/
l_oInitializedViewHolder.eventName.setText(m_oValues.get(position));
return l_oRowView;
//return super.getView();
}
public myCustomAdapter(Context cont, int viewResId, String[] strings)
{
this(cont, viewResId, Arrays.asList(strings));
}
#Override
public String getItem(int position)
{
return sortedList.get(position);
}
#Override
public int getPosition(String item)
{
return sortedList.indexOf(item);
}
}
What am I doing wrong here?
All I want is to be able to select "files" for deletion, using the CheckBoxes
Try only using only onclick for textview and checkbox, not onListItemClick -which you can remove- as well, so you should change some properties for the linear layout as well.
<?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="wrap_content"
android:clickable="false"
android:focusable="false"
android:gravity="left"
android:orientation="horizontal" >
<TextView
android:id="#+id/textview_event_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="3dp"
android:paddingTop="5dp"
android:focusable="true"
android:singleLine="false" />
<CheckBox
android:id="#+id/checkbox_for_event_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:focusable="false"
android:clickable="false" />
</LinearLayout>
Implement in the adapter
// PlaceHolder pattern:
final myCustomAdapterViewHolder l_oViewHolder = new myCustomAdapterViewHolder();
l_oViewHolder.eventName = (TextView) l_oRowView.findViewById(R.id.textview_event_name);
l_oViewHolder.eventCheckBox = (CheckBox) l_oRowView.findViewById(R.id.checkbox_for_event_name);
l_oViewHolder.eventName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code for textview click
}
}
l_oViewHolder.eventCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
//cb.setChecked(!cb.isChecked());
String l_sFilename = l_oViewHolder.eventName.getText().toString();
if (cb.isChecked())
{
if (!m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.add(l_sFilename);
}
else
{
if (m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.remove(l_sFilename);
}
}
});
l_oViewHolder.eventCheckBox.setFocusable(false);
add following attribute:
android:focusable="false"
android:clickable="false"
for example in my xml file:
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:button="?android:attr/listChoiceIndicatorSingle"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:buttonTint="#color/gray"
android:focusable="false"
android:clickable="false"
/>
and in my code:
public class MyTestFragment extends ListFragment {
.....
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}

Android - Listview not showing the last item

My Problem is the last item in the listview is not displaying even though it has been added to the adapter and as well as in the list as i can see the number of items in the adapter is ok. Is it the problem with the layout? this is my layout
<?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="match_parent"
android:background="#drawable/golive_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/Room"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus android:layout_width="wrap_content" />
</EditText>
<Button
android:id="#+id/Search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search" />
<ImageButton
android:id="#+id/CreateRoomimageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/closed_doorplus" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/listRooms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:transcriptMode="alwaysScroll">
</ListView>
</LinearLayout>
</LinearLayout>
This is my class activity
public class chatRoomsListActivity extends Activity implements OnScrollListener {
private static String Password;
private ListView lv;
private static Collection<HostedRoom> rooms;
private static ArrayList<String> Roomlist = new ArrayList<String>();
private static Handler mHandler = new Handler();
private Button SearchButton;
private ImageButton CreateButton;
private EditText EditTextSearch;
private String Search;
private String RoomName;
private static ChatRoomListAdapter adapter;
private static String Nickname="";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_rooms);
SearchButton=(Button)findViewById(R.id.Search1);
CreateButton=(ImageButton)findViewById(R.id.CreateRoomimageButton);
lv = (ListView) findViewById(R.id.listRooms);
adapter = new ChatRoomListAdapter(getApplicationContext(),
R.layout.chat_rooms_wrapper);
lv.setAdapter(adapter);
//ScrollView.measureChildWithMargins();
try {
populate_RoomList();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addListenerOnButton();
/*
arrayAdapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,Roomlist);
lv.setAdapter(arrayAdapter);
*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet,
android.view.View view,
int position, long id) {
setRoomName(ChatRoomListAdapter.getItemName(position));
showOptionDialog();
}
});
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
CreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
createRoomDialog();
}
});
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditTextSearch=(EditText) findViewById(R.id.Room);
Search=EditTextSearch.getText().toString();
//Search=Search.concat("*");
try {
// populate_RoomList();
getSearchlist();
// updateList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void getSearchlist() throws XMPPException{
Roomlist.clear();
adapter.clear();
ChatRoomListAdapter.getChatRoom().clear();
rooms=getHostedRooms(MyService.getConnection(),"conference."+
MyService.getDomain());
System.out.println("in getsearch");
for (HostedRoom h : rooms)
{
System.out.println(h.getName().toString()+" contain " +Search);
if(h.getName().toString().contains(Search)){
System.out.println("roomlist= " +h.getJid().toString());
Roomlist.add(h.getName());
System.out.println("ChatRooms.IsRoomPassProtected(h.getName())==
"+ChatRooms.IsRoomPassProtected(h.getName()));
if(ChatRooms.IsRoomPassProtected(h.getName())==true){
adapter.add(new ChatRoom(h.getName(),true));
}
else if(ChatRooms.IsRoomPassProtected(h.getName())==false){
adapter.add(new ChatRoom(h.getName(),false));
}
}
}
System.out.println("Adapter count="+adapter.getCount());
}
private void populate_RoomList() throws XMPPException {
//chatRoomsList.getRooms();"
Roomlist.clear();
adapter.clear();
//rooms.clear();
ChatRoomListAdapter.getChatRoom().clear();
rooms=getHostedRooms(MyService.getConnection(),"conference."+
MyService.getDomain());
//System.out.println(rooms.iterator().next().getName());
for (HostedRoom h : rooms)
{
System.out.println("roomlist= " +h.getName().toString());
Roomlist.add(h.getName());
System.out.println("ChatRooms.IsRoomPassProtected(h.getName())==
"+ChatRooms.IsRoomPassProtected(h.getName()));
if(ChatRooms.IsRoomPassProtected(h.getName())==true){
adapter.add(new ChatRoom(h.getName(),true));
}
else if(ChatRooms.IsRoomPassProtected(h.getName())==false){
adapter.add(new ChatRoom(h.getName(),false));
}
}
System.out.println("Adapter count="+adapter.getCount());
}
public void setRoomName(String roomName) {
RoomName = roomName;
}
public static Collection<HostedRoom> getHostedRooms(Connection connection, String serviceName)
throws XMPPException {
List<HostedRoom> answer = new ArrayList<HostedRoom>();
ServiceDiscoveryManager discoManager = new
ServiceDiscoveryManager(connection);
DiscoverItems items = discoManager.discoverItems(serviceName);
for (Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext();) {
answer.add(new HostedRoom(it.next()));
}
return answer;
}
}
And this is my custom adapter
public class ChatRoomListAdapter extends ArrayAdapter<ChatRoom> {
private TextView name;
private static List<ChatRoom> ChatRoom = new ArrayList<ChatRoom>();
private LinearLayout wrapper;
private ImageView lock;
public ChatRoomListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public static List<ChatRoom> getChatRoom() {
return ChatRoom;
}
public static void setChatRoom(List<ChatRoom> chatRoom) {
ChatRoom = chatRoom;
}
public ChatRoom getItem(int index) {
return ChatRoomListAdapter.ChatRoom.get(index);
}
public static String getItemName(int index) {
return ChatRoomListAdapter.ChatRoom.get(index).name;
}
public static void setfriends(List<Friends> friends) {
FriendListAdapter.setFriends(friends);
}
public void add(ChatRoom object) {
System.out.println("IN Chat room list adapter "+" addded");
ChatRoomListAdapter.ChatRoom.add(object);
super.add(object);
}
public void remove(ChatRoom object) {
ChatRoom.remove(object);
super.remove(object);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_rooms_wrapper, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.C_R_wrapper);
name = (TextView) row.findViewById(R.id.C_R_RoomName);
lock=(ImageView)row.findViewById(R.id.C_R_Lock);
try {
Log.d("Chat room adapter", "heere");
ChatRoom CR= getItem(position);
System.out.println("name= "+CR.name);
name.setText(CR.name);
if(CR.lock==true)
{
lock.setImageResource(R.drawable.lock_lock_icon);
}else{
lock.setImageResource(R.drawable.lock_unlock_icon);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
Thanks in advance.
Add this line to your Viewpager
android:layout_marginBottom="?attr/actionBarSize"
because the size you don't have at the bottom is exactly the size taken by your Toolbar
Example with RecyclerView
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_trips"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginBottom="?attr/actionBarSize"/>
Example with Viewpager
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_trip_history"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize" />
Try this you can solve your problem with this:
You just need to change your xml file as below:
<?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="match_parent"
android:background="#drawable/golive_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="6" >
<EditText
android:id="#+id/Room"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_weight="4">
<requestFocus android:layout_width="wrap_content" />
</EditText>
<Button
android:id="#+id/Search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search"
android:layout_weight="1" />
<ImageButton
android:id="#+id/CreateRoomimageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/closed_doorplus"
android:layout_weight="1" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listRooms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
</LinearLayout>
You can get the last item inside getView of the Adapter and change it layout params height by setLayoutParams. But the minus is you have to correct other items height because the height will change when scroll the list up/down
Maybe its very simple. Try to set the layout_height of your listview in the xml file to wrap_content.
android:layout_height="wrap_content"
Try to set the second LinearLayout holding the Listview to match_parent height... It seems like your LinearLayout is growing with the ListView (wrap_content) out of your screen space

customAdapter for object isnt working

I have a model class. Now from my activity i want to set the values in model class & show them in gridview using my custom adapter. After that i need to store the object in a variable(class type) from gridview's onItemClick. I have done the below codes. But its not working. Where did i go wrong?
activity_country.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".CountryActivity" >
<TextView
android:id="#+id/nTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="26dp"
android:text="Name" />
<TextView
android:id="#+id/aTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nTextView"
android:layout_below="#+id/nTextView"
android:layout_marginTop="24dp"
android:text="About" />
<EditText
android:id="#+id/CountryNameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/nTextView"
android:layout_alignBottom="#+id/nTextView"
android:layout_marginLeft="48dp"
android:layout_toRightOf="#+id/nTextView"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/CountryAboutEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryNameEditText"
android:layout_alignTop="#+id/aTextView"
android:ems="10" />
<Button
android:id="#+id/saveCountryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryAboutEditText"
android:layout_below="#+id/CountryAboutEditText"
android:layout_marginLeft="16dp"
android:layout_marginTop="22dp"
android:text="Save"
android:onClick="saveCountry"
/>
<GridView
android:id="#+id/countryGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/saveCountryButton"
android:layout_centerHorizontal="true"
android:numColumns="2">
</GridView>
</RelativeLayout>
CountryActivity.java
public class CountryActivity extends Activity
{
ArrayList<Country> countries = new ArrayList<Country>();
Country aCountry;
EditText CountryNameTxtBox;
EditText CountryAboutTxtBox;
GridView countrygGridView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country);
// Show the Up button in the action bar.
setupActionBar();
CountryNameTxtBox = (EditText)findViewById(R.id.CountryNameEditText);
CountryAboutTxtBox = (EditText)findViewById(R.id.CountryAboutEditText);
countrygGridView = (GridView)findViewById(R.id.countryGridView);
}
public void saveCountry(View view)
{
String txtName = CountryNameTxtBox.getText().toString();
String txtAbout = CountryAboutTxtBox.getText().toString();
showGrid();
}
public void showGrid()
{
/*
ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(this,android.R.layout.simple_list_item_1, countries);
countrygGridView.setAdapter(adapter);
*/
countrygGridView.setAdapter(new myAdapter(this,countries));
countrygGridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
for(Country mCountry: countries)
{
if(countries.contains(aCountry))
{
Toast.makeText(CountryActivity.this,countries.get(position).getName(), 2000).show();
}
}
}
});
}
countrygrid.xml
<?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="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
</LinearLayout>
myAdapter.java
public class myAdapter extends BaseAdapter
{
Context mycontext;
ArrayList<Country> countries;
public myAdapter(Context c, ArrayList<Country> obj)
{
this.mycontext=c;
this.countries = obj;
}
public int getCount() {
// TODO Auto-generated method stub
return countries.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return countries.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertview, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if(convertview==null)
{
gridView =new View(mycontext);
gridView =inflater.inflate(R.layout.countrygrid, null);
TextView txtvw1 = (TextView) gridView.findViewById(R.id.label1);
txtvw1.setText(countries.get(position).getName());
TextView txtvw2 = (TextView) gridView.findViewById(R.id.label2);
txtvw2.setText(countries.get(position).getAbout());
}
else
{
gridView = (View) convertview;
}
return gridView;
}
}
*Its showing error in countryActivity.java- when i am trying to set the adapter inside showGrid() *
countrygGridView.setAdapter(new myAdapter(this,countries));
public class myAdapter
{
does not extend anything
It should be
public class myAdapter extends BaseAdapter //orArrayAdapter
{
If you still have a problem post the stacktrace for further help

Unable to select an item in a ListView whose content is set by an Array Adapter

I couldn't select an item on ListView. I use Custom Adapter to set content of ListView. I have set OnItemClickListener of ListView. However, it didn't respond. I appriciate your help. Here is my code:
List Item (connections.xml):
<?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="wrap_content"
android:orientation="horizontal"
android:padding="6dip" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:orientation="vertical" >
<TextView
android:id="#+id/connname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/acc1" />
<TextView
android:id="#+id/conntype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="9sp"
android:text="#string/acctype1" />
</LinearLayout>
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The screen which containt ListView (groupconnections.xml):
<?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"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:orientation="vertical"
android:id="#+id/textOperLayout">
<TextView
android:id="#+id/connectionsLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/connections"
android:textColor="#color/conn_text"
android:textSize="25sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:background="#color/conn_back"/>
<EditText
android:id="#+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/searchhint"
android:layout_marginTop="10dp"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dip"
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_above="#+id/textOperLayout"
android:id="#+id/listviewlayout">
<ListView
android:id="#+id/connectionlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice" />
</LinearLayout>
<Button
android:id="#+id/addConnCommitButton"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:text="#string/commitToAdd" />
</RelativeLayout>
The related activity (AddMoreConnections.xml):
public class AddMoreConnections extends Activity implements OnItemClickListener{
private ListView mainListView ;
private ArrayAdapter<AbstractHolder> listAdapter ;
private TextView searchConnTextView;
private Button commitButton;
private ArrayList<AbstractHolder> connlist;
private ArrayList<AbstractHolder> listNotOnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Generate list View from ArrayLis
setContentView(R.layout.groupconnections);
addListenerOnSearchConnTextView();
//Initialize properties
mainListView = (ListView) findViewById( R.id.connectionlist );
mainListView.setOnItemClickListener(this);
// Create and populate a List of planet names.
listNotOnView = new ArrayList<AbstractHolder>();
connlist = new ArrayList<AbstractHolder>(5);
Iterator<AbstractHolder> iter = SocialRssModel.holders.values().iterator();
while(iter.hasNext())
connlist.add(iter.next());
// Create ArrayAdapter using the planet list.
listAdapter = new CustomAdapter(this,
R.layout.connlist, connlist);
mainListView.setAdapter( listAdapter );
}
public void addListenerToFinishButton(){
commitButton = (Button) findViewById(R.id.addConnCommitButton);
commitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void addListenerOnSearchConnTextView(){
searchConnTextView = (TextView) findViewById(R.id.searchEditText);
searchConnTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int listNotOnViewsize = listNotOnView.size();
int connlistsize = connlist.size();
for(int i= 0; i < connlistsize; i++){
if(!connlist.get(i).connNameContains(s.toString())){
listNotOnView.add(connlist.remove(i));
i--;
connlistsize--;
}
}
for(int i=0; i < listNotOnViewsize; i++){
if(listNotOnView.get(i).connNameContains(s.toString())){
connlist.add(listNotOnView.remove(i));
i--;
listNotOnViewsize--;
}
}
((CustomAdapter) listAdapter).updateList(connlist);
listAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
Intent i = new Intent(this, CategoryContentViewerController.class);
Bundle b = new Bundle();
b.putInt("AbstractHolderKey", temp.getId());
i.putExtras(b);
startActivity(i);
finish();
}
private class CustomAdapter extends ArrayAdapter<AbstractHolder> {
private ArrayList<AbstractHolder> connectionList;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<AbstractHolder> connList) {
super(context, textViewResourceId, connList);
this.connectionList = new ArrayList<AbstractHolder>();
this.connectionList.addAll(connList);
}
public void updateList(ArrayList<AbstractHolder> connList){
connectionList.clear();
connectionList.addAll(connList);
}
private class ViewHolder {
TextView name;
TextView acctype;
CheckBox sel;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
convertView = vi.inflate(R.layout.connlist, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.connname);
holder.acctype = (TextView) convertView.findViewById(R.id.conntype);
holder.sel = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
AbstractHolder conn = connectionList.get(position);
holder.name.setText(conn.getName());
holder.acctype.setText(conn.getConntype());
holder.sel.setChecked(conn.isSelected());
holder.sel.setTag(conn);
return convertView;
}
}
}
It is related to checkbox item in connections.xml which is the list row item. If I remove checkbox, related listeners responses. I think, it may be thought there is no need a setItemOnClickListener(..) method since each row has a checkbox. Or it is a bug.

GridView doesn't display content in android

i am trying to display image using GridView. This is the first time i using GridView, so i using the example from here and implement it to mine (i have tried the example that contained there, and it's works).
But, i have checked it many time, there's no error comes from LogCat, no Force Closed, the image didn't show. i have no idea where's the wrong part.
Here's my code:
choosepic.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bg_inner">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/book_inner"
android:layout_marginTop="50dp"
/>
<ImageButton
android:id="#+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/home_btn"
android:background="#null"
/>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/bg_arrow_btn"
android:layout_alignParentRight="true"
/>
<ImageButton
android:id="#+id/nextBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/right_arrow"
android:background="#null"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:layout_marginRight="7dp"
android:layout_marginLeft="7dp"
/>
<ImageButton
android:id="#+id/prevBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/left_arrow"
android:background="#null"
android:layout_toLeftOf="#+id/nextBtn"
android:layout_marginTop="5dp"
/>
<GridView
android:id="#+id/gridView1"
android:numColumns="3"
android:gravity="center"
android:columnWidth="30dp"
android:stretchMode="columnWidth"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="70dp"
>
</GridView>
</RelativeLayout>
animalbutton.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:visibility="gone">
</TextView>
ImageAdapter.java
public class ImageAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
public ImageAdapter(Activity activity,ArrayList<String> listName, ArrayList<Integer> listImage) {
super();
this.listNm = listName;
this.listAnim = listImage;
this.activity = activity;
}
public static class ViewHolder
{
public ImageView imgViewAnim;
public TextView txtViewAnim;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.animalbutton, null);
view.txtViewAnim = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewAnim = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewAnim.setText(listNm.get(position));
view.imgViewAnim.setImageResource(listAnim.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listNm.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
choosepic.java
public class choosepic extends Activity {
/** Called when the activity is first created. */
ImageAdapter mAdapter;
GridView gridView;
static final String[] animal = new String[] {
"cat", "cow","croc", "duck", "elephant", "giraffe", "lion", "moose", "mouse"};
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choosepic);
gridView = (GridView) findViewById(R.id.gridView1);
prepare_list1();
mAdapter = new ImageAdapter(this,listNm, listAnim);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Toast.makeText(getApplicationContext(), mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
public void prepare_list1(){
listNm = new ArrayList<String>();
listAnim = new ArrayList<Integer>();
for (int i = 0; i < animal.length; i++) {
listNm.add(animal[i]);
listAnim.add(getResources().getIdentifier("anim_"+animal[i], "drawable", getPackageName()));
}
}
}
i need some help. i appreciate any help. thank you in advance!
i think the problem is in your getCount() that returns 0 elements
instead of that make it like this
#Override
public int getCount() {
// TODO Auto-generated method stub
return listNm.size();
}

Categories

Resources