i have a listview for showing products (product Name, product Price and product Description).
I want to show the product description in a webview because i use html code (images,tables,video etc).
Everything is ok on the products list except the product description on the WebView.
When i scroll the listview on the products that they are not visible, the product Description(WebView) is completely wrong, actually it shows descriptions from previous products.
The problem it is inside the GetView function, and although i use a viewHolder class , it still the problem remailns. Below i show the code snippet of the Getview and the viewholder class :
/////THE VIEWHOLDER CLASS THAT HOLDS THE UI COMPONENTS//////////////////
private class ViewHolder {
TextView prName;
WebView prDescription;
TextView product_descr2;//for test, this shows always the correct pr. descr.
TextView prfprice;
ImageView prImage;
ProgressBar prProgressBar;
int ProdPosition;
}
//////THE GETVIEW() FUNCTION , WHERE I LOAD EACH PRODUCT VALUES///////
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
View view = convertView;
final ProductsData info = getItem(position);
if (view == null) {
// Product row
view = mInflater.inflate(R.layout.productslistitem_layout, null);
viewHolder = new ViewHolder();
assert view != null;
viewHolder.prName = (TextView) view.findViewById(R.id.product_name);
viewHolder.prDescription = (WebView) view.findViewById(R.id.webView1);
viewHolder.product_descr2 = (TextView)view.findViewById(R.id.product_descr2);
viewHolder.prDescription.setFocusable(false);
//final price
viewHolder.prfprice = (TextView) view.findViewById(R.id.product_fprice);
viewHolder.prImage = (ImageView) view.findViewById(R.id.product_image);
viewHolder.prProgressBar = (ProgressBar)view.findViewById(R.id.pbProduct);
view.setTag(viewHolder);
}else
viewHolder = (ViewHolder) view.getTag();
MainActivity.imageLoaderProducts.displayImage(info.getPrUrl(), viewHolder.prImage, options, new SimpleImageLoadingListener(){
#Override
public void onLoadingStarted(String imageUri, View view) {
viewHolder.prProgressBar.setProgress(0);
viewHolder.prProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
viewHolder.prProgressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
viewHolder.prProgressBar.setVisibility(View.GONE);
viewHolder.prName.setText(info.getPrName()); //PRODUCT NAME
viewHolder.product_descr2.setText(info.getPrDescr()));//PRODUCT DESCR, CORRECT VALUES
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
viewHolder.prDescription.setWebViewClient(new WebViewClient());
viewHolder.prDescription.getSettings().setJavaScriptEnabled(true);
//ENCODING UTF-8
viewHolder.prDescription.getSettings().setDefaultTextEncodingName("utf-8");
viewHolder.prDescription.loadData(header +"<div style='background-color:#fff'>"+ info.getPrDescr()+"</div>", "text/html; charset=utf-8", null);//WBVIEW SHOW WRONG PR.DESCR.
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current,int total) {
viewHolder.prProgressBar.setProgress(Math.round(100.0f * current / total));
}
}
);
return view;
}
The product_descr2(TextView) shows the correct product description but the prDescription(WebView) shows the correct description only for the first product of the list. Is it a bug of WebView component or am i doing something wrong?
If anyone knows any solution please give a hand.
/*******************************/
I noticed that if i add convertview = null; into the getView, it loads the correct values into the WebViews but it is too slow.
i show the code of the products file. I use the universal image loader for lazy loading of the product images.
/******************PRODUCTS FILE************************************************************/
import java.util.ArrayList;
public class FragmentProducts extends Fragment implements
OnItemClickListener {
private ArrayList<ProductsData> productsList;
private ArrayList<ProductBitmapData> ProductBitmapList;
private LayoutInflater mInflater;
private ProductsListAdapter pAdapter;
private GridView lvProducts;
private ImageButton btnRefreshProducts;
private String VarTitle;//vartitle for the cart
private String VarId;//varId for the cart
private float VarPrice;//varPrice for the cart
//NEW for universal image loader
private DisplayImageOptions options;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
//change fonts
TextView tvProductsHeader = (TextView)getActivity().findViewById(R.id.tvProductsHeader);
Utils.TypeFace(tvProductsHeader, getActivity().getAssets());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mInflater = getActivity().getLayoutInflater();
pAdapter = new ProductsListAdapter(getActivity(), productsList);
lvProducts.setAdapter(pAdapter);
}
public static final FragmentProducts newInstance(
ArrayList<ProductsData> productsList,
ArrayList<ProductBitmapData> ProductBitmapList) {
FragmentProducts fr = new FragmentProducts();
Bundle args = new Bundle();
args.putSerializable("products", productsList);
args.putSerializable("bitmaps", ProductBitmapList);
fr.setArguments(args);
return fr;
}
public static final FragmentProducts newInstance(
ArrayList<ProductsData> productsList) {
//OLD FragmentProductsList fr = new FragmentProductsList();
FragmentProducts fr = new FragmentProducts();
Bundle args = new Bundle();
args.putSerializable("products", productsList);
fr.setArguments(args);
return fr;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.productsList = (ArrayList<ProductsData>) (getArguments() != null ? getArguments()
.getSerializable("products") : null);
this.ProductBitmapList = (ArrayList<ProductBitmapData>) (getArguments() != null ? getArguments()
.getSerializable("bitmaps") : null);
//display options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.productslist_layout, container,
false);
lvProducts = (GridView) view.findViewById(R.id.glist);
lvProducts.setOnItemClickListener(this);
btnRefreshProducts = (ImageButton) view
.findViewById(R.id.btnRefreshProducts);
btnRefreshProducts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pAdapter = new ProductsListAdapter(getActivity(), productsList);
lvProducts.setAdapter(pAdapter);
}
});
return view;
}
// CUSTOM ARRAY ADAPTER FOR THE LIST of CATEGORY ITEMS
public class ProductsListAdapter extends ArrayAdapter<ProductsData> {
public ProductsListAdapter(Context context, ArrayList<ProductsData> data) {
super(context, 0, data);
}
private class ViewHolder {
TextView prName;
WebView prDescription;
TextView prfprice;
ImageView prImage;
ProgressBar prProgressBar;
Spinner PrVariants1;
Spinner PrVariants2;
int ProdPosition;
//adapters
ArrayAdapter<String> var1Adapter;
ArrayAdapter<String> var2Adapter;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public ProductsData getItem(int position) {
return super.getItem(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
/*Clear convert view , and the WEBVIEW(DESCRIPTION) WORKS FINE! **/
/*BUT IT IS TOO SLOW BECAUSE, IT LOADS FROM THE START EACH TIME*/
convertView = null;
/*************************/
View view = convertView;
final ProductsData info = getItem(position);
if (view == null) {
// Product row
view = mInflater.inflate(R.layout.productslistitem_layout, null);
viewHolder = new ViewHolder();
assert view != null;
viewHolder.prName = (TextView) view.findViewById(R.id.product_name);
viewHolder.prDescription = (WebView) view.findViewById(R.id.webView1);
viewHolder.prDescription.setFocusable(false);
//starting price
/*viewHolder.prsprice = (TextView) view.findViewById(R.id.product_sprice);*/
//final price
viewHolder.prfprice = (TextView) view.findViewById(R.id.product_fprice);
viewHolder.prImage = (ImageView) view.findViewById(R.id.product_image);
viewHolder.prProgressBar = (ProgressBar)view.findViewById(R.id.pbProduct);
viewHolder.PrVariants1 = (Spinner) view.findViewById(R.id.spOptions1);
viewHolder.PrVariants1.setFocusable(false);
viewHolder.PrVariants2 = (Spinner) view.findViewById(R.id.spOptions2);
viewHolder.PrVariants2.setFocusable(false);
view.setTag(viewHolder);
}else
viewHolder = (ViewHolder) view.getTag();
MainActivity.imageLoaderProducts.displayImage(info.getPrUrl(), viewHolder.prImage, options, new SimpleImageLoadingListener(){
#Override
public void onLoadingStarted(String imageUri, View view) {
viewHolder.prProgressBar.setProgress(0);
viewHolder.prProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
viewHolder.prProgressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
viewHolder.prProgressBar.setVisibility(View.GONE);
viewHolder.prName.setText(info.getPrName());
//SHOW WEBVIEW PRODUCT VALUE
String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
viewHolder.prDescription.setWebViewClient(new WebViewClient());
viewHolder.prDescription.getSettings().setJavaScriptEnabled(true);
//ENCODING UTF-8
viewHolder.prDescription.getSettings().setDefaultTextEncodingName("utf-8");
/**HERE IS THE PROBLEM ,I LOAD THE info.PrComments(product description)*/
viewHolder.prDescription.loadData(header +"<div style='background-color:#fff'>"+ info.getPrComments()+"</div>", "text/html; charset=utf-8", null);
/****************AND IF I SCROLL THE WEBVIEW VALUES ARE CONFUSED ***********/
/********START FILL VARIANTS 1 & 2***********/
viewHolder.var1Adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item);
viewHolder.var2Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item);
//product id
int tempPrid = info.getPrID();
//new variants1
//LOAD variant1
for(int i = 0; i < info.getVariantsItems().size(); i ++){
viewHolder.var1Adapter.add(info.getVariantsItems().get(i).getVarOptions1());
}
//IF VARIANT2 IS NULL, View.GONE
if(info.getVariantsItems2().get(0).getVarOptions2() != null){
for(int i = 0; i < info.getVariantsItems2().size(); i ++){
viewHolder.var2Adapter.add(info.getVariantsItems2().get(i).getVarOptions2());
}
viewHolder.var2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.PrVariants2.setAdapter(viewHolder.var2Adapter);
}//end if
else{
viewHolder.PrVariants2.setVisibility(View.GONE);
}//end else variant2
viewHolder.var1Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.PrVariants1.setAdapter(viewHolder.var1Adapter);
//add eventListener on variants1 listbox
viewHolder.PrVariants1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View arg1, int pos, long arg3) {
//GET VALUES FROM spinner1
String tempOption1 = parent.getItemAtPosition(pos).toString();
//initialize
String tempOption2=null;
//CHECK IF SPINNER2 IS VISIBLE(IF IT IS VISIBLE ,IT HAS VALUE)
if (viewHolder.PrVariants2.getVisibility() != View.GONE){
if (viewHolder.PrVariants2.getSelectedItem() != null){
tempOption2 = viewHolder.PrVariants2.getSelectedItem().toString();
}
}
if (tempOption2 !=null)
{
VarTitle = tempOption1 + "/" + tempOption2;
}else
VarTitle = tempOption1;
ArrayList<String> res = MainApplication.dbHelper.checkVariation(VarTitle, Integer.toString(info.getPrID()));
//IF VARIATION DOES NOT EXIST , price field = N/A
if (res.isEmpty())
viewHolder.prfprice.setText("N/A");
else{
viewHolder.prfprice.setText(res.get(1) + "€");
VarId = res.get(0);//get the variantId for the cart
VarPrice = Float.valueOf(res.get(1));//get the variant price for the cart
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
//add event listener on variants2 listbox
viewHolder.PrVariants2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View arg1, int pos, long arg3) {
//initialize
String tempOption2 = null;
if(parent.getItemAtPosition(pos) != null){
tempOption2 = parent.getItemAtPosition(pos).toString();
}
//GET SPINNER1 VALUE
String tempOption1 = viewHolder.PrVariants1.getSelectedItem().toString();
if(tempOption2 != null)
{
VarTitle = tempOption1 + "/" + tempOption2;
}else
VarTitle = tempOption1;
ArrayList<String> res = MainApplication.dbHelper.checkVariation(VarTitle, Integer.toString(info.getPrID()));
///IF VARIATION DOES NOT EXIST , price field = N/A
if (res.isEmpty())
viewHolder.prfprice.setText("N/A");
else{
viewHolder.prfprice.setText(res.get(1) + "€");
VarId = res.get(0);//get the variantId for the cart
VarPrice = Float.valueOf(res.get(1));//get the variant price for the cart
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
/********END FILL VARIANTS 1 & 2*************/
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current,
int total) {
viewHolder.prProgressBar.setProgress(Math.round(100.0f * current / total));
}
}
);
return view;
}
}
Don't use ViewHolder! => http://blog.xebia.com/2013/07/22/viewholder-considered-harmful/
try this:
...without if(convert == null){ ....
just inflate convertView
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = Inflater.inflate(R.layout.productslistitem_layout, null);
...
...
Related
I am watching the monitor on Android and I notice that the memory keeps increasing when you scroll down and up.
I am using an Adaper. It's supposed to reuse the views, but it seems that it doesn't work.
As you can see in the images below the memory starts at 9.94 MB and I could increase it at 25.82 MB just by scrolling down and up.
You can see the code that I use.
public class ListMainFragment
extends Fragment
implements LoaderManager.LoaderCallbacks<List<Earthquake>> {
public ListMainFragment() {
// Required empty public constructor
}
ListView listView;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewRoot = inflater.inflate(R.layout.fragment_mainlist, container, false);
final ArrayList<Earthquake> earthquake =
(ArrayList<Earthquake>) new EarthquakeController(new EarthquakesJson()).getListOfEarthquakes();
listView = (ListView)viewRoot.findViewById(R.id.list_view);
EarthquakeAdapter noteAdapter = new EarthquakeAdapter(getActivity(), earthquake);
listView.setAdapter(noteAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//final String mensaje = notas.get(position).getMag();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(earthquake.get(0).getMapURL()));
Log.w("ListView", "Se despliega la siguente URL " + earthquake.get(0).getMapURL());
startActivity(intent);
}
});
return viewRoot;
}
}
The Adapter:
public class EarthquakeAdapter extends ArrayAdapter <Earthquake> {
public EarthquakeAdapter(Context context, ArrayList<Earthquake> notas) {
super(context, 0, notas);
}
private static final String LOCATION_SEPARATOR = " of";
View view;
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
*/
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);
Log.w("AppList", "converView es null");
}
Earthquake note = getItem(position);
Date dateObject = new Date(note.getTimeInMilliseconds());
TextView locationOffset = (TextView)convertView.findViewById(R.id.listItem_tv_locationOffset);
TextView place = (TextView)convertView.findViewById(R.id.listItem_tv_place);
TextView date = (TextView)convertView.findViewById(R.id.lisItem_tv_date);
TextView time = (TextView)convertView.findViewById(R.id.lisItem_tv_time);
TextView mag = (TextView) convertView.findViewById(R.id.listItem_tv_mag);
GradientDrawable magnitudCicle = (GradientDrawable) mag.getBackground();
magnitudCicle.setColor(getMagnitudColor(note.getMag()));
String str_locationOffset, str_place;
if (note.getPlace().contains(LOCATION_SEPARATOR)) {
String [] locations = note.getPlace().split(LOCATION_SEPARATOR);
str_locationOffset = locations[0];
str_place = locations[1];
}
else {
str_place = note.getPlace();
str_locationOffset = getContext().getString(R.string.near_the);
}
mag.setText( new DecimalFormat("0.0").format(note.getMag()));
date.setText(formatDate(dateObject));
place.setText(str_place);
time.setText(formatTime(dateObject));
locationOffset.setText(str_locationOffset);
/* final String mensaje = title.getText().toString();
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),mensaje,Toast.LENGTH_SHORT).show();
}
});*/
return convertView;
}
}
You should use Recycler View for better performance.
From: https://developer.android.com/training/material/lists-cards.html
I'm using a view pager with a sliding panel inside, so when my panel is expanded it creates a request of users and instantiates viewholders to show them in the list view, the problem is that they get instantiated on wherever they want, how I can tell in what fragment it should be instantiated.
Here is my code:
#Override
public void onPanelAnchored(View panel) {
final View cView = panel;
EndpointInterface Service = ServiceAuthGenerator.createService(EndpointInterface.class);
currentID = sharedpreferences.getInt("CURRENTID", 0);
Call<List<Ride>> call = Service.getPassengers(currentRide);
call.enqueue(new Callback<List<Ride>>() {
#Override
public void onResponse(Response<List<Ride>> response, Retrofit retrofit) {
if (response.isSuccess() && !response.body().isEmpty()) {
dialogx.dismiss();
ArrayList<String> myUsersName = new ArrayList<>();
ArrayList<String> myUsersLastName = new ArrayList<>();
ArrayList<String> myUsersMapDirection = new ArrayList<>();
ArrayList<Integer> myUsersID = new ArrayList<>();
ArrayList<Boolean> myUsersRole = new ArrayList<>();
for (int i = 0; i < response.body().size(); i++) {
myUsersRole.add(response.body().get(i).getRole());
myUsersName.add(response.body().get(i).getUser().getFirst_name());
myUsersLastName.add(response.body().get(i).getUser().getLast_name());
myUsersMapDirection.add(getAdress(new LatLng(response.body().get(i).getOrigin_lat(), response.body().get(i).getOrigin_lng())));
myUsersID.add(response.body().get(i).getId());
currentName = myUsersName.get(i) + " " + myUsersLastName.get(i);
mMap.addMarker(new MarkerOptions().snippet(getAdress(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng()))).position(new LatLng(response.body().get(Integer.valueOf(i)).getOrigin_lat(), response.body().get(Integer.valueOf(i)).getOrigin_lng())).title(response.body().get(Integer.valueOf(i)).getUser().getFirst_name()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
ListAdapter userAdapter = new CustomAdapterRequest(MainMenu.this, myUsersName, myUsersLastName, myUsersMapDirection, myUsersID, myUsersRole, currentRide);
ListView userListView = (ListView) cView.findViewById(R.id.listViewUserRequest);
userListView.setAdapter(userAdapter);
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
}
});
}
Also, here is my adapter code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
myViewHolder holder = null;
if (row == null) {
LayoutInflater customInflater = (LayoutInflater) contexto.getSystemService(contexto.LAYOUT_INFLATER_SERVICE);
row = customInflater.inflate(R.layout.custom_row_request, parent, false);
holder = new myViewHolder(row);
row.setTag(holder);
} else {
holder = (myViewHolder) row.getTag();
}
String singleNameItem = itemName.get(position);
String singleLastNameItem = itemLastName.get(position);
String singleDir = itemDirection.get(position);
Integer singleID = itemIDs.get(position);
Boolean singleRole = itemRoles.get(position);
holder.tv_name.setText(singleNameItem + " " + singleLastNameItem);
holder.tv_Direction.setText(singleDir);
holder.im_profilepic.setImageResource(R.mipmap.profile_photo3);
return row;
}
And my holder class.
class myViewHolder {
TextView tv_name;
TextView tv_Direction;
ImageView im_profilepic;
myViewHolder(View v) {
tv_name = (TextView) v.findViewById(R.id.nameText);
tv_Direction = (TextView) v.findViewById(R.id.originText);
im_profilepic = (ImageView) v.findViewById(R.id.ivImage);
}
}
This is the Fragment class
public class fragment1 extends Fragment {
public fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (CardView) inflater.inflate(R.layout.layout1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setTextDestination(String origin, String Destination, Long Date, String estimatedTime, boolean singleRole) {
TextView tv_Destination = (TextView) getView().findViewById(R.id.TextDestination);
TextView tv_origin = (TextView) getView().findViewById(R.id.TextOrigin);
TextView tv_Date = (TextView) getView().findViewById(R.id.textDatePager);
TextView tv_EstimatedTiem = (TextView) getView().findViewById(R.id.estimatedTimeRoute);
ImageView iv_roleType = (ImageView) getView().findViewById(R.id.ImgView_roleTypeLayout1);
tv_Destination.setText(Destination);
tv_origin.setText(origin);
iv_roleType.setImageResource(singleRole ? R.mipmap.steerorange3 : R.mipmap.handorange3);
tv_EstimatedTiem.setText(estimatedTime);
java.util.Date date = new Date(Date * 1000L);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getDefault());
String formatted = format.format(date);
tv_Date.setText(formatted);
}
}
I created a list of fragment1 which is mu fragment class and added it to a list, then depending on how many items on the list I have is the number of instances I get, my set text function works correctly but I don't know how to do that with the list view!
Thanks! :D
moved the method that added the list view to the fragment that was instantiated.
is it possible to call a method in my CustomAdapter to set a checkbox Visible/Gone by clicking on an Element on my Fragments Listview? Ive got those two methods:
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
But How do I access them from my Fragment? Or do I have do chose another way?
(I want to set the checkbox visible by after "long click" on one of the ListView Elements)
Fragment:
public class ListViewFragment extends Fragment {
[...]
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
getActivity().setTitle(getString(R.string.listView));
registerForContextMenu(view);
final Context context = getContext();
mydb = new DbHelper(context);
locationpicker = (Spinner) view.findViewById(R.id.spinner_locations);
roomnr = (EditText) view.findViewById(R.id.editText_roomNr);
Drawable drawableForFabAdd = getResources().getDrawable(R.drawable.ic_add);
((MainActivity) getActivity()).fabmain.setImageDrawable(drawableForFabAdd);
((MainActivity) getActivity()).fabmain.animate().translationY(0);
((MainActivity) getActivity()).fabmain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).scanQRCode();
((MainActivity) getActivity()).loadListViewFragment();
}
});
((MainActivity) getActivity()).fabdelete.animate().translationY(0);
final String locationNamesFromTableArray = mydb.getLocationNames();
if(!locationNamesFromTableArray.isEmpty()){
String[] roomNumbersFromTableArrayFinal = locationNamesFromTableArray.split("\t");
ArrayAdapter<String> adapter_locations;
adapter_locations = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, roomNumbersFromTableArrayFinal);
locationpicker.setAdapter(adapter_locations);
setFabdeleteVisible(listViewOk);
}
locationpicker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
actualLocation = locationpicker.getSelectedItem().toString();
locationOk = true;
setFabsVisible(roomNrOk, true, listViewOk);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
roomnr.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
Pattern p = Pattern.compile("^[0-9]{3}$");
Matcher m = p.matcher(s);
roomNrOk = m.find();
setFabsVisible(roomNrOk, locationOk, listViewOk);
}
});
dataList = mydb.getElementsWithoutRoom();
if (!dataList.isEmpty()) {
final String[] dataListArray = dataList.split("\n");
Log.d("DATALIST", dataListArray[0]);
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray);
final ListView dataListListView = (ListView) view.findViewById(R.id.listView_datalist);
dataListListView.setAdapter(dataListAdapter);
dataListListView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
((MainActivity) getActivity()).fabmain.animate().translationY(300);
}
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
((MainActivity) getActivity()).fabmain.animate().translationY(0);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
listViewOk = true;
setFabsVisible(roomNrOk, locationOk, true);
setFabdeleteVisible(listViewOk);
dataListListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedFromList = (dataListListView.getItemAtPosition(position).toString());
selectedElementArray = selectedFromList.split("\t");
dataListListView.showContextMenu();
}
});
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
(CustomListAdapter).setCheckBoxSelectItemVisible();
return true;
}
});
[...]
return view;
}
public void reloadListViewFragment(){
Fragment fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment = new ListViewFragment();
ft.replace(R.id.container, fragment);
ft.commitAllowingStateLoss();
}
[...]
}
CustomAdapter:
class CustomListAdapter extends ArrayAdapter<String> {
String doubleTab = "\t\t";
CheckBox checkBoxSelectItem;
public CustomListAdapter(Context context, String[] dataListFinal) {
super(context, R.layout.list_item_datalist ,dataListFinal);
}
public String allElementsAdapter = "";
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
return customView;
}
public String getAllElements(){
return allElementsAdapter;
}
public void setCheckBoxSelectItemVisible(){
checkBoxSelectItem.setVisibility(View.VISIBLE);
return;
}
public void setCheckBoxSelectItemGone(){
checkBoxSelectItem.setVisibility(View.GONE);
return;
}
}
first change your Custom Adapter constructor with following
ArrayList<Boolean> mIsVisible;
public CustomListAdapter(Context context, String[] dataListFinal,ArrayList<Boolean> isVisible) {
super(context, R.layout.list_item_datalist ,dataListFinal);
mIsVisible = isVisible;
}
then modify getView()
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater iteminflater = LayoutInflater.from(getContext());
View customView = iteminflater.inflate(R.layout.list_item_datalist, parent, false);
ImageView image = (ImageView) customView.findViewById(R.id.list_icon_product);
TextView textViewlabel = (TextView) customView.findViewById(R.id.list_item_datalist_label_textview);
TextView textViewdetails1 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_1);
TextView textViewdetails2 = (TextView) customView.findViewById(R.id.list_item_datalist_textview_details_2);
checkBoxSelectItem = (CheckBox) customView.findViewById(R.id.checkBox_Item);
String singleListItem = getItem(position);
String[] singleListItemArray = singleListItem.split("\t");
String id = singleListItemArray[0];
String product = singleListItemArray[1];
allElementsAdapter = product + label + serial + mac + daaid + bill;
switch (product) {
case "Pc":
image.setImageResource(R.drawable.icon_pc_circle);
break;
case "Laptop":
image.setImageResource(R.drawable.icon_laptop_circle);
break;
}
String details1 = serial +doubleTab+ mac;
String details2 = daaid +doubleTab+ bill;
textViewlabel.setText(label);
textViewdetails1.setText(details1);
textViewdetails2.setText(details2);
if(mIsVisible.get(position)){
checkBoxSelectItem.setVisibility(View.VISIBLE);
}else{
checkBoxSelectItem.setVisibility(View.GONE);
}
return customView;
}
After that modify your activity CustomAdapter creation part
final ArrayList<Boolean> isVisible=new ArrayList<Boolean>();
for(int count =0 ;count<dataListArray.length; count++){
isVisible.add(false);
}
final ListAdapter dataListAdapter = new CustomListAdapter(context, dataListArray, isVisible);
And last modify listener part
dataListListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(isVisible.get(position))
isVisible.set(position,false);
else
isVisible.set(position,true);
dataListAdapter.notifyDataSetChanged();
return true;
}
});
Done...!!!!!
It works with ((BaseAdapter)dataListAdapter).notifyDataSetChanged();
I have a GridView and adapter for GridView (BasketAdapter extends BaseAdapter).
I load data in GridView from sharedpref file.
After I change data, I resave sharedpref file with data and call notifyDataSetChanged().
But notifyDataSetChanged() doesn't work unfortunately.
If I create new adapter and set it to my GridView, it works.
Can anyone help me with this issue?
Here is my code:
public class FragmentBasket extends SherlockFragment {
// my gridview
GridView gvCatalogAllStoneBasket;
// list of data from shared pref
ArrayList<CatalogItem> catalogItemBasket = new ArrayList<CatalogItem>();
ActionMode mode;
public static CatalogItem catalogItem;
// id variables for actionmode's actions
static final int ID_DELETE = 1;
static final int ID_EDIT = 2;
// shared pref id string
static String SHARED_PREFS_FILE = "basket";
// my adapter
BasketAdapter adapter = null;
public FragmentBasket() {
}
#Override
public void onStart() {
super.onStart();
// loading saved data from file
new GetCatalogAllStoneBasket().execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Receiver receiver = new Receiver();
IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.EDIT_ITEM_BASKET");
IntentFilter intentFilterDelete = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");
getActivity().registerReceiver(receiver, intentFilterAdd);
getActivity().registerReceiver(receiver, intentFilterEdit);
getActivity().registerReceiver(receiver, intentFilterDelete);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid, container, false);
gvCatalogAllStoneBasket = (GridView)view.findViewById(R.id.gvCatalogAllStoneBasket);
gvCatalogAllStoneBasket.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// start action mode and send id of clicked item
mode = getSherlockActivity().startActionMode(new ActionModeOfBasket(String.valueOf(view.getTag())));
return false;
}
});
return view;
}
private final class ActionModeOfBasket implements ActionMode.Callback
{
String itemId;
public ActionModeOfBasket(String itemId) {
// get id from clicked item
this.itemId = itemId;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(0, ID_EDIT, 0, "Edit")
.setIcon(android.R.drawable.ic_menu_edit)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
menu.add(0, ID_DELETE, 1, "Delete")
.setIcon(android.R.drawable.ic_menu_delete)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// get file
SharedPreferences sPref = getActivity().getSharedPreferences(SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
// open file for reading, writing
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
switch (item.getItemId())
{
// if clicked del button
case ID_DELETE:
// delete item
bHelper.DelItem(itemId);
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
// if clicked edit button
case ID_EDIT:
// edit item
bHelper.EditItem(itemId, getFragmentManager());
mode.finish();
catalogItemBasket = bHelper.GetAllItems();
break;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
class GetCatalogAllStoneBasket extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
SharedPreferences sPref = getActivity().getSharedPreferences(FragmentCatalogStonePosition.SHARED_PREFS_FILE, getActivity().MODE_PRIVATE);
try {
if(sPref.getString(FragmentCatalogStonePosition.TASK, null) != null)
{
BasketHelper bHelper = new BasketHelper(sPref, getActivity());
catalogItemBasket = bHelper.GetAllItems();
}
} catch (Exception e) {
Log.d(MainActivity.tag, e.getMessage() + " " + e.getCause());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(adapter);
}
}
class Receiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().toString() == "com.example.myproject.ADD_ITEM_BASKET")
{
}
else if(intent.getAction().toString() == "com.example.myproject.EDIT_ITEM_BASKET")
{
// this code doesn't work (((
adapter.notifyDataSetChanged();
// this one successfully works
BasketAdapter bAdapter = new BasketAdapter(getActivity(), catalogItemBasket);
gvCatalogAllStoneBasket.setAdapter(bAdapter);
}
else if(intent.getAction().toString() == "com.example.myproject.DELETE_ITEM_BASKET")
{
}
}
}
class BasketAdapter extends BaseAdapter
{
Context context = null;
ArrayList<CatalogItem> data = null;
public BasketAdapter(Context context, ArrayList<CatalogItem> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
public CatalogItem getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
}
return view;
}
}
}
Your convertView isn't null in case the View is recycled, so your getView() should be something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflater = getLayoutInflater(null);
view = inflater.inflate(R.layout.right_panel_fragment_catalog_grid_item, parent, false);
}
CatalogItem item = getItem(position);
((TextView)view.findViewById(R.id.tvCatalogItemBasketName)).setText(item.name + " / " + item.code);
Double gPrice = Double.valueOf(item.price) * Double.valueOf(item.count);
((TextView)view.findViewById(R.id.tvCatalogItemBasketCount)).setText(String.valueOf(item.count));
((TextView)view.findViewById(R.id.tvCatalogItemBasketGeneralPrice)).setText(String.valueOf(gPrice));
((TextView)view.findViewById(R.id.tvCatalogItemBasketDescription)).setText(item.description);
final ImageView imgView = (ImageView)view.findViewById(R.id.ivCatalogItemBasketImage);
String strURL = "http://myproject.ua/images/stock/" + item.folder + "/" + item.images + "_800x600.jpg";
ImageLoaderConfiguration config = ImageHelper.ImageConfig(getActivity().getApplicationContext());
DisplayImageOptions options = ImageHelper.ImageOptions();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
final ProgressBar pImgDialog = (ProgressBar)view.findViewById(R.id.pbImage);
imageLoader.displayImage(strURL, imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
pImgDialog.setVisibility(View.VISIBLE);
imgView.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
pImgDialog.setVisibility(View.GONE);
imgView.setVisibility(View.VISIBLE);
}
});
view.setTag(item.catalog_id);
return view;
}
and since you have your own ArrayList inside your adapter, you have to update this one as well. Just add this method to your BasketAdapter:
public void changeModelList(List<CatalogItem> models) {
this.data = models;
notifyDataSetChanged();
}
and use it instead of notifyDataSetChanged().
it's not tested, but i think this is your problem.
Hello Everyone!!
I am making a sample shopping cart in which i need to get the position of item clicked and get the image displayed on the page on selecting the image from the shopping cart..But here i am getting image of first item only no matter i have clicked another..it is always showing first image of the list...
Here is my code for ProductAdapter.java
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
}}
And Here is my shoppingcart file
public class ShoppingCartActivity extends Activity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),
true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),
ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
startActivity(productDetailsIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if (mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
double subTotal = 0;
for (Product p : mCartList) {
int quantity = ShoppingCartHelper.getProductQuantity(p);
subTotal += p.price * quantity;
}
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);
}
}
ProductActivity.java
public class CatalogActivity extends Activity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
Code for ProductDetailsActivity.java
public class ProductDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productdetails);
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
productPriceTextView.setText("$" + selectedProduct.price);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
Plz guys Any help will be highly appreciated.
Thanx in advance..
The int position in onItemClick gives the position of the clicked item in the array/list you gave to the adapter.
You can also do getItemAtPosition(); on your listview, if you don't have an easy handle on your original list.
add this code to your Project :
mProductList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
int h = parent.getPositionForView(v);
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected" + h,
Toast.LENGTH_SHORT).show();
}
});
Just geussig that you have a problematic code where you are reading the index value. Following is the sample code for writing and reading int extra:
To put int value:
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
Following code should be used to read this value in another Activity
int index = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
Hope it helps...