I'm trying to make a ListFragment. I looked the Api Demo (FragmentLayout). it works on a simple example and now i want to apply it to my existing project.
Here is my code. I create inner classes (RecipeList & RecipeDetail) as in the Api Demo.
public class InfoActivity extends MenuActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_fragment_layout);
// ...
}
public static class RecipeList extends ListFragment {
private int mCurrentSelectedItemIndex = -1;
private boolean mIsTablet = false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
accountData = new ArrayList<Account>();
new AccountSyncTask() {
#Override
public void onPostExecute(
final ArrayList<ArrayList<String>> result) {
// For each retrieved account
Bd.insert(retrievedAccount);
accountData.add(retrievedAccount);
}
accountListAdapter = new AccountListAdapter(
InfoActivity.this, R.layout.accountlist_detail,
accountData);
accountListAdapter = new AccountListAdapter(
activityContext, R.layout.accountlist_detail,
accountData);
setListAdapter(accountListAdapter);
}
}.execute(sessionName, null, "getAllObjectOnServer",
String.valueOf(nbRow));
if (savedInstanceState != null) {
mCurrentSelectedItemIndex = savedInstanceState.getInt(
"currentListIndex", -1);
}
// This is a tablet if this view exists
View recipeDetails = getActivity()
.findViewById(R.id.recipe_details);
mIsTablet = recipeDetails != null
&& recipeDetails.getVisibility() == View.VISIBLE;
if (mIsTablet) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mIsTablet && mCurrentSelectedItemIndex != -1) {
showRecipeDetails();
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
mCurrentSelectedItemIndex = position;
showRecipeDetails();
}
private void showRecipeDetails() {
if (mIsTablet) {
// Set the list item as checked
getListView().setItemChecked(mCurrentSelectedItemIndex, true);
// Get the fragment instance
RecipeDetail details = (RecipeDetail) getFragmentManager()
.findFragmentById(R.id.recipe_details);
// Is the current visible recipe the same as the clicked? If so,
// there is no need to update
if (details == null
|| details.getRecipeIndex() != mCurrentSelectedItemIndex) {
details = RecipeDetail
.newInstance(mCurrentSelectedItemIndex);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.recipe_details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentListIndex", mCurrentSelectedItemIndex);
}
}
public static class RecipeDetail extends Fragment {
private int mRecipeIndex;
public static RecipeDetail newInstance(int recipeIndex) {
// Create a new fragment instance
RecipeDetail detail = new RecipeDetail();
// Set the recipe index
detail.setRecipeIndex(recipeIndex);
return detail;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater
.inflate(R.layout.recipe_details, container, false);
//..
return v;
}
public int getRecipeIndex() {
return mRecipeIndex;
}
public void setRecipeIndex(int index) {
mRecipeIndex = index;
}
}
I have a custom ArrayAdapter (my items in the ListFragment contain 4 textViews and a clickable imageButton).
AccountListAdapter :
public class AccountListAdapter extends ArrayAdapter<Account> {
private final Context context;
private final int layoutResourceId;
private final ArrayList<Account> data;
public AccountListAdapter(Context context, int layoutResourceId,
ArrayList<Account> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
AccountHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
holder = new AccountHolder();
convertView.setClickable(true);
convertView.setFocusable(true);
holder.txtName = (TextView) convertView.findViewById(R.id.nom);
holder.txtId = (TextView) convertView.findViewById(R.id.id);
convertView.setTag(holder);
} else {
holder = (AccountHolder) convertView.getTag();
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click", "index = " + position);
}
});
holder.txtName.setText(data.get(position).getName());
holder.txtId.setText(data.get(position).getId());
convertView.setBackgroundResource(R.drawable.list_selector);
ImageButton img = (ImageButton) convertView.findViewById(R.id.check);
img.setTag(position);
return convertView;
}
static class AccountHolder {
TextView txtName;
TextView txtId;
}
}
Problem :
When i click on an Item of the listFragment,
public void onListItemClick(ListView l, View v, int position, long id) {
mCurrentSelectedItemIndex = position;
Log.i("click", "here";
showRecipeDetails();
}
is not called but the listener on an item defined in AccountListAdapter works
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click", "index = " + position);
}
});
Why is onListitemClick never called ?
Another question : is it a proper way to consume a web service in another thread in the onActivityCreated function of my ListFragment (in order to populate the list) ?
Thx in advance
EDIT = For the moment i made "showRecipeDetails" static and call it in the listener in my custom ArrayAdapter.
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RecipeList.showRecipeDetails(position);
}}
I'm not satisfied with my solution, i'm interessed to any other solution
OnItemClickListeners must first be associated with the ListView you want to record clicks for. In your onActivityCreated(..) method, place getListView().setOnItemClickListener(this) somewhere and put implements OnItemClickListener after public static class RecipeList extends ListFragment.
Related
Problem - I have list of in app purchases loaded from app store in a Listview.
When user purchases (taps on a button in listview) the item is purchased and the button should be now hidden and the list item purchased should show an image of tick.
What I have tried -
Refresh the listview after item is purchased by calling notifyDataSetChanged
Set the visibility of the button and image using View.GONE and View.VISIBLE
None of the above seems to work.
I am using this in app billing library
public class ListViewAdapter extends ArrayAdapter<Product> {
private ArrayList<Product> iapProducts= new ArrayList<>();
private final LayoutInflater inflater;
private final Activity activity;
public ArrayList<Product> getIapProducts() {
return iapProducts;
}
public void setIapProducts(ArrayList<Product> iapProducts) {
this.iapProducts = iapProducts;
}
public ListViewAdapter(final Activity context) {
super(context, 0);
inflater = LayoutInflater.from(context);
this.activity = context;
}
#Override
public int getCount() {
return this.iapProducts.size();
}
public String getItem(String position) {
return position;
}
#Override
public boolean hasStableIds(){
return true;
}
public void addAll(ArrayList<Product> iapProducts){
this.iapProducts.addAll(iapProducts);
notifyDataSetChanged();
}
public static class ViewHolder {
public TextView name;
public ImageView imageView;
public Button purchaseButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.names_filter_row, null);
holder = new ViewHolder();
holder.name = (TextView) vi.findViewById(R.id.languageName);
holder.imageView = (ImageView) vi.findViewById(R.id.imgTick);
holder.purchaseButton = (Button) vi.findViewById(R.id.iapProductPurchaseBtn);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
final Product product = iapProducts.get(position);
holder.name.setText(product.getTitle());
holder.purchaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemPurchased(v);
}
});
holder.iapProductId.setText(product.getProductId());
holder.purchaseButton.setText(product.getPriceText());
holder.imageView.setVisibility(View.GONE);
if(product.isPurchased()){
holder.purchaseButton.setVisibility(View.GONE);
holder.imageView.setVisibility(View.VISIBLE);
}else{
holder.purchaseButton.setVisibility(View.VISIBLE);
holder.imageView.setVisibility(View.GONE);
}
return vi;
}
private void onItemPurchased(View v){
final RelativeLayout parentLayout = (RelativeLayout)v.getParent();
final TextView productId = (TextView)parentLayout.findViewById(R.id.iapProductId);
final ImageView languageCheck = (ImageView)parentLayout.findViewById(R.id.imgTick);
PurchaseActivity purchaseActivity = (PurchaseActivity) this.activity;
purchaseActivity.purchaseItem(productId.getText().toString(), v);
}
}
public class PurchaseActivity extends AppCompatActivity implements BillingProcessor.IBillingHandler {
private BillingProcessor bp;
boolean isOneTimePurchaseSupported;
private ArrayList<Product> productsToPurchase = new ArrayList<>();
private final static String TAG = PurchaseActivity.class.getName();
private ListViewAdapter adapter;
private ImageView imageTick;
private Button buttonPurchase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
bp = BillingProcessor.newBillingProcessor(this, "billingKey", this); // doesn't bind
bp.initialize(); // binds
adapter = new ListViewAdapter(this);
nameFilterListView.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onBillingInitialized() {
isOneTimePurchaseSupported = bp.isOneTimePurchaseSupported();
if(isOneTimePurchaseSupported){
loadIAPData(false);
}else{
Toast.makeText(this,"Billing not supported",Toast.LENGTH_LONG).show();
}
}
private void loadIAPData(boolean showProgressDialog){
bp.loadOwnedPurchasesFromGoogle();
final List<SkuDetails> productDetails = bp.getPurchaseListingDetails(productList);
if(productDetails!= null && !productDetails.isEmpty()){
//fetch products and add to the list
productsToPurchase.add(product);
}
//add all the products to adapter
adapter.addAll(productsToPurchase);
}
}
public void purchaseItem(#NonNull final String productId, final View imageTick, final View button){
this.imageTick = (ImageView) imageTick;
this.buttonPurchase = (Button) button;
bp.purchase(this,productId);
}
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
//hide button show image
this.imageTick.setVisibility(View.VISIBLE);
this.buttonPurchase.setVisibility(View.GONE);
adapter.setIapProducts(new ArrayList<>(productsToPurchase));
adapter.notifyDataSetChanged();
}
}
(Moved comment into a post)
After a user purchases something, is that Product within productsToPurchase updated? The adapter looks okie so maybe the list you're using isn't being updated after a purchase.
I'm assuming you need to flip the isPurchased flag of the Product in onProductPurchased() using the provided productId.
I have created a class PickedDropsAdapter that extends ArrayAdapter for a listView that lists Objects from a List
Adding and removing basically works fine except that position in getView is always 0 and I just can't figure out, why.
I found a few similar question but none of the answers was really helping
Maybe important to mention is that listView is in a Fragment which again is in a ViewPager with two pages.
PickedDropsAdapter.java
public class PickedDropsAdapter extends ArrayAdapter {
private LayoutInflater myInflater;
private List<PickedDrop> pickedList;
public PickedDropsAdapter(Context context, int resource, List objects){
super(context, resource, objects);
myInflater = LayoutInflater.from(context);
setData(objects);
}
public void setData(List list){
this.pickedList = list;
}
#Override
public int getPosition(Object item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView profileName;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.picked_drop, null);
profileName = (TextView)convertView.findViewById(R.id.profileName);
Log.i("TAG", "Name in adapter: " + pickedList.get(position).name);
Log.i("TAG", "Postion in adapter: " + position);
profileName.setText(pickedList.get(position).name);
pickedList.get(position).makeActive(convertView);
}
return convertView;
}
}
PickedDrop
public class PickedDrop extends Fragment {
int id, listLoc;
String name;
RelativeLayout pickedLayout;
PickedDropsFrag parentFrag = null;
public static PickedDrop newInstance(String nameParam, int idParam) {
final PickedDrop fragment = new PickedDrop();
fragment.name = nameParam;
Log.i("TAG", "Drop name: " + fragment.name);
fragment.id = idParam;
return fragment;
}
public PickedDrop() {
// Required empty public constructor
}
public void openDrop(){
MainActivity mainActivity = (MainActivity)parentFrag.getActivity();
mainActivity.openDrop(this);
}
public void openDrop(int i){
listLoc = i;
MainActivity mainActivity = (MainActivity)parentFrag.getActivity();
mainActivity.openDrop(this);
}
public void makeActive(View convertView){
pickedLayout = (RelativeLayout)convertView.findViewById(R.id.pickedLayout);
}
}
Part of PickedDropsFrag (The fragment that contains the listView)
public class PickedDropsFrag extends Fragment {
private OnFragmentInteractionListener mListener;
PickedDropsAdapter pickedAdapter;
ListView pickedListView;
List<PickedDrop> pickedList;
public PickedDropsFrag() {
// Required empty public constructor
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pickedListView = (ListView)getView().findViewById(R.id.pickedListView);
pickedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
PickedDrop drop = (PickedDrop) adapterView.getItemAtPosition(i);
drop.openDrop(i);
}
});
pickedList = new ArrayList<>();
pickedAdapter = new PickedDropsAdapter(
getActivity(),
R.layout.picked_drop,
pickedList
);
pickedListView.setAdapter(pickedAdapter);
}
public void addToPicked(PickedDrop drop){
drop.parentFrag = this;
//pickedList.add(drop);
pickedAdapter.add(drop);
drop.listLoc = pickedList.size() - 1;
//pickedAdapter.notifyDataSetChanged();
drop.openDrop();
}
That should be everything important, I hope I didn't forget anything.
Update following methods in your Adapter:
public class PickedDropsAdapter extends ArrayAdapter {
#Override
public int getCount() {
return pickedList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView profileName;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.picked_drop, null);
}
profileName = (TextView)convertView.findViewById(R.id.profileName);
Log.i("TAG", "Name in adapter: " + pickedList.get(position).name);
Log.i("TAG", "Postion in adapter: " + position);
profileName.setText(pickedList.get(position).name);
pickedList.get(position).makeActive(convertView);
return convertView;
}
}
I have three fragments, the second and the third one, have a listView in their respective layout.
initially, the listView of both "second and third Frament", is populated with the same items. i other words, initially the the listView of
the second fragment and the third one, contain the following where CB: is checkBox and IV: is ImageView and t is: textview, and SaveButton is a buton
t1........CB.......IV
t2........CB.......IV
t3........CB.......IV
t4........CB.......IV
t5........CB.......IV
t6........CB.......IV
SaveButton
what i am trying to do is, while i am in the second fragment and selected an item(s) from the listView "using the checkbox" and clicked "Save" button, then, that item i selected, should be deleted from the listView in the third Fragment.
to achieve this,in getview(), i checked if the the checkBox is checked from the the listView of the second fragment, and if it is checked, i add the checked items
to a list. as shown in getView():
Second Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, ECO_FRAG_ID);
this.listView.setAdapter(adapter);
}
Third Fragment:
private void setUpListView() {
// TODO Auto-generated method stub
this.topicsList = new ArrayList<String>();
for (int i = 0; i < this.topics.length; i++) {
this.topicsList.add(topics[i]);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
BaseAdapter:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater layoutinflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutinflater.inflate(R.layout.list_items_layout, null);
}
if (this.checkedItemsList1 == null) {
this.checkedItemsList1 = new ArrayList<String>();
}
if (this.checkedItemsList2 == null) {
this.checkedItemsList2 = new ArrayList<String>();
}
final TextView tv = (TextView) convertView.findViewById(R.id.tvlist_topic);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cbList_hook);
final ImageView iv = (ImageView) convertView.findViewById(R.id.ivList_delete);
tv.setText(this.topicsList.get(position));
if (cb.isChecked() && (this.id == 1) ) {
this.checkedItemsList1.add(this.topicsList.get(position));
this.setCheckedItemsList1(this.checkedItemsList1);
}
if (cb.isChecked() && (this.id == 2) ) {
this.checkedItemsList2.add(this.topicsList.get(position));
this.setCheckedItemsList2(this.checkedItemsList2);
}
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (cb.isChecked())
cb.setChecked(false);
topicsList.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
And i created an interface, which is initialised in onAttach() and called when i click the savebuton in the secondFragment as folows:
private OnClickListener btnSaveListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Save to SQLite", Toast.LENGTH_SHORT).show();
Log.d(TAG, "size: " + adapter.getCheckedItemsList1().size());
iCSC.onCheckedStateChanged(adapter.checkedItemsList1, ECO_FRAG_ID);
}
};
this inerface, the mainActivity implements it, and in the implemntation of the interface, i pass the list f the checked items from the second Fragment to the third
Fragment through a public method in the third fragmet that updates the list and then assign the list to the adapter, as follows:
#Override
public void onCheckedStateChanged(ArrayList<String> list, int id) {
// TODO Auto-generated method stub
switch (id) {
case 1:
((Logger_Settings_Frag) this.fragList.get(2)).updateTopicList(list);
break;
case 2:
break;
}
}
**updateTopicList in the third fragment**
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
updateTopicList in the third fragment
public void updateTopicList(ArrayList<String> list) {
for (String str : list) {
this.topicsList.remove(str);
}
this.adapter = new ListViewAdapter(getActivity(), this.topicsList, LOGGER_FRAG_ID);
this.listView.setAdapter(adapter);
}
when i run that code, in the saveButton listener of the second fragment, the log.d message displays that the size of the list that should contain the items that was checked, is zero size?!
please have a look at the code and let me know what i am missing?
try this: Its a sample Project OneActivity with two Fragments:
public ArrayList myBeansList_frgnt1;
public ArrayList myBeansList_frgnt2;
by clicking the save button iterate the myBeansList_frgnt1 and checking the condition that any item is selected or not. if item is selected i am adding that item to myBeansList_frgnt2 .showing in fragment2.
MainActivity:
public class MainActivity extends FragmentActivity {
private FragmentManager mFragmentManager;
private MyFragment1 myFragment1;
public ArrayList<MyBean> myBeansList_frgnt1;
public ArrayList<MyBean> myBeansList_frgnt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
myBeansList_frgnt1 = new ArrayList<MyBean>();
myBeansList_frgnt2 = new ArrayList<MyBean>();
}
#Override
protected void onResume() {
super.onResume();
myFragment1 = new MyFragment1();
FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
mTransaction.replace(R.id.framid, myFragment1, "applock").commit();
}
}
MyBaseAdpter: maintaining the states in the MyBean object
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
holder.mTextView = (TextView) view.findViewById(R.id.textView1);
holder.mBox = (CheckBox) view.findViewById(R.id.checkBox1);
holder.mImageView = (ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final MyBean mBean = mBeansList.get(position);
holder.mBox.setOnCheckedChangeListener(null);
holder.mBox.setChecked(mBean.isChecked());
holder.mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mBean.setChecked(true);
} else {
mBean.setChecked(false);
}
}
});
// setting text and image
holder.mTextView.setText(mBean.getmName());
holder.mImageView.setImageResource(mBean.getmImgId());
return view;
}
private class ViewHolder {
TextView mTextView;
CheckBox mBox;
ImageView mImageView;
}
Fragment1:
public class MyFragment1 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
private Button mButton;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
mButton = (Button) view.findViewById(R.id.bttnid);
return view;
}
#Override
public void onResume() {
super.onResume();
final MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt1, getActivity());
mListView.setAdapter(myBaseAdpter);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int size = mActivity.myBeansList_frgnt1.size();
for (int i = 0; i < size; i++) {
MyBean mMyBean = mActivity.myBeansList_frgnt1.get(i);
if (mMyBean.isChecked()) {
mActivity.myBeansList_frgnt2.add(mMyBean);
}
}
}
});
}
}
Fragment2:
public class MyFragment2 extends Fragment {
private ListView mListView;
private MyBaseAdpter myBaseAdpter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null);
mListView = (ListView) view.findViewById(R.id.listviewid);
return view;
}
#Override
public void onResume() {
super.onResume();
MainActivity mActivity = (MainActivity) getActivity();
myBaseAdpter = new MyBaseAdpter(mActivity.myBeansList_frgnt2, getActivity());
mListView.setAdapter(myBaseAdpter);
}
}
MyBean:
public class MyBean {
private String mName;
private int mImgId;
private boolean isChecked;
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public int getmImgId() {
return mImgId;
}
public void setmImgId(int mImgId) {
this.mImgId = mImgId;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public MyBean() {
super();
// TODO Auto-generated constructor stub
}
}
every one! I am a new bie in android...In my app after clicking the button on fragment I switch to new Activity which shows the list then I filtered the list and now I want to get details of selected filtered list item back to calling fragment...I tried for onClick Listener in the getView method of adapter class which extends base adapter but it not switch to calling fragment..it remains there only
My Adapter classs
public class user_list_Adapter extends BaseAdapter {
private Context context;
public static ArrayList<user_list_item> user_arraylist;
private ArrayList<user_list_item> arraylist;
public static String selected_code;
public user_list_Adapter(Context context, ArrayList<user_list_item> user_array) {
this.context = context;
this.user_arraylist = user_array;
this.arraylist = new ArrayList<user_list_item>();
this.arraylist.addAll(user_array);
}
#Override
public int getCount() {
return user_arraylist.size();
}
#Override
public Object getItem(int position) {
return user_arraylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.user_row, null);
}
TextView txtname = (TextView) convertView.findViewById(R.id.dname);
TextView txtcode = (TextView) convertView.findViewById(R.id.dcode);
txtname.setText(user_arraylist.get(position).getCust_name());
txtcode.setText(user_arraylist.get(position).getCode());
// Listen for ListView Item Click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Deposite df = new Deposite();
MainActivity activity = (MainActivity) context; //this line gives class cast exception
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
Bundle b = new Bundle();
b.putString("search_name ", search_name);
b.putString("search_code ", search_code);
df.setArguments(b);
transaction.replace(R.id.content_frame, df);
transaction.addToBackStack(null);
transaction.commit();
}
});
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
user_arraylist.clear();
if (charText.length() == 0) {
user_arraylist.addAll(arraylist);
}
else
{
for (user_list_item item : arraylist)
{
if (item.getCust_name().toLowerCase(Locale.getDefault()).contains(charText))
{
user_arraylist.add(item);
}
if (item.getCode().toLowerCase(Locale.getDefault()).contains(charText))
{
user_arraylist.add(item);
}
}
}
notifyDataSetChanged();
}
}
My Adpater class with inner class filter
public class user_list_Adapter extends ArrayAdapter<user_list_item> implements Filterable
{
private Filter mfilter;
private Context context;
private ArrayList<user_list_item> filter_user_list;
private ArrayList<user_list_item> alluserlist;
//public static String selected_code;
public user_list_Adapter(Context context, ArrayList<user_list_item> user_array) {
super(context,R.layout.user_row,user_array);
this.context = context;
this.filter_user_list = user_array;
this.alluserlist = new ArrayList<user_list_item>();
this.alluserlist.addAll(user_array);
}
#Override
public int getCount() {
return filter_user_list.size();
}
#Override
public user_list_item getItem(int position) {
return filter_user_list.get(position);
}
#Override
public long getItemId(int position) {
return filter_user_list.get(position).hashCode();
}
public void resetData() {
filter_user_list = alluserlist;
}
/* *********************************
* We use the holder pattern
* It makes the view faster and avoid finding the component
* **********************************/
private static class UserHolder {
public TextView txtname;
public TextView txtcode;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
UserHolder uholder=new UserHolder();
// First let's verify the convertView is not null
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.user_row, null);
// Now we can fill the layout with the right values
TextView tvname = (TextView) convertView.findViewById(R.id.dname);
TextView tvcode = (TextView) convertView.findViewById(R.id.dcode);
uholder.txtname = tvname;
uholder.txtcode = tvcode;
convertView.setTag(uholder);
}
else
uholder = (UserHolder) convertView.getTag();
user_list_item p = filter_user_list.get(position);
uholder.txtname.setText(p.getCust_name());
uholder.txtcode.setText(p.getCode());
return convertView;
}
/*
* We create our filter
*/
#Override
public Filter getFilter() {
if (mfilter == null)
mfilter = new userFilter();
return mfilter;
}
private class userFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence charText) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (charText == null || charText.length() == 0) {
// No filter implemented we return all the list
results.values = alluserlist;
results.count = alluserlist.size();
}
else {
// We perform filtering operation
List<user_list_item> uList = new ArrayList<user_list_item>();
for (user_list_item p : filter_user_list) {
if (p.getCust_name().toLowerCase(Locale.getDefault()).contains(charText)) {
uList.add(p);
}
if (p.getCode().toLowerCase(Locale.getDefault()).contains(charText)) {
uList.add(p);
}
}
results.values = uList;
results.count = uList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
filter_user_list = (ArrayList<user_list_item>) results.values;
notifyDataSetChanged();
}
}
}
}
In My search_window Activity class ie.List class which calls adapter class
set onItemclick listener as
// Binds the Adapter to the ListView
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
// We know that each row in the adapter is a Map
user_list_item row = adapter.getItem(position);
//Toast.makeText(getApplicationContext(),"You Clicked On.."+row.getCust_name(),Toast.LENGTH_LONG).show();
MainActivity.deposite_search_flag = true; //global static variable
MainActivity.search_name = row.getCust_name(); //global
MainActivity.search_code =row.getCode(); //global
for (int i=0;i<RecordList.size();i++){ //user_list_item only contains name n code
if (row.getCode()==Code_Array[i]){
MainActivity.search_available = avail_bal_Array[i];
}
}
finish(); //switch to caller fragment and executes OnResume method of fragment
}
});
by setting global variables on MainActivity class I switched to caller fragment by directly finishing this activity(finish();)
//In caller fragment class
#Override
public void onResume() {
super.onResume();
if (MainActivity.deposite_search_flag){
txtname.setText(MainActivity.search_name);
txtcode.setText(MainActivity.search_code);
txt_available_bal.setText(MainActivity.search_available);
}
}
i created custom listview with text and two buttons, i set up arraylist and adapter but my listview is showing every element as last, for ex. if i add 3 elements: "text1","text2","text3" my listview shows "text3", "text3" "text3" and i dont have any idea why.
private ListView lista;
private List<Piosenka> listaPiosenek;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
lista = (ListView) findViewById(R.id.listView1);
lista.setClickable(true);
}
public void update_listy() throws MalformedURLException, IOException
{
final List<Piosenka> listaPiosenek = new ArrayList<Piosenka>();
listaPiosenek.add(new Piosenka("text1"));
listaPiosenek.add(new Piosenka("text2"));
listaPiosenek.add(new Piosenka("text3"));
PiosenkaAdapter adapter = new PiosenkaAdapter(this, listaPiosenek);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long index)
{
System.out.println("sadsfsf");
}
});
lista.setAdapter(adapter);
}
Edit: PiosenkaAdapter code
public class PiosenkaAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Piosenka> listapiosenek;
public PiosenkaAdapter(Context context, List<Piosenka> listapiosenek) {
this.context = context;
this.listapiosenek = listapiosenek;
}
public int getCount() {
return listapiosenek.size();
}
public Object getItem(int position) {
return listapiosenek.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Piosenka element = listapiosenek.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_element, null);
}
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Button btnPobierz = (Button) convertView.findViewById(R.id.btnPobierz);
btnPobierz.setFocusableInTouchMode(false);
btnPobierz.setFocusable(false);
btnPobierz.setTag(element);
Button btnPlay = (Button) convertView.findViewById(R.id.btnPlay);
btnPlay.setFocusableInTouchMode(false);
btnPlay.setFocusable(false);
btnPlay.setOnClickListener(this);
btnPlay.setTag(element);
// btnRemove.setId(position);
return convertView;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPobierz:
Piosenka entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
case R.id.btnPlay:
entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
}
}
}
Try this...
lista.setAdapter(adapter);
adapter.notifyDataSetChanged();
Can you paste you PiosenkaAdapter's code?
I don't know your language, but the Piosenka variable is fetched correctly in getView()
Piosenka element = listapiosenek.get(position);
But this looks strange to me
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Piosenka.getTytul() looks to me as a static method call, where you should do a regular method call to element.getTytul() instead.