I have a list of array adapters that have the following layout which contains checkbox, textview increase, textview count, and textview decrease :
layout product adapter.
what the problem is how to call or implement clicklistener from ProdukActivity.java on each object that appears on the adapter. I just want to know how does it work with object in adapter so i can count the product price in every checkbox is checked.
Here is my adapter code :
public class ProductAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<ProductModel> productItems;
public ProductAdapter(Activity activity, List<ProductModel> productItems) {
this.activity = activity;
this.productItems = productItems;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int location) {
return productItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_produk, null);
CheckBox namaProduk = (CheckBox) convertView.findViewById(R.id.checkBox_productName);
TextView kurangProduk = (TextView) convertView.findViewById(R.id.decrease_product);
TextView hitungProduk = (TextView) convertView.findViewById(R.id.count_product);
TextView tambahProduk = (TextView) convertView.findViewById(R.id.increase_product);
TextView hargaProduk = (TextView) convertView.findViewById(R.id.product_price);
ProductModel produk = productItems.get(position);
namaProduk.setText(produk.getProduct_name());
hargaProduk.setText(produk.getProduct_price());
return convertView;
}
}
and here is my ProdukActivity.java :
public class ProdukLaundry extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
ActionBar actionBar;
ListView listProduk;
SwipeRefreshLayout swipeProduct;
List<ProductModel> productList = new ArrayList<ProductModel>();
ProductAdapter productAdapter;
int success;
AlertDialog.Builder dialog;
RadioButton radioReguler, radioExpress;
TextView tvTotal;
Button next;
String product_id, laundry_id, product_name, product_price, service_type;
private int offset = 0;
private static final String TAG = ProdukLaundry.class.getSimpleName();
private static String url_select = Server.URL + "selectproduk.php";
public static final String TAG_PRODUCT_ID = "product_id";
public static final String TAG_LAUNDRY_ID = "laundry_id";
public static final String TAG_PRODUCT_NAME = "product_name";
public static final String TAG_PRODUCT_PRICE = "product_price";
public static final String TAG_SERVICE_TYPE = "service_type";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
int countcheckBox = 0;
int totalCount = 0;
boolean regular = true;
boolean express = false;
boolean checkBox = false;
Transaction transaction;
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new ProductAdapter(ProdukLaundry.this, productList);
listProduk.setAdapter(productAdapter);
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRefresh() {
productList.clear();
productAdapter.notifyDataSetChanged();
callProduct();
}
public void onClick(View view){
switch (view.getId()){
case R.id.increase_product:
countcheckBox++;
changeCheckBox();
hitung();
break;
case R.id.decrease_product:
if (countcheckBox>0){
countcheckBox--;
changeCheckBox();
hitung();
}
break;
case R.id.button_next:
save();
break;
default:
break;
}
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio_regular:
if (checked) {
regular = true;
express = false;
hitung();
}
break;
case R.id.radio_express:
if (checked){
regular = false;
express = true;
hitung();
}
break;
}
}
public void changeCheckBox(){
tvTotal.setText(countcheckBox+"");
}
public void hitung(){
int totalCount = 0;
int expressCost = 20000;
int harga = Integer.parseInt(product_price);
if (checkBox){
if (express){
totalCount+=(harga+expressCost)*countcheckBox;
}else{
totalCount+=harga*countcheckBox;
}
}
this.totalCount = totalCount;
tvTotal.setText(this.totalCount+"");
}
private void save() {
if (tvTotal.getText().toString().equals("0")){
Toast.makeText(this, "Choose Service.",
Toast.LENGTH_SHORT).show();
return;
}
String transId = "variabel transaksi id";
String uid = "variabel produk id";
String type;
if (regular) {
type = "regular";
} else {
type = "express";
}
transaction = new Transaction(transId, uid, type);
if (checkBox) {
transaction.setCheckBox(String.valueOf(countcheckBox));
}
transaction.total = String.valueOf(totalCount);
/*Intent intent = new Intent(this, LocationActivity.class);
intent.putExtra("transaction", transaction);
startActivity(intent);*/
}
Add listener for every object like below, inside getView of adapter. And inside the listener, do your handling
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_produk, null);
final CheckBox namaProduk = (CheckBox) convertView.findViewById(R.id.checkBox_productName);
TextView kurangProduk = (TextView) convertView.findViewById(R.id.decrease_product);
TextView hitungProduk = (TextView) convertView.findViewById(R.id.count_product);
TextView tambahProduk = (TextView) convertView.findViewById(R.id.increase_product);
TextView hargaProduk = (TextView) convertView.findViewById(R.id.product_price);
ProductModel produk = productItems.get(position);
namaProduk.setText(produk.getProduct_name());
hargaProduk.setText(produk.getProduct_price());
namaProduk.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//check here
}
}
}
);
kurangProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
hitungProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
tambahProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
hargaProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
return convertView;
}
Related
In my App, I'm using Custom Listview, where I need to delete an item from Listview as well as corresponding row from CSV file simultaneously when Listview is long clicked.
My CSV file looks like this
2020/11/22,10:30PM,96.3°F,Normal,Body
2020/11/22,10:30PM,98.2°F,Normal,Body
2020/11/22,10:31PM,96.7°F,Normal,Body
2020/11/22,10:40PM,95.0°F,Normal,Body
For instance, if second item from Listview is removed when long clicked, the corresponding data row from CSV file above which is second row on CSV file should also be removed when Listview is long clicked.
Here's my Code:
LogViewActivity.java
public class LogViewActivity extends BaseAppCompatActivity {
private static final String TAG = "LogViewActivity";
private File logFile;
private Toolbar toolbar;
private ListView lvproducts;
ArrayList<Product> list;
ProductAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_view_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
public void onResume() {
super.onResume();
logFile = (File) getIntent().getExtras().get(Constants.EXTRA_LOG_FILE);
if (logFile != null) {
toolbar.setTitle(logFile.getName());
try {
setLogText(logFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_log_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.action_send_to:
intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(logFile), "text/plain");
startActivity(intent);
break;
default:
Log.e(TAG, "Unknown id");
break;
}
return super.onOptionsItemSelected(item);
}
private void setLogText(File file) throws FileNotFoundException {
// Textview visisbility is invisible and used only for setting up String data.
TextView textView1 = (TextView) findViewById(R.id.tvview1);
TextView textView2 = (TextView) findViewById(R.id.tvview2);
TextView textView3 = (TextView) findViewById(R.id.tvview3);
TextView textView4 = (TextView) findViewById(R.id.tvview4);
TextView textView5 = (TextView) findViewById(R.id.tvview5);
lvproducts = (ListView) findViewById(R.id.lvproducts);
list =new ArrayList<Product>();
Scanner inputStream;
inputStream = new Scanner(file);
while(inputStream.hasNext()){
String line= inputStream.next();
if (line.equals("")) { continue; } // <--- notice this line
String[] values = line.split(",");
String V = values[0];
String W= values[1];
String X= values[2];
String Y= values[3];
String Z= values[4];
// Textview visisbility is invisible and used only for setting up String data.
textView1.setText(Z);
textView2.setText(X);
textView3.setText(Y);
textView4.setText(V);
textView5.setText(W);
Product product1 = new Product(textView1.getText().toString(), textView2.getText().toString(), textView3.getText().toString(), textView4.getText().toString(), textView5.getText().toString());
list.add(product1);
adapter = new ProductAdapter(LogViewActivity.this, list);
lvproducts.setAdapter(adapter);
}
inputStream.close();
lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int which_item = position;
new AlertDialog.Builder(LogViewActivity.this)
.setTitle(getResources().getString(R.string.delete_log_file_title))
.setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
+ getResources().getString(R.string.file_name))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(which_item);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
});
}
}
Product.java
public class Product {
private String mode;
private String temp;
private String condition;
private String dates;
private String times;
public Product(String mode, String temp, String condition, String dates, String times) {
this.mode = mode;
this.temp = temp;
this.condition = condition;
this.dates = dates;
this.times = times;
}
public String getMode() {
return mode;
}
public String getTemp() {
return temp;
}
public String getCondition() {
return condition;
}
public String getDates() {
return dates;
}
public String getTimes() {
return times;
}
}
ProductAdapter.java
public class ProductAdapter extends ArrayAdapter<Product> {
private final Context context;
private final ArrayList<Product> values;
public ProductAdapter(#NonNull Context context, ArrayList<Product> list) {
super(context, R.layout.row_layout, list);
this.context = context;
this.values = list;
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = inflater.inflate(R.layout.row_layout, parent, false);
CardView cdview = (CardView) rowview.findViewById(R.id.cdview);
TextView tvtemp = (TextView) rowview.findViewById(R.id.tvtemp);
TextView tvcondition = (TextView) rowview.findViewById(R.id.tvcondition);
TextView tvdate = (TextView) rowview.findViewById(R.id.tvdate);
TextView tvtime = (TextView) rowview.findViewById(R.id.tvtime);
ImageView ivmode = (ImageView) rowview.findViewById(R.id.ivmode);
tvtemp.setText(values.get(position).getTemp());
tvcondition.setText(values.get(position).getCondition());
tvdate.setText(values.get(position).getDates());
tvtime.setText(values.get(position).getTimes());
if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_blue);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.homewhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Normal")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backgreen);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Low-Grade-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backyellow);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("High-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("HIGH")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("LOW")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_low);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.homewhite);
}
return rowview;
}
}
Please help me out. Thank you!
You are only removing item from the loaded data set, therefore only list item is removing. You need to update your csv file on removal of list item
lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int which_item = position;
new AlertDialog.Builder(LogViewActivity.this)
.setTitle(getResources().getString(R.string.delete_log_file_title))
.setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
+ getResources().getString(R.string.file_name))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(which_item);
adapter.notifyDataSetChanged();
updateCSVFile();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
});
public void updateCSVFile() {
// Write your logic her to update CSV file after item removal.
}
I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.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 inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.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 inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] answers = new String[]{"choice0","choice2","choice0","choice1","choice3","choice3"};
Question[] questions = new Question[6];
for(int i=0; i<6; i++){
questions[i] = new Question("Question"+(1+i),new String[]{"choice0","choice1","choice2","choice3"},answers[i]);
}
ListView listView = (ListView)findViewById(R.id.listQuestions);
QuestionAdapter questionAdapter = new QuestionAdapter(this, R.layout.list_item_row_qs, questions);
listView.setAdapter(questionAdapter);
}
}
Adapter
public class QuestionAdapter extends ArrayAdapter {
Context context;
Question[] questions;
View view;
public QuestionAdapter(Context context, int id, Question[] questions){
super(context, id, questions);
this.context = context;
this.questions = questions;
}
private class ViewHolder{
TextView chapName;
RadioButton rb0;
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
Button button;
RadioGroup rg;
TextView hiddenAnswer;
}
#Override
public View getView(int pos, View row, ViewGroup parent){
this.view = row;
ViewHolder viewHolder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item_row_qs, null);
viewHolder = new ViewHolder();
viewHolder.chapName=(TextView) row.findViewById(R.id.question);
viewHolder.rb0 = (RadioButton) row.findViewById(R.id.choice0);
viewHolder.rb1 = (RadioButton) row.findViewById(R.id.choice1);
viewHolder.rb2 = (RadioButton) row.findViewById(R.id.choice2);
viewHolder.rb3 = (RadioButton) row.findViewById(R.id.choice3);
viewHolder.button = (Button) row.findViewById(R.id.check);
viewHolder.hiddenAnswer = (TextView) row.findViewById(R.id.answer);
row.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)row.getTag();
}
viewHolder.chapName.setText(questions[pos].getQuestionDescr());
viewHolder.rb0.setText(questions[pos].getChoice()[0]);
viewHolder.rb1.setText(questions[pos].getChoice()[1]);
viewHolder.rb2.setText(questions[pos].getChoice()[2]);
viewHolder.rb3.setText(questions[pos].getChoice()[3]);
viewHolder.hiddenAnswer.setText(questions[pos].getAnswer());
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowView = (ViewGroup) v.getParent();
RadioGroup group = (RadioGroup) rowView.findViewById(R.id.rg);
int selectedId = group.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(context, "Please choose the correct option", Toast.LENGTH_LONG).show();
} else {
RadioButton radioButton = (RadioButton) group.findViewById(selectedId);
String answer = String.valueOf(((TextView) rowView.findViewById(R.id.answer)).getText());
if (radioButton.getText().equals(answer)) {
Toast.makeText(context, "Correct Answer", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Wrong Answer", Toast.LENGTH_LONG).show();
}
}
}
});
return row;
}
}
Problem
First item in the list maps to 5th item. 2nd item to sixth item. I mean if I change radio button at the first item, Same radio button gets selected at the 5th list item also.
Any suggestions?
Is it because of recycling?
How do I resolve it?
I tried saving in Question object and retrieving it. I used pos to retrieve and set. But same problem still exist.
Adapter:
public class PersonAdapter extends BaseAdapter
{
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
}
Activity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
// _adapter = new PersonAdapter(this, _data);
// _listView.setAdapter(_adapter);
RedirectToMainActivityTask task = new RedirectToMainActivityTask();
task.execute();
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}
}
I am saving the state of the person view inside of person object
Explanation:
I have a listview in my fragment. When I click one of the row of the listview it goes to another activity.In listview,I got the data from the adapter.
Inside the adapter view,I set the setOnClick().
Problem is when I click one of the row multiple time it is opening multiple activity.I want to restrict only one time click on the particular row over the listview item.
Here is my fragment where I get the listview and set the adapter-
public class HomeFragment extends Fragment{
public HomeFragment() {
}
public static String key_updated = "updated", key_description = "description", key_title = "title", key_link = "link", key_url = "url", key_name = "name", key_description_text = "description_text";
private static String url = "";
List<String> lst_key = null;
List<JSONObject> arr_completed = null;
List<String> lst_key2 = null;
List<JSONObject> lst_obj = null;
List<String> list_status = null;
ListView completed_listview;
int PagerLength = 0,exeption_flag=0;
View rootView;
private ViewPager pagerRecentMatches;
private ImageView imgOneSliderRecent;
private ImageView imgTwoSliderRecent;
private ImageView imgThreeSliderRecent;
private ImageView imgFourSliderRecent;
private ImageView imgFiveSliderRecent;
private ImageView imgSixSliderRecent;
private ImageView imgSevenSliderRecent;
private ImageView imgEightSliderRecent;
LinearLayout selector_dynamic;
LinearLayout Recent_header_layout;
FrameLayout adbar;
String access_token = "";
SharedPreferences sharedPreferences;
int current_pos=0,status_flag=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
findViews();
selector_dynamic = (LinearLayout) rootView.findViewById(R.id.selectors_dynamic);
adbar = (FrameLayout) rootView.findViewById(R.id.adbar);
new AddLoader(getContext()).LoadAds(adbar);
MainActivity activity = (MainActivity) getActivity();
access_token = activity.getMyData();
sharedPreferences = getContext().getSharedPreferences("HomePref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (access_token == null || access_token=="") {
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + sharedPreferences.getString("access_token", null) + "&card_type=summary_card";
} else {
editor.putString("access_token", access_token);
editor.commit();
url = "https://api.litzscore.com/rest/v2/recent_matches/?access_token=" + access_token + "&card_type=summary_card";
}
completed_listview = (ListView) rootView.findViewById(R.id.completed_listview);
Recent_header_layout = (LinearLayout) rootView.findViewById(R.id.Recent_header_layout);
Recent_header_layout.setVisibility(View.GONE);
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
new TabJson().execute();
}
pagerRecentMatches.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
return rootView;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void dialog_popup() {
final Dialog dialog = new Dialog(getContext());
DisplayMetrics metrics = getResources()
.getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.90);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.internet_alert_box);
dialog.getWindow().setLayout(screenWidth, WindowManager.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
getActivity().finish();
}
});
dialog.show();
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Utils.isNetworkConnected(getContext())){
dialog_popup();
}
else{
dialog.dismiss();
new TabJson().execute();
}
}
});
dialog.show();
}
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
exeption_flag=0;
status_flag = 0;
if (jsonStr != null) {
try {
if (jsonStr.equals("IO") || jsonStr.equals("MalFormed") || jsonStr.equals("NotResponse")) {
exeption_flag = 1;
} else {
JSONObject obj = new JSONObject(jsonStr);
if (obj.has("status") && !obj.isNull("status")) {
if (obj.getString("status").equals("false") || obj.getString("status").equals("403")) {
status_flag = 1;
} else {
JSONObject data = obj.getJSONObject("data");
JSONArray card = data.getJSONArray("cards");
PagerLength = 0;
lst_obj = new ArrayList<>();
list_status = new ArrayList<>();
lst_key = new ArrayList<>();
lst_key2 = new ArrayList<>();
arr_completed = new ArrayList<>();
for (int i = 0; i < card.length(); i++) {
JSONObject card_obj = card.getJSONObject(i);
if (card_obj.getString("status").equals("started")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("notstarted")) {
PagerLength++;
lst_obj.add(card_obj);
list_status.add(card_obj.getString("status"));
lst_key.add(card_obj.getString("key"));
}
if (card_obj.getString("status").equals("completed")) {
arr_completed.add(card_obj);
lst_key2.add(card_obj.getString("key"));
}
}
}
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Utils.Pdialog_dismiss();
if (status_flag == 1 || exeption_flag==1) {
dialog_popup();
} else {
Recent_header_layout.setVisibility(View.VISIBLE);
LiveAdapter adapterTabRecent = new LiveAdapter(getContext(), lst_obj, PagerLength, list_status, lst_key);
adapterTabRecent.notifyDataSetChanged();
pagerRecentMatches.setAdapter(adapterTabRecent);
pagerRecentMatches.setCurrentItem(current_pos);
ScheduleAdapter CmAdapter = new ScheduleAdapter(getContext(), arr_completed, lst_key2);
CmAdapter.notifyDataSetChanged();
completed_listview.setAdapter(CmAdapter);
}
}
}
private void findViews() {
pagerRecentMatches = (ViewPager) rootView
.findViewById(R.id.pager_recent_matches);
imgOneSliderRecent = (ImageView) rootView
.findViewById(R.id.img_one_slider_recent);
imgTwoSliderRecent = (ImageView) rootView
.findViewById(R.id.img_two_slider_recent);
imgThreeSliderRecent = (ImageView) rootView
.findViewById(R.id.img_three_slider_recent);
imgFourSliderRecent=(ImageView)rootView.findViewById(R.id.img_four_slider_recent);
imgFiveSliderRecent=(ImageView)rootView.findViewById(R.id.img_five_slider_recent);
imgSixSliderRecent=(ImageView)rootView.findViewById(R.id.img_six_slider_recent);
imgSevenSliderRecent = (ImageView) rootView.findViewById(R.id.img_seven_slider_recent);
imgEightSliderRecent = (ImageView) rootView.findViewById(R.id.img_eight_slider_recent);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
After load the data from the server it passed to the onPost() i called an adapter which extends BaseAdpter
Here is my BaseAdapter
package adapter;
public class ScheduleAdapter extends BaseAdapter{
private Context context;
private List<JSONObject> arr_schedule;
private List<String> arr_matchKey;
private static LayoutInflater inflater;
int flag = 0;
String time="";
String status="";
String match_title = "";
String match_key="";
public ScheduleAdapter(Context context,List<JSONObject> arr_schedule,List<String> arr_matchKey){
this.context=context;
this.arr_schedule=arr_schedule;
this.arr_matchKey=arr_matchKey;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.arr_schedule.size();
}
#Override
public Object getItem(int position) {
return this.arr_schedule.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class Holder{
TextView txt_one_country_name;
TextView txt_two_country_name;
TextView txt_venue;
TextView txtTimeGMT;
TextView txtDate;
TextView txtTimeIST;
ImageView team_one_flag_icon;
ImageView team_two_flag_icon;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
String[] parts;
String[] state_parts;
String[] match_parts;
Typeface tf=null;
String winner_team = "";
String final_Score="";
String now_bat_team="",team_name="";
String related_status="";
if(convertView==null) {
convertView = inflater.inflate(R.layout.recent_home_layout, null);
holder.txt_one_country_name = (TextView) convertView.findViewById(R.id.txt_one_country_name);
holder.txt_two_country_name = (TextView) convertView.findViewById(R.id.txt_two_country_name);
holder.txt_venue = (TextView) convertView.findViewById(R.id.venue);
holder.txtTimeIST = (TextView) convertView.findViewById(R.id.txt_timeist);
holder.txtTimeGMT = (TextView) convertView.findViewById(R.id.txt_timegmt);
holder.txtDate = (TextView) convertView.findViewById(R.id.txt_date);
holder.team_one_flag_icon = (ImageView) convertView.findViewById(R.id.team_one_flag_icon);
holder.team_two_flag_icon = (ImageView) convertView.findViewById(R.id.team_two_flag_icon);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
holder.txt_one_country_name.setTypeface(tf);
holder.txt_two_country_name.setTypeface(tf);
holder.txt_venue.setTypeface(tf);
holder.txtTimeIST.setTypeface(tf);
holder.txtTimeGMT.setTypeface(tf);
holder.txtDate.setTypeface(tf);
convertView.setTag(holder);
}
else{
holder=(Holder)convertView.getTag();
}
try {
String overs="";
String wickets_now="";
String now_runs="";
String[] over_parts;
time = "";
JSONObject mainObj = this.arr_schedule.get(position);
status = mainObj.getString("status");
String name = mainObj.getString("short_name");
String state = mainObj.getString("venue");
String title = mainObj.getString("title");
related_status=mainObj.getString("related_name");
JSONObject start_date = mainObj.getJSONObject("start_date");
JSONObject teams=null;
JSONObject team_a=null;
JSONObject team_b=null;
String team_a_key="";
String team_b_key="";
time = start_date.getString("iso");
parts = name.split("vs");
match_parts = title.split("-");
state_parts = state.split(",");
int length = state_parts.length;
flag=0;
match_title="";
winner_team="";
if (!mainObj.isNull("msgs")) {
JSONObject msgs = mainObj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
flag = 1;
}
}
match_title=name+" - "+match_parts[1];
JSONObject now=null;
if(mainObj.has("now") && !mainObj.isNull("now")) {
now = mainObj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if(now.getString("runs_str").equals("null")){
overs="0";
}
else{
over_parts=now.getString("runs_str").split(" ");
overs=over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
try {
if (!mainObj.isNull("teams") && mainObj.has("teams")) {
teams = mainObj.getJSONObject("teams");
team_a = teams.getJSONObject("a");
team_b = teams.getJSONObject("b");
team_a_key = team_a.getString("key");
team_b_key = team_b.getString("key");
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
}
}
catch (NullPointerException e){
e.printStackTrace();
}
if(mainObj.has("status_overview") && !mainObj.isNull("status_overview")){
if(mainObj.getString("status_overview").equals("abandoned") || mainObj.getString("status_overview").equals("canceled")){
final_Score="";
}
else{
final_Score=team_name+" - "+now_runs+"/"+wickets_now+" ("+overs+" ovr)";
}
}
holder.txt_one_country_name.setText(parts[0]);
holder.txt_two_country_name.setText(parts[1]);
if(length==1){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
holder.txtTimeGMT.setText(state_parts[0]);
}
if(length==2){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
holder.txtTimeGMT.setText(state_parts[0] + "," + state_parts[1]);
}
if(length==3){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[1] + "," + state_parts[2]);
}
if(length==4){
holder.txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
holder.txtTimeGMT.setText(state_parts[2] + "," + state_parts[3]);
}
holder.txtDate.setText(final_Score);
holder.txtDate.setTypeface(tf, Typeface.BOLD);
holder.txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
holder.txtTimeIST.setText(winner_team);
holder.txt_venue.setText(related_status);
} catch (JSONException e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
}
});
return convertView;
}
#Override
public boolean isEnabled(int position) {
return super.isEnabled(position);
}
}
This adapter set the listrow item into listview.
In ScheduleAdapter.java i set the onclick() on the convertView in which i called a GetValue class which is only implement a Asynctask to get the data and called and intent then it goes to an activity.
Means HomeFragment->ScheduleAdapter->GetValue->Scorecard
Here,
HomeFragment is fragment which have listview
ScheduleAdpter is an adapter which set data to listview which reside in homefragment
GetValue is class which implement some important task and it passed an intent and goes to an activity(It's work as a background)
ScoreCard is my activity which called after click on the row of the listview which reside in HomeFragment.
Please, help me to solve out this problem.
You can use a flag in Listview click - isListClicked, and set flag value as false in onPostexecute method of Aysnc task class -GetValue
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isListClicked){
match_key = arr_matchKey.get(position);
MainActivity activity = (MainActivity) context;
GetValue gv = new GetValue(context);
gv.setFullUrl(match_key);
gv.setAccessToken(activity.getMyData());
gv.execute();
isListClicked = true;
}
}
});
If you want to prevent multiple activities being opened when the user spams with touches, add into your onClick event the removal of that onClickListener so that the listener won't exist after the first press.
Easy way is you can create a model class of your json object with those field you taken in holder class. And add one more boolean field isClickable with by default with true value.Now when user press a row for the first time you can set your model class field isClickable to false. Now second time when user press a row,you will get a position of row and you can check for isClickable. it will return false this time.
Model Class :
public class CountryInfoModel {
//other fields to parse json object
private boolean isClickable; //<- add one more extra field
public boolean isClickable() {
return isClickable;
}
public void setIsClickable(boolean isClickable) {
this.isClickable = isClickable;
}
}
listview click perform :
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//country_list is your list of model class List<CountryInfo>
if(country_list.get(position).isClickable())
{
//Perform your logic
country_list.get(position).setIsClickable(false);
}else{
//Do nothing : 2nd time click
}
}
});
Try creating your custom click listener for your listview and use it. In this way
public abstract class OnListItemClickListener implements OnItemClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public abstract void onListItemSingleClick(View parent, View view, int position, long id);
public OnListItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
onListItemSingleClick(parent, view, position, id);
}
}
I have a problem with click on image in item in ListView. When I click I want to show layout which is gone. This is my code:
public class MyActualOffers extends BaseActivity {
private IResponse iResponse = null;
private ListView actualOffersList;
private ActualOffersListAdapter actualOffersAdapter;
private ArrayList<Offers> actualOffersFromJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_actual_offers);
actualOffersFromJson = new ArrayList<Offers>();
actualOffersList = (ListView) findViewById(R.id.actualOffersList);
iResponse = new IResponse() {
#Override
public void onResponse(JSONObject jObject) {
// messageUser = new User();
// messageUser.parseJsonResponse(jObject);
// usersMessages.add(messageUser);
// new DownloadImageTask(profileP)
// .execute("http://"+messageUser.getAvatarURL());
//
// messagesListView.refreshDrawableState();
// adapter.notifyDataSetChanged();
// adapter.notifyDataSetInvalidated();
}
#Override
public void onResponse(JSONArray jArray) {
try {
for (int i = 0; i < 3; i++) {
JSONObject messageJSON = (JSONObject)jArray.get(i);
Offers offer = new Offers();
offer.parseJsonResponse(messageJSON);
actualOffersFromJson.add(offer);
}
}catch (JSONException e) {
e.printStackTrace();
}
actualOffersAdapter = new ActualOffersListAdapter(getApplicationContext(), actualOffersFromJson);
actualOffersList.setAdapter(actualOffersAdapter);
// adapter = new MessagesListAdapter(getApplicationContext(), myMessagesList, usersMessages);
// messagesListView.setAdapter(adapter);
}
#Override
public void onError(JSONObject jObject) {
ErrorObject error = new ErrorObject();
error.parseJsonResponse(jObject);
error.showErrorDialog(MyActualOffers.this);
}
};
getActualMyOffers();
}
private void getActualMyOffers(){
SharedPreferencesData sharedData = new SharedPreferencesData();
String url = ConnectionParams.URL_OFFERS_FETCH_CURRENT_USER_OFFERS.replace("{0}", ""+"get");
String token = "?auth_token="+sharedData.getTokenData(getBaseContext());
connection.get(url + token + "&state=active", iResponse);
}
private class ActualOffersListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Offers> offersList;
private LayoutInflater inflater;
private ViewHolder holder;
boolean isExpand = false;
public ActualOffersListAdapter(Context context, ArrayList<Offers> offersList) {
this.context = context;
this.offersList = offersList;
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return offersList.size();
}
#Override
public Object getItem(int position) {
return offersList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(
R.layout.actual_offers_list_item, null);
holder = new ViewHolder();
holder.cities = (TextViewWithImage) convertView.findViewById(R.id.actualOffersFromCityTXT);
holder.date = (TextView) convertView.findViewById(R.id.actualOffersCalendarTXT);
holder.type = (TextView) convertView.findViewById(R.id.actualOffersTripTypeTXT);
holder.shipment = (TextView) convertView.findViewById(R.id.actualOffersShipmentTypeTXT);
holder.transport = (TextView) convertView.findViewById(R.id.actualOffersTransportTypeTXT);
holder.deleteOffer = (TextView) convertView.findViewById(R.id.actualOffersDeleteTXT);
holder.editOffer = (TextView) convertView.findViewById(R.id.actualOffersEditOfferTXT);
holder.addSimilar = (TextView) convertView.findViewById(R.id.actualOffersAddSimilarTXT);
holder.addOpposite = (TextView) convertView.findViewById(R.id.actualOffersAddOppositeTXT);
holder.infoIcon = (ImageView) convertView.findViewById(R.id.actualOffersInfoICON);
holder.shipmentIcon = (ImageView) convertView.findViewById(R.id.actualOffersShipmentTypeICON);
holder.transportIcon = (ImageView) convertView.findViewById(R.id.actualOffersTransportTypeICON);
holder.typeIcon = (ImageView) convertView.findViewById(R.id.actualOffersTripTypeICON);
holder.expandIcon = (ImageView) convertView.findViewById(R.id.expandIcon);
holder.actualOffersExpandLayout = (RelativeLayout) convertView.findViewById(R.id.actualOffersExpandLayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.cities.setText(offersList.get(position).getStart() + " [img src=ic_in_text_arrow/] " + offersList.get(position).getDestination());
holder.date.setText(offersList.get(position).getCreatedAt());
if(offersList.get(position).getFrequency().equals("once")){
holder.typeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_in_text_once));
}else{
holder.typeIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_in_text_infinity));
}
holder.type.setText(offersList.get(position).getType());
holder.shipmentIcon.setImageDrawable(ShipmentTypeEnum.setIconForShipmentType(ShipmentTypeEnum.fromString(offersList.get(position).getShipmentType()), getApplicationContext()));
holder.transportIcon.setImageDrawable(TransportTypeEnum.setIconForTransportType(TransportTypeEnum.fromString(offersList.get(position).getTransportType()), getApplicationContext()));
holder.deleteOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.editOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.addSimilar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.addOpposite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder.expandIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isExpand){
holder.actualOffersExpandLayout.setVisibility(View.INVISIBLE);
isExpand = false;
}else{
holder.actualOffersExpandLayout.setVisibility(View.VISIBLE);
isExpand = true;
}
}
});
holder.infoIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
}
public static class ViewHolder {
public TextViewWithImage cities;
public TextView date;
public TextView type;
public TextView shipment;
public TextView transport;
public TextView deleteOffer;
public TextView editOffer;
public TextView addSimilar;
public TextView addOpposite;
public ImageView infoIcon;
public ImageView shipmentIcon;
public ImageView transportIcon;
public ImageView typeIcon;
public ImageView expandIcon;
public RelativeLayout actualOffersExpandLayout;
}
}
No when I click on holder.expandIcon in first item, expand layout show in last item of list. How can I create list with my item and properly working click on image in every item?
You are expanding the last item in the list because that was the last view retrieved by getView. The way the code is written now, there is only one isExpand value.
So you need to (a) add isExpand on the ViewHolder, and (b) use the ViewHolder attached to the View that was passed in the event handler. Like this:
holder.expandIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder vh = (ViewHolder)v.getTag();
if(vh.isExpand){
vh.actualOffersExpandLayout.setVisibility(View.INVISIBLE);
vh.isExpand = false;
}else{
vh.actualOffersExpandLayout.setVisibility(View.VISIBLE);
vh.isExpand = true;
}
}
});