I have a multicolumn List view like the one shown in the image, i used custom adapters to populate this custom list.so the question is how to get data on click of submit button means when i click submit button i should get data like name, price and quantity of only checked checkbox....Thanx in advance.
In my Main xml i have a listview and in mainlist xml i have txtname, txtprice, edittext and checkbox and use efficient adapter.
i'm able to view data in list view, bt the problem is i m unable to save data on click of submit button... so plz help me out, with a sample code, bcz m new to android..
the following is my code..
public class Menu extends Activity {
ListView list;
Cursor cursorMenu;
Button btnPlaceOrder;
Button btnShowOrders;
String Descstr="";
String strtotal="";
List<String[]> lstSelectedItems = null;
DBAdapter db = new DBAdapter(this);
private String[] strName;
private String[] strPrice;
private String[] strDescription;
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
try {
return strName.length;
} catch (Exception e) {
//Toast.makeText(Menu.this, "No Data !", Toast.LENGTH_LONG).show();
return 0;
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menulist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.txtItemName);
holder.text2 = (TextView) convertView
.findViewById(R.id.txtPrice);
holder.text3 = (TextView) convertView
.findViewById(R.id.txtDescription);
holder.etext3 = (EditText) convertView
.findViewById(R.id.txtQty);
holder.chk = (CheckBox) convertView
.findViewById(R.id.chkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(strName[position]);
holder.text2.setText(strPrice[position]);
holder.text3.setText(strDescription[position]);
return convertView;
}
class ViewHolder {
TextView text;
TextView text2;
TextView text3;
EditText etext3;
CheckBox chk;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
btnPlaceOrder = (Button) findViewById(R.id.btnPlaceOrder);
btnPlaceOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*db.open();
cursorMenu = db.menu_getAllTitles();
int rowcount = cursorMenu.getCount();
System.out.println("---- +++++ " + rowcount);
System.out.println("---- column +++++ " + cursorMenu.getColumnCount());
int index = 0;
if (rowcount > 0) {
strName = new String[rowcount];
strPrice = new String[rowcount];
strDescription = new String[rowcount];
if (cursorMenu.moveToFirst()) {
do {
strName[index] = cursorMenu.getString(1);
strDescription[index] = cursorMenu.getString(2);
strPrice[index] = cursorMenu.getString(3);
Log.v(TAG, "Name-- " + strName[index] + "Price-- "
+ strPrice[index]);
index++;
} while (cursorMenu.moveToNext());
}
cursorMenu.close();
} else {
Toast.makeText(this, "No Data found", Toast.LENGTH_LONG).show();
}*/
list = (ListView) findViewById(R.id.lstMenu);
list.setAdapter(new EfficientAdapter(this));
System.out.println("--List Child count-----"+list.getChildCount());
System.out.println("--List count-----"+list.getCount());
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(),
"You clciked " + strName[arg2] + "\t" + strPrice[arg2],
Toast.LENGTH_LONG).show();
}
});
}
}
http://www.vogella.de/articles/AndroidListView/article.html go through this example you can get every thing regards listview.
Related
I have checked most of the places but i could not get the precise answer for this question.
problem in function : getView
What is the problem : When if condition gets true,
mproduct.remove((position));
notifyDataSetChanged();
both statement suppose to work.
// here mproduct is object of ArrayList;
If i write Log.e(); It displays promt message.
Thanks in advance.
{
public class DataAdapterCheckOut extends BaseAdapter {
Context context;
ArrayList<CheckOutProduct> mproduct;
public DataAdapterCheckOut(Context context, ArrayList<CheckOutProduct>
product){
// super(context, R.layout.activity_list_product, product);
this.context=context;
this.mproduct=product;
}
public class Holder{
TextView nameFV, mrpFV, our_priceFV, weightFv, unitFV, countFV;
ImageView pic;
int countTemp=1,mrp=0,ourPrice=0;
String name;
Button btnAdd, btnSubstract, btnAddCart;
}
#Override
public int getCount() {
return mproduct.size();
}
#Override
public Object getItem(int position) {
return mproduct.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final CheckOutProduct checkOutProduct = mproduct.get(position);
// Check if an existing view is being reused, otherwise inflate the view
SharedPreferences prefs = context.getSharedPreferences("MNA",
Context.MODE_PRIVATE);
String personalEmail = prefs.getString("personalEmail", null);
String mobTemp = prefs.getString("MNAF", null);
final Holder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.activity_list_product,
parent, false);
viewHolder.nameFV = (TextView)
convertView.findViewById(R.id.txtNameViewer);
//viewHolder.idFV = (TextView)
convertView.findViewById(R.id.txtIdViewer);
viewHolder.mrpFV = (TextView)
convertView.findViewById(R.id.txtMrpViewer);
viewHolder.our_priceFV = (TextView)
convertView.findViewById(R.id.txtOurPriceViewer);
viewHolder.weightFv = (TextView)
convertView.findViewById(R.id.txtWeightViewer);
viewHolder.unitFV = (TextView)
convertView.findViewById(R.id.txtUnitViewer);
viewHolder.countFV = (TextView)
convertView.findViewById(R.id.txtViewProductCount);
viewHolder.pic = (ImageView)
convertView.findViewById(R.id.imgView);
viewHolder.btnAdd = (Button)
convertView.findViewById(R.id.buttonAdd);
viewHolder.btnSubstract = (Button)
convertView.findViewById(R.id.buttonSubstract);
viewHolder.btnAddCart = (Button)
convertView.findViewById(R.id.buttonAddCart);
convertView.setTag(viewHolder);
} else {
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(checkOutProduct.get_name());
viewHolder.name = checkOutProduct.get_name();
viewHolder.mrpFV.setText("MRP : " +
checkOutProduct.getMrp());
viewHolder.mrp = checkOutProduct.getMrp();
viewHolder.our_priceFV.setText("Our Price : " +
checkOutProduct.getOurPrice());
viewHolder.ourPrice = checkOutProduct.getOurPrice();
viewHolder.weightFv.setText(checkOutProduct.getWeight());
viewHolder.unitFV.setText(" " + checkOutProduct.getUnit());
viewHolder.pic.setImageBitmap(convertToBitmap(checkOutProduct.getImage()));
viewHolder.countFV.setText("" +
checkOutProduct.get_quantity());
viewHolder.countTemp = checkOutProduct.get_quantity();
viewHolder.btnAdd.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp++;
viewHolder.countFV.setText("" +
viewHolder.countTemp);
}
});
viewHolder.btnSubstract.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp--;
if (viewHolder.countTemp >= 1)
viewHolder.countFV.setText("" +
viewHolder.countTemp);
else {
Toast.makeText(context, "Sorry Item Count at
least 1", Toast.LENGTH_LONG).show();
viewHolder.countTemp = 1;
}
}
});
viewHolder.btnAddCart.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("B", "Added into Cart");
SharedPreferences prefs =
context.getSharedPreferences("MNA", Context.MODE_PRIVATE);
String personalEmail =
prefs.getString("personalEmail", null);
CheckOutDBHelper checkOutDBHelper1 = new
CheckOutDBHelper(context);
checkOutDBHelper1.addCheckOutInformation(new
CheckOutProduct(personalEmail, checkOutProduct.get_name(),
checkOutProduct.getID(), checkOutProduct.getMrp(),
checkOutProduct.getOurPrice(), checkOutProduct.getWeight(),
checkOutProduct.getUnit(), checkOutProduct.getImage(),
viewHolder.countTemp));
}
});
UserDBHelper userDBHelper = new UserDBHelper(context);
if(personalEmail!=null&&!personalEmail.equals(checkOutProduct.get_gmail()))
{
mproduct.remove(position);
notifyDataSetChanged();
}
if (mobTemp!=null&&!userDBHelper.getEmailId(mobTemp).equals(checkOutProduct.get_gmail())){
mproduct.remove((`enter code here`position));
notifyDataSetChanged();
enter code here
}
return convertView;
}
//get bitmap image from byte array
private Bitmap convertToBitmap(byte[] b){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
}
}
I used GridView to display images of types of batteries. When user clicks any image, the features of that particular battery will get print on next page. The images and features are fetching from the server. The problem is the first battery image is displaying when I opened the GridView, but the other battery images are displaying in that GridView only after I scroll the screen two to three times. But I want to display all the images once I opened the GridView.
private void getDatasFromIntent() {
alHM = new ArrayList<>();
Intent intent = getIntent();
String typeResp = intent.getStringExtra("IMG_S");
try {
JSONObject jsonObject = new JSONObject(typeResp);
JSONArray jsonArray = jsonObject.getJSONArray("process");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hm = new HashMap<>();
JSONObject bat_json = jsonArray.getJSONObject(i);
String battery_featues_id = bat_json.getString("battery_featues_id");
String battery = bat_json.getString("battery_type");
String battery_image = bat_json.getString("battery_image");
battery_image = battery_image.replace("\\", "");
hm.put("battery_featues_id", battery_featues_id);
hm.put("battery_type", battery);
hm.put("battery_image", battery_image);
alHM.add(hm);
}
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this, alHM);
// Set custom adapter to gridview
GridView gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(SampleBatteryList.this, "a: " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GridviewAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> list;
private final SampleBatteryList activity;
public GridviewAdapter(SampleBatteryList sampleBatteryList,
ArrayList<HashMap<String, String>> alHM) {
this.activity = sampleBatteryList;
this.list = alHM;
Log.d("VOLLY", "ADP :" + alHM);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class ViewHolder {
public ImageView imgViewFlag;
public TextView txtViewTitle;
public Button button;
ViewHolder view;
}
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
}
here you are using view holder class but after initialization part and assign value part are in if and else so value not showing.
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
change to
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
}else{
view = (ViewHolder) contentView.getTag();
}
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
return contentView;
}
I have implemented a listview with checkbox where the checkbox is ticked whenever the user clicks on it. But I realized it's pretty inconvenient this way and I'd like to change it to whenever the user clicks on a row, the checkbox will be automatically ticked. My question is how can I do that? How can I change the code in listView.setOnItemClickListener such that my checkbox will be ticked? Any ideas?
This is my code so far:
MyCustomAdapter dataAdapter = null;
public static ArrayList countries = new ArrayList();;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isNetworkAvailable()) {
setContentView(R.layout.activity_show_countries);
ArrayList countries = new ArrayList();
countries.clear(); // refresh
//Generate list View from ArrayList
displayListView();
Button btn1 = (Button) findViewById(R.id.next);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ShowCountries.this, ShowTypes.class));
}
});
}
else
{
startActivity(new Intent(ShowCountries.this, NoInternetConnection.class));
}
}
private void displayListView() {
//Array list of countries
countries.clear();//refresh
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("POIs","Show POIs around me",false);
countryList.add(country);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.list_countries);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
if (countries.indexOf(country.getName()) !=-1) {
countries.remove(country.getName());
}
else
{
// thick checkbox
countries.add(country.getName());
}
// Toast.makeText(getApplicationContext(),
// "Clicked on Row: " + country.getName(),
// Toast.LENGTH_LONG).show();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#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)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Country country = (Country) cb.getTag();
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
if (countries.indexOf(cb.getText()) !=-1) {
country.setSelected(cb.isChecked());
countries.remove(cb.getText());
}
else
{
countries.add(cb.getText());
}
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(" (" + country.getCode() + ")");
holder.name.setText(country.getName());
holder.name.setChecked(country.isSelected());
holder.name.setTag(country);
return convertView;
}
}
}
I guess there are couple of ways to do it, the one I use is:
Make a custom ListView using custom view which has a Checkbox then in getView() method use that Checkbox. Then make it implement setOnCheckChangeListener() to register the clicking.
And also don't forget to set value to Checkbox for example
Checkbox.setChecked(condition)
Checkbox.setOnCheckChangeListener()
I hope this helps
When your list item has been clicked, just call the toggle() function on your checkbox. And for your listview register a listselector to indicate focused and pressed states.
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...
My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..