I am trying to call a new fragment in android and when I am clicking the button Search it is working but after to execute the code:
Activity ac = (Activity) v.getContext();
AllFragment to = new AllFragment(null, false);
FragmentTransaction fragTransaction = ac.getFragmentManager().beginTransaction();
fragTransaction.replace(R.id.frame_container, to);
fragTransaction.addToBackStack(null);
fragTransaction.commit();
after it I see in the emulator the next screen:
then what I expected is a Listview of Products. The code I have in the fragment it is working perfect.
my fragment code is:
#SuppressLint("UseValueOf")
public class AllFragment extends ListFragment {
String codigo = null;
boolean esOferta = false;
public AllFragment(String codigo, boolean esOferta) {
this.esOferta = esOferta;
this.codigo = codigo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try
{
DataBaseManager db = new DataBaseManager(inflater.getContext());
Integer poblacion = null;
Integer provincia = null;
String codigo = null;
ArrayList<ProductsOffers> data = null;
if (db.existKey("PROVINCIA")) provincia = new Integer(db.getDatoByKey("PROVINCIA"));
if (db.existKey("POBLACION")) poblacion = new Integer(db.getDatoByKey("POBLACION"));
if (db.existKey("CODIGO")) codigo = db.getDatoByKey("CODIGO");
if (!this.esOferta) data = IAndroid.getAllProductsAndOffers(provincia, poblacion, this.codigo, null, null);
else {
data = IAndroid.getProductsByOfferCode(this.codigo);
}
if (data != null) setListAdapter(new ProductOffersListAdapter(inflater.getContext(), data));
}
catch (Exception ex)
{
}
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
}
In my emulator I am using version 4.0.3
My adapter code is:
public class ProductOffersListAdapter extends BaseAdapter {
private Context context;
private ArrayList<info.android.model.ProductsOffers> navProOffers;
public ProductOffersListAdapter(Context context, ArrayList<info.android.model.ProductsOffers> navProOffers) {
this.context = context;
this.navProOffers = navProOffers;
}
#Override
public int getCount() {
return navProOffers.size();
}
#Override
public info.android.model.ProductsOffers getItem(int position) {
return navProOffers.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.fragment_row, null);
}
ProductsOffers po = (ProductsOffers) getItem(position);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView vwtipo = (TextView) v.findViewById(R.id.vwTipo);
TextView vwcodigo = (TextView) v.findViewById(R.id.txtCodigo);
Activity act = (Activity) v.getContext();
ProductFragment to = new ProductFragment(vwcodigo.getText().toString(), vwtipo.getText().equals("OFERTA"));
FragmentTransaction fragTransaction = act.getFragmentManager().beginTransaction();
fragTransaction.replace(R.id.frame_container, to);
fragTransaction.addToBackStack(null);
fragTransaction.commit();
}
});
try
{
ImageView img = (ImageView) convertView.findViewById(R.id.image);
TextView vwtipo = (TextView) convertView.findViewById(R.id.vwTipo);
TextView txtCodigo = (TextView) convertView.findViewById(R.id.txtCodigo);
TextView txtCiudad = (TextView) convertView.findViewById(R.id.txtCiudad);
TextView txtVF = (TextView) convertView.findViewById(R.id.txtVF);
String sVF = Double.toString(getItem(position).ValorFinal) + "€";
String aux = "";
aux = po.tipo;
vwtipo.setText((aux.equals("O"))? "OFERTA":"PRODUCTO");
vwtipo.setBackgroundColor(aux.equals("O")?Color.RED: Color.WHITE);
txtVF.setText(sVF);
txtCiudad.setText(po.ciudad);
txtCodigo.setText(po.codigo);
convertView.setTag(po.codigo);
img.setImageBitmap(po.Imagen);
} catch (Exception ex) {}
return convertView;
}
}
Why my fragment is not executing?
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 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.
I have some problem. when I click a delete(btnPlus.setOnClickListener in the interestAdepter class) button from listview baseAdapter, I want to refresh the fragment which contains the listview.
1.InterestAdapter class{edtied}
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
public InterestAdapter() {
m_List = new ArrayList<InterestClass>();
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
2.InterestFragment{edited}
public class InterestFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private ListView interest_ListView;
private InterestAdapter interest_Adapter;
String TAG="response";
RbPreference keep_Login;
public InterestFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment InterestFragment.
*/
// TODO: Rename and change types and number of parameters
public static InterestFragment newInstance(String param1, String param2) {
InterestFragment fragment = new InterestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
keep_Login = new RbPreference(getContext());
Log.v("interFrag","oncreate");
// Inflate the layout for this fragment
/*if(keep_Login.get("name",null)!=null) {
return inflater.inflate(R.layout.fragment_interest, container, false);
}else{
return inflater.inflate(R.layout.need_login, container, false);
}*/
return inflater.inflate(R.layout.fragment_interest, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("ListFragment", "onActivityCreated().");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");
if(keep_Login.get("no",null)!=null) {
String enc_Id="";
Crypto enc=new Crypto();
try{
enc_Id=enc.AES_Encode(keep_Login.get("no",null),enc.global_deckey);
}catch(Exception e){
}
interest_Adapter = new InterestAdapter();
interest_ListView = (ListView) getView().findViewById(R.id.i_ListView);
AsyncCallInterest task = new AsyncCallInterest();
task.execute(enc_Id);
}
}
private class AsyncCallInterest extends AsyncTask<String, Void, JSONArray> {
JSONArray interest_Array;
InterestFragment interest;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected JSONArray doInBackground(String... params) {
String id=params[0];
dbConnection db_Cont=new dbConnection();
interest_Array=db_Cont.getFavorite(id);
Log.v("doinbackgroud", interest_Array.toString());
return interest_Array;
}
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interest_Adapter.add(i_Class);
}
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Is there any way to refresh the fragment from the button in baseAdapter class? I searched a lot but I couldn't fine answer. Please help me, Thank you.
{edited}
I add AsyncCallAddDelFavorite class and AsyncCallInterest class. Thank you.
Update your adapter constructor. After deleting content, remove the item from the arraylist and notify dataset changed.
public class InterestAdapter extends BaseAdapter{
private ArrayList<InterestClass> m_List;
private Context mContext;
public InterestAdapter(Context context, ArrayList<InterestClass> list) {
m_List = list;
mContext = context;
}
#Override
public int getCount() {
return m_List.size();
}
#Override
public Object getItem(int position) {
return m_List.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
TextView textName = null;
TextView textDate = null;
TextView textConPrice = null;
TextView textNowPrice = null;
TextView textFog = null;
ImageButton btnPlus = null;
CustomHolder holder = null;
if ( convertView == null ) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_interest, parent, false);
textName = (TextView) convertView.findViewById(R.id.i_ProdNmae);
textDate = (TextView) convertView.findViewById(R.id.i_Date);
textConPrice = (TextView) convertView.findViewById(R.id.i_InterPrice);
textNowPrice = (TextView) convertView.findViewById(R.id.i_currentPrice);
textFog = (TextView) convertView.findViewById(R.id.i_Analysis);
btnPlus = (ImageButton) convertView.findViewById(R.id.i_addBtn);
holder = new CustomHolder();
holder.i_TextView = textName;
holder.i_TextView1 = textDate;
holder.i_TextView2 = textConPrice;
holder.i_TextView3 = textNowPrice;
holder.i_TextView4 = textFog;
holder.i_Btn = btnPlus;
convertView.setTag(holder);
}
else {
holder = (CustomHolder) convertView.getTag();
textName = holder.i_TextView;
textDate = holder.i_TextView1;
textConPrice = holder.i_TextView2;
textNowPrice = holder.i_TextView3;
textFog = holder.i_TextView4;
btnPlus = holder.i_Btn;
}
/*if(position == 0) {
textName.setText("종목");
textDate.setText("관심일");
textConPrice.setText("관심가");
textNowPrice.setText("현재가");
textFog.setText("수급");
btnPlus.setEnabled(false);
}else{
}*/
textName.setText(m_List.get(position).getName());
textDate.setText(m_List.get(position).getDate());
textConPrice.setText(m_List.get(position).getConPrice());
textNowPrice.setText(m_List.get(position).getNowPrice());
textFog.setText(m_List.get(position).getFog());
btnPlus.setEnabled(true);
textName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailActivity.class);
context.startActivity(intent);
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crypto enc = new Crypto();
SharedPreferences pref = context.getSharedPreferences("com.rabiaband.pref", 0);
String[] add_Params = new String[2];
try {
add_Params[0] = enc.AES_Encode(pref.getString("no", null), enc.global_deckey);
add_Params[1] = enc.AES_Encode(m_List.get(pos).getJmcode(), enc.global_deckey);
} catch (Exception e) {
Log.e("HomeCryptographError:", "" + e.getMessage());
}
AsyncCallAddDelFavorite delFavorite = new AsyncCallAddDelFavorite();
delFavorite.execute(add_Params);
**m_List.remove(position);
notifyDatasetChanged();**
}
});
private class AsyncCallAddDelFavorite extends AsyncTask<String, Void, Void> {
JSONObject del_Favorite_List;
/* public AsyncCallAddFavorite(HomeFragment home){
this.home=home;
}*/
#Override
protected void onPreExecute() {
/*Log.i(TAG, "onPreExecute");*/
}
#Override
protected Void doInBackground(String... params) {
dbConnection db_Cont=new dbConnection();
String id=params[0];
String jmcode=params[1];
Log.v("doinbackgroud",""+id+"ssssss"+jmcode);
del_Favorite_List=db_Cont.delFavorite(id, jmcode);
Log.v("doinbackgroud",del_Favorite_List.toString());
return null;
}
#Override
protected void onPostExecute(Void result) {
/*Log.i(TAG, "onPostExecute");*/
}
}
}
Update Adapter initialization in fragment. You are adding item to adapter directly. Use arraylist and after downloading data create adapter instance.
private ArrayList<InterestClass> interestList = new ArrayList<>();
and update your onPostExecute Method
#Override
protected void onPostExecute(JSONArray result) {
try{
for (int i = 0 ; i < result.length() ; i ++){
InterestClass i_Class = new InterestClass();
String date=result.getJSONObject(i).getString("indate");
String time=date.substring(5,date.length());
i_Class.setJmcode(result.getJSONObject(i).getString("jmcode"));
i_Class.setName(result.getJSONObject(i).getString("jmname"));
i_Class.setDate(time);
i_Class.setConPrice(result.getJSONObject(i).getString("fprice"));
i_Class.setNowPrice(result.getJSONObject(i).getString("price"));
i_Class.setFog("40");
i_Class.setPlus(true);
interestList.add(i_Class);
}
interest_Adapter = new InterestAdapter(getActivity,interestList);
interest_ListView.setAdapter(interest_Adapter);
}catch(Exception e){
Toast.makeText(getActivity(), "interest"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
If I understand you correctly you want to remove the item from your ListView too after your removing it from your Database, to achieve that you can call this
m_List.remove(position);
interest_Adapter..notifyDataSetChanged();
First line removes the item and Second one will insure that the Adapter gets updated after the item has been removed.
Hope this helps
I am doing custom ListView in android and I have a share button on each item. After clicking button it must create chooser(facebook, etc). But when I click it the app crashes and logcat shows nothing. Please help me
Here is my Adapter:
public class AdapterQ extends BaseAdapter {
List<Quotes> sss;
Context ss;
Intent sendIntent;
public AdapterQ(Context ss, List<Quotes>items){
this.ss = ss;
this.sss = items;
}
#Override
public int getCount() {
return sss.size();
}
#Override
public Object getItem(int position) {
return sss.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
ss.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.quoteitem, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.legendImage);
final TextView tvTitle = (TextView) convertView.findViewById(R.id.legendName);
ImageView ssss= (ImageView) convertView.findViewById(R.id.Nation);
final Quotes quotes = sss.get(position);
imgIcon.setImageResource(quotes.getIcon());
tvTitle.setText(quotes.getText());
ssss.setImageResource(R.mipmap.ic_share_black_24dp);
ssss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendIntent =new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, tvTitle.getText());
sendIntent.setType("text/plain");
ss.startActivity(Intent.createChooser(sendIntent, "Поделиться..."));
}
});
return convertView;
}
}
Quotes:
public class Quotes {
private String mText;
private int mIcon;
public String getText() {
return mText;
}
public void setText(String mText) {
this.mText = mText;
}
public int getIcon() {
return mIcon;
}
public void setIcon(int mIcon) {
this.mIcon = mIcon;
}
}
Fragment:
public class AllFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rrrr = inflater.inflate(R.layout.fragment_all, container, false);
String[] ss = getResources().getStringArray(R.array.Абай);
String[] qq = getResources().getStringArray(R.array.Абылай);
String[] sr = new String[ss.length + qq.length];
System.arraycopy(ss, 0, sr, 0, ss.length);
System.arraycopy(qq, 0, sr, ss.length, qq.length);
ListView se = (ListView) rrrr.findViewById(R.id.listView2);
shuffleArray(sr);
List<Quotes> ser = new ArrayList<Quotes>();
for (int s = 0; s<sr.length; s++){
if(Arrays.asList(ss).contains(sr[s]) ){
Quotes quotes = new Quotes();
quotes.setText(sr[s]);
quotes.setIcon(R.drawable.abay);
ser.add(quotes);
} else if(Arrays.asList(qq).contains(sr[s])){
Quotes quotes = new Quotes();
quotes.setText(sr[s]);
quotes.setIcon(R.drawable.abylai);
ser.add(quotes);
}
}
AdapterQ ses = new AdapterQ(getActivity().getApplicationContext(), ser);
se.setAdapter(ses);
return rrrr;
}
Here:
AdapterQ ses = new AdapterQ(getActivity().getApplicationContext(), ser);
Try this:
AdapterQ ses = new AdapterQ(getActivity(), ser);
Hi I am trying to add view pager into my application. I have loaded all the details that I want into the view pager including Map (I am displaying it in some part). But the instantiateItem method is being called multiple times. Where did I make a mistake..help me. Below is my posted code.
public class ViewPagerAdapter extends PagerAdapter
{
Activity context;
List<ListDetails> products;
LayoutInflater inflater;
private String user_latitude;
private String user_longitude;
private double to_latitude;
private Location nwLocation;
AppLocationService appLocationService;
private double to_longitude;
private static View itemView;
private CopyOnWriteArrayList<ListDetails> ListItemsData;
private static GMapV2Direction gmapdirection;
private static GoogleMap gmap;
private JSONObject SaveOfferObj;
static final String ARG_POSITION = "position";
int mCurrentPosition = -1;
private TextView txt_offer;
private TextView txt_distance;
private TextView txt_shop;
private TextView txt_category;
private TextView txt_couponcode;
private RatingBar rat_user;
private TextView txt_enddate;
// private View alertLayout;
private static View alertLayout;
ListDetails product;
private HorizontalListView swipelisview;
private Repo repoObject;
ImageView viewdetails;
TableLayout tbldetails;
public ViewPagerAdapter(Context context, List<ListDetails> products, android.app.FragmentManager fragmentManager) {
this.context = (Activity) context;
this.products = products;
}
#Override
public int getCount() {
return products.size();
}
public ListDetails getItem(int position) {
return products.get(position);
}
/* public NotificationViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return _notificationViewPager.getCount();
}
#Override
public Fragment getItem(int position) {
return NotificationFragment.newInstance(_context, _notificationViewPager.getNotification(position), position, _notificationViewPager.getTotalNotifications());
} */
#Override
public int getItemPosition(Object object) {
int index = products.indexOf(object);
if(index >= 0){
return index;
}else{
return PagerAdapter.POSITION_NONE;
}
}
/*#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}*/
#Override
public boolean isViewFromObject(View view, Object object) {
if(object != null){
return ((FrameLayout)object) == view;
//return ((FrameLayout)object).getRootView() == view;
}else{
return false;
}
/*if(object != null){
return ((Fragment)object).getView() == view;
}else{
return false;
}*/
}
#SuppressLint("InflateParams")
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(itemView==null)
{
if(alertLayout==null)
alertLayout = li.inflate(R.layout.map_dialog,
null);
}
/*if (itemView != null) {
ViewGroup parentViewGroup = (ViewGroup) itemView.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeView(itemView);
//((ViewPager) container).removeView(itemView);
}
} */
try {
//if(itemView == null)
//{
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.single,container, false);
//}
} catch (InflateException e) {
}
try {
txt_offer = (TextView) itemView
.findViewById(R.id.Offer_edittext);
txt_distance = (TextView) itemView
.findViewById(R.id.distance_edittext);
/*TextView txt_area = (TextView) rootView
.findViewById(R.id.area_edittext);*/
txt_shop = (TextView) itemView
.findViewById(R.id.Shop_edittext);
tbldetails = (TableLayout) itemView.findViewById(R.id.tablevielw);
rat_user = (RatingBar) itemView.findViewById(R.id.user_ratingbar);
viewdetails = (ImageView) itemView.findViewById(R.id.btn_details);
viewdetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tbldetails.getVisibility()==View.GONE){
viewdetails.setBackgroundResource(R.drawable.collapse);
expand();
}else{
viewdetails.setBackgroundResource(R.drawable.expand);
collapse();
}
}
});
RatingBar rat_user = (RatingBar) itemView.findViewById(R.id.user_ratingbar);
//ImageView map = (ImageView) itemView.findViewById(R.id.btn_map);
swipelisview = (HorizontalListView) itemView.findViewById(R.id.gridview);
swipelisview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
appLocationService = new AppLocationService(context);
nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation == null) {
nwLocation = new Location("");
nwLocation.setLatitude(17.4165);
nwLocation.setLongitude(78.4382);
}
ListDetails mDetails = ListItemsData.get(position);
user_latitude = Double.toString(nwLocation.getLatitude());
user_longitude = Double.toString(nwLocation.getLongitude());
to_latitude =mDetails.getLat();
to_longitude = mDetails.getLng();
String AreaName = mDetails.getAreaName();
String ShopName = mDetails.getShopName();
String ShopID = mDetails.getShopID();
String OfferName = mDetails.getDeal();
float Distance = mDetails.getDistance();
String PromoCode = mDetails.getPromoCode();
String PostedDate = mDetails.getPostedDate();
String EndDate = mDetails.getOfferEndDate();
String Category = mDetails.getCategoryName();
String OfferId = mDetails.getOfferID();
TextView txt_offer = (TextView) itemView
.findViewById(R.id.Offer_edittext);
TextView txt_distance = (TextView) itemView
.findViewById(R.id.distance_edittext);
/*TextView txt_area = (TextView) rootView
.findViewById(R.id.area_edittext);*/
TextView txt_shop = (TextView) itemView
.findViewById(R.id.Shop_edittext);
RatingBar rat_user = (RatingBar) itemView.findViewById(R.id.user_ratingbar);
TextView txt_posteddate = (TextView) itemView
.findViewById(R.id.offerPosted_edittext);
TextView txt_enddate = (TextView) itemView
.findViewById(R.id.OfferEnd_edittext);
TextView txt_category = (TextView) itemView
.findViewById(R.id.category_edittext);
TextView txt_couponcode = (TextView) itemView
.findViewById(R.id.Coupon_edittext);
final ArrayList<String> ImageArrayList = new ArrayList<String>();
String ImageNameStr = mDetails.getImageName1();
final String[] ImageNameArr = ImageNameStr.split(",");
for (int i = 0; i < ImageNameArr.length; i++) {
ImageArrayList.add(ImageNameArr[i]);
}
ViewPager viewPager = (ViewPager) itemView
.findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(context,
ImageArrayList);
viewPager.setAdapter(adapter);
CirclePageIndicator mIndicator = (CirclePageIndicator) itemView.findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
txt_offer.setText(OfferName);
txt_distance.setText(Distance+" KM Away");
//txt_area.setText(AreaName);
txt_shop.setText(ShopName+" , "+ AreaName);
txt_couponcode.setText(PromoCode);
txt_category.setText(Category);
txt_posteddate.setText(PostedDate);
txt_enddate.setText(EndDate);
rat_user.setRating(3f);
LoadPlaceDetails();
}
});
Button btnrating = (Button) itemView.findViewById(R.id.btn_rating);
btnrating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
Rating_Listview mRating_Listview = new Rating_Listview();
Bundle PFBundel = new Bundle();
PFBundel.putString("Offer",product.getDeal());
PFBundel.putString("OfferID",product.getOfferID());
android.app.FragmentManager fragment = context.getFragmentManager();
mRating_Listview.setArguments(PFBundel);
fragment.beginTransaction()
.replace(R.id.frame_container, mRating_Listview)
.commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.Rating_Listview;
ModuleFragmentBackStackingClass.AddtoStack(
mRating_Listview,
EnumModuleTags.Rating_Listview,
"RightPlaceRightTime");
} catch (Exception e) {
Toast.makeText(context, e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
TextView txt_posteddate = (TextView) itemView
.findViewById(R.id.offerPosted_edittext);
txt_enddate = (TextView) itemView
.findViewById(R.id.OfferEnd_edittext);
txt_category = (TextView) itemView
.findViewById(R.id.category_edittext);
txt_couponcode = (TextView) itemView
.findViewById(R.id.Coupon_edittext);
product = (ListDetails) getItem(position);
final ArrayList<String> ImageArrayList = new ArrayList<String>();
String ImageNameStr = product.getImageName1();
final String[] ImageNameArr = ImageNameStr.split(",");
for (int i = 0; i < ImageNameArr.length; i++) {
ImageArrayList.add(ImageNameArr[i]);
}
ViewPager viewPager = (ViewPager) itemView
.findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(context,
ImageArrayList);
viewPager.setAdapter(adapter);
CirclePageIndicator mIndicator = (CirclePageIndicator) itemView.findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
appLocationService = new AppLocationService(context);
nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation == null) {
nwLocation = new Location("");
nwLocation.setLatitude(17.4165);
nwLocation.setLongitude(78.4382);
}
user_latitude = Double.toString(nwLocation.getLatitude());
user_longitude = Double.toString(nwLocation.getLongitude());
to_latitude = product.getLat();
to_longitude = product.getLng();
txt_offer.setText(product.getDeal());
txt_distance.setText(product.getDistance()+" KM Away");
//txt_area.setText(AreaName);
txt_shop.setText(product.getShopName()+" , "+ product.getAreaName());
txt_couponcode.setText(product.getPromoCode());
txt_category.setText(product.getCategoryName());
txt_posteddate.setText(product.getPostedDate());
txt_enddate.setText(product.getOfferEndDate());
rat_user.setRating(3f);
final FloatingActionsMenu fmenu = (FloatingActionsMenu) itemView.findViewById(R.id.multiple_actions);
final FloatingActionsMenu fmenu1 = (FloatingActionsMenu) itemView.findViewById(R.id.multiple_actions1);
fmenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fmenu1.collapse();
}
});
fmenu1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fmenu.collapse();
}
});
//}
((ViewPager) container).addView(itemView , 0);
//return itemView;
} catch (Exception e) {
PostLogcatErorrs(e);
}
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((FrameLayout) object);
/* android.app.FragmentTransaction ft=fm.beginTransaction();
ft.remove((Fragment) object);
ft.commit(); */
Fragment f = context.getFragmentManager().findFragmentById(R.id.map);
if (f != null)
context.getFragmentManager().beginTransaction().remove(f).commit();
}
private void LoadPlaceDetails() {
try {
// TODO Auto-generated method stub
// Your code goes here
final LatLng fromPosition = new LatLng(
Double.parseDouble(user_latitude),
Double.parseDouble(user_longitude));
final LatLng toPosition = new LatLng(to_latitude,
to_longitude);
gmapdirection = new GMapV2Direction();
FragmentManager fm = ((FragmentActivity) context)
.getSupportFragmentManager();
gmap = ((SupportMapFragment) fm.findFragmentById(R.id.map)).getMap();
gmap.clear();
LatLng coordinates = new LatLng(
(Double.parseDouble(user_latitude) + to_latitude) / 2,
(Double.parseDouble(user_longitude) + to_latitude) / 2);
gmap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
gmap.addMarker(new MarkerOptions()
.position(fromPosition)
.title("Current Location")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
gmap.addMarker(new MarkerOptions()
.position(toPosition)
.title("")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
Document doc = gmapdirection.getDocument(fromPosition, toPosition,
GMapV2Direction.MODE_DRIVING, context);
} catch (NumberFormatException e) {
PostLogcatErorrs(e);
}
}
public static void Newe(Document doc) {
// TODO Auto-generated method stub
ArrayList<LatLng> directionPoint = gmapdirection.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
gmap.addPolyline(rectLine);
}
private void GetOfferShopList() {
try {
if(SplashScreen.isOnline)
{
final Location CurrentLocation = new Location("point A");
CurrentLocation.setLatitude(Double.parseDouble(user_latitude));
CurrentLocation.setLongitude(Double.parseDouble(user_longitude));
ListItemsData = new CopyOnWriteArrayList<ListDetails>();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(LoadActivity.BaseUri + "GetAllOffer?type="+product.getCategoryName(),
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
JSONArray GetMG_AppointmentRequestResult = null;
try {
GetMG_AppointmentRequestResult = response.getJSONArray("GetAllOfferResult");
} catch (JSONException e1) {
Toast.makeText(context,
e1.getMessage(), Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
// Parsing json
for (int i = 0; i < GetMG_AppointmentRequestResult.length(); i++) {
try {
JSONObject obj = GetMG_AppointmentRequestResult.getJSONObject(i);
ListDetails ListModelObj = new ListDetails();
Location RetailerLocation = new Location("point B");
RetailerLocation.setLatitude(Double.parseDouble(obj
.getString("Lat")));
RetailerLocation.setLongitude(Double.parseDouble(obj
.getString("Lng")));
float distance = CurrentLocation.distanceTo(RetailerLocation)/1000;
float val = (float)Math.round(distance * 10) / 10;
ListModelObj.setDistance(val);
ListModelObj.setPosition_id(Integer.parseInt(obj.getString("ShopRegID")));
ListModelObj.setShopName(obj.getString("ShopName"));
ListModelObj.setDescription(obj.getString("OfferName"));
ListModelObj.setLat(Double.parseDouble(obj.getString("Lat")));
ListModelObj.setLng(Double.parseDouble(obj.getString("Lng")));
ListModelObj.setDeal(obj.getString("Deal"));
ListModelObj.setPromoCode(obj.getString("PromoCode"));
ListModelObj.setAreaName(obj.getString("AreaName"));
ListModelObj.setOfferStatus(obj.getString("OfferStatus"));
ListModelObj.setCategoryName(obj.getString("CategoryType"));
ListModelObj.setPostedDate(obj
.getString("OfferStartDate"));
ListModelObj.setOfferEndTime(obj
.getString("OfferEndTime"));
ListModelObj.setOfferEndDate(obj
.getString("OfferEndDate"));
ListModelObj.setOfferID(obj
.getString("OfferID"));
ListModelObj.setImageName1(obj.getString("ImageName"));
//ListModelObj.setImageName2(obj.getString("ImageName2"));
//ListModelObj.setImageName3(obj.getString("ImageName3"));
String abc = obj.getString("ImageName");
String[] xyz = abc.split(",");
ListModelObj.setListImage(LoadActivity.BaseUriImg
+ xyz[0]);
ListItemsData.add(ListModelObj);
/*offertable Offers = null;
Repo repoObject = LoadActivity.getRepo();
Offers = new offertable();
Offers.setOfferID(Integer.parseInt(obj.getString("OfferID")));
Offers.setShopRegID(Integer.parseInt(obj.getString("ShopRegID")));
Offers.setShopName(obj.getString("ShopName"));
Offers.setTime(obj.getString("Time"));
Offers.setCreatedDate(obj.getString("CreatedDate"));
Offers.setModifyDate(obj.getString("ModifyDate"));
Offers.setOfferStartDate(obj.getString("OfferStartDate"));
Offers.setOfferEndDate(obj.getString("OfferEndDate"));
Offers.setOfferStartTime(obj.getString("OfferStartTime"));
Offers.setOfferEndTime(obj.getString("OfferEndTime"));
Offers.setDeal(obj.getString("Deal"));
Offers.setDescription(obj.getString("Description"));
Offers.setPromoCode(obj.getString("PromoCode"));
Offers.setImageName(obj.getString("ImageName"));
Offers.setOfferStatus(Integer.parseInt(obj.getString("OfferStatus")));
Offers.setRowStatus("A");
Offers.setAreaName(obj.getString("AreaName"));
Offers.setLat(obj.getString("Lat"));
Offers.setLng(obj.getString("Lng"));
Offers.setCategoryType(obj.getString("CategoryType"));
Offers.setDistance(String.valueOf(val));
//Offers.setTimeTaking(distance1);
repoObject.roffertable.save(Offers);*/
} catch (JSONException e) {
Toast.makeText(context,
e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
CustomGridAdapter customAdapter =new CustomGridAdapter(context,ListItemsData);
swipelisview.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
else {
repoObject = LoadActivity.getRepo();
List<offertable> alloffers = repoObject.roffertable.getAlloffersByFilter(product.getCategoryName());
ListItemsData = new CopyOnWriteArrayList<ListDetails>();
if (alloffers != null) {
for (offertable s : alloffers) {
final ListDetails ListModelObj = new ListDetails();
ListModelObj.setTime(s.getTimeTaking());
ListModelObj.setDistance(Float.parseFloat(s.getDistance()));
ListModelObj.setPosition_id(s.getShopRegID());
ListModelObj.setShopName(s.getShopName());
ListModelObj.setDescription(s.getDescription());
ListModelObj.setLat(Double.parseDouble(s.getLat()));
ListModelObj.setLng(Double.parseDouble(s.getLng()));
ListModelObj.setDeal(s.getDeal());
ListModelObj.setPromoCode(s.getPromoCode());
ListModelObj.setAreaName(s.getAreaName());
ListModelObj.setPostedDate(s.getOfferStartDate());
ListModelObj.setOfferEndTime(s.getOfferEndTime());
ListModelObj.setOfferEndDate(s.getOfferEndDate());
ListModelObj.setShopID(String.valueOf(s.getShopRegID()));
ListModelObj.setOfferStatus(String.valueOf(s.getOfferStatus()));
ListModelObj.setCategoryName(s.getCategoryType());
ListModelObj.setOfferID(String.valueOf(s.getOfferID()));
ListModelObj.setImageName1(s.getImageName());
String abc = s.getImageName();
String[] xyz = abc.split(",");
ListModelObj
.setListImage(LoadActivity.BaseUriImg + xyz[0]);
ListItemsData.add(ListModelObj);
}
CustomGridAdapter customAdapter =new CustomGridAdapter(context,ListItemsData);
swipelisview.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
//progresdialog.dismiss();
}
}
} catch (Exception e1) {
Toast.makeText(context,
e1.getMessage(), Toast.LENGTH_LONG).show();
e1.printStackTrace();
//java.lang.NullPointerException: Attempt to invoke virtual method
//'void customlistviewvolley.AppController.addToRequestQueue(com.android.volley.Request)'
//on a null object reference
}
}
}
What does your layout code look like?
I had a similar issue when I was instantiating the Fragment in the layout and then also in the onCreate() method