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
Related
For example, I need to judge the contents of the item in the Item can be clicked.
enter image description here
As shown in the picture, I need to get the gray Item cannot be clicked.
Here is my adapter
public class RoomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context mContext;
private List<Room> mDatas;
public RoomAdapter(Context context, List<Room> mDatas) {
mInflater = LayoutInflater.from(context);
this.mContext = context;
this.mDatas = mDatas;
}
#Override
public int getCount() {
return mDatas.size();
}
#Override
public Object getItem(int position) {
return mDatas.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Room room = mDatas.get(position);
ViewHolder viewHolder = null;
View view;
if (convertView == null) {
viewHolder = new ViewHolder();
view = mInflater.inflate(R.layout.roomstate_item, null);
viewHolder.tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
viewHolder.tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
viewHolder.tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
viewHolder.tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
view.setTag(viewHolder);
}else{
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
// String nu = room.getRoom_number();
viewHolder.tv_roomstate.setText(room.getRoom_status());
viewHolder.tv_roomnumber.setText(room.getRoom_number());
viewHolder.tv_roomtype.setText(room.getRoomType().getRoom_type_name());
viewHolder.tv_roomprice.setText(room.getRoomType().getRoom_type_price());
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setClickable(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setClickable(false);
view.setBackgroundResource(R.drawable.doubleg);
}
return view;
}
private class ViewHolder {
TextView tv_roomnumber;
TextView tv_roomstate;
TextView tv_roomtype;
TextView tv_roomprice;
}
}
Here is my Activity
public class RoomList extends Activity {
private ImageView iv_back;
private TextView tv_hotelname;
private GridView griv_hotel;
private RoomAdapter adapter;
private String hotelname;
private String url
= "http://jm/user/room/selectRoomByHotelName?hotel_name=";
private List<Room> mRoom;
private RoomType mRoomType;
private boolean isfinish = false;//判断请求是否完成
private String hotel_address;
private String hotel_id;
private Bundle mBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_room_list);
init();
sendRequestWithOkHttp();
boolean is = true;
while (is) {
if (isfinish) {
adapter = new RoomAdapter(this, mRoom);
griv_hotel.setAdapter(adapter);
griv_hotel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv_roomnumber = (TextView) view.findViewById(R.id.tv_roomnumber);
TextView tv_roomstate = (TextView) view.findViewById(R.id.tv_roomstate);
TextView tv_roomprice = (TextView) view.findViewById(R.id.tv_roomprice);
TextView tv_roomtype = (TextView) view.findViewById(R.id.tv_roomtype);
String roomnumber = tv_roomnumber.getText().toString();
String roomstate = tv_roomstate.getText().toString();
String roomtype = tv_roomtype.getText().toString();
String roomprice = tv_roomprice.getText().toString();
Log.e("房间类型",roomtype);
// if (roomstate.equals("0") && roomtype.equals("0")) {
// view.setClickable(false);
// } else if (roomstate.equals("1") && roomtype.equals("0")) {
// view.setClickable(true);
// } else if (roomstate.equals("1") && roomtype.equals("1")) {
// view.setClickable(true);
// } else {
// view.setClickable(false);
// }
mBundle.putString("roomnumber", roomnumber);
mBundle.putString("roomstate", roomstate);
mBundle.putString("roomtype", roomtype);
mBundle.putString("roomprice", roomprice);
mBundle.putString("hoteladdress", hotel_address);
mBundle.putString("hotelid", hotel_id);
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
});
is = false;
}
}
}
private void init() {
initView();
initEvents();
}
private void initEvents() {
iv_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void initView() {
iv_back = (ImageView) findViewById(R.id.iv_back);
tv_hotelname = (TextView) findViewById(R.id.tv_hotelname);
mBundle = getIntent().getExtras();
hotelname = mBundle.getString("hotelname");
tv_hotelname.setText(hotelname);
griv_hotel = (GridView) findViewById(R.id.griv_hotel);
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
#Override
public void run() {
MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
try {
OkHttpClient client = new OkHttpClient();
String postBody = hotelname;
Request request = new Request.Builder()
.url(url + hotelname)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
try {
parseJSON(responseData);
isfinish = true;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSON(String responseData) throws JSONException {
JSONArray JSONArray = new JSONArray(responseData);
mRoom = new ArrayList<Room>();
for (int i = 0; i < JSONArray.length(); i++) {
try {
JSONObject JSON = JSONArray.getJSONObject(i);
String room_number = JSON.getString("room_number");
String room_status = JSON.getString("room_status");
JSONObject jsonObject = JSON.getJSONObject("roomType");
String room_type_name = jsonObject.getString("room_type_name");
String room_type_price = jsonObject.getString("room_type_price");
JSONObject jsonObj = JSON.getJSONObject("hotel");
hotel_id = String.valueOf(jsonObj.getInt("hotel_id"));
hotel_address = jsonObj.getString("hotel_location");
mRoomType = new RoomType(null, room_type_name, room_type_price, null, null);
mRoom.add(new Room(null, room_number, room_status, null, null, mRoomType));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I set view.setClickable (false)in my Adapter, but it does not work.
item.setEnabled(false);
when u need to make it clickable call
item.setEnabled(true);
Here item is your edittext or button or anything else
Try this:
if (room.getRoom_status().equals("0") &&room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single);
view.setEnabled(false);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("0")) {
view.setBackgroundResource(R.drawable.single_b);
} else if (room.getRoom_status().equals("1") && room.getRoomType().getRoom_type_name().equals("1")) {
view.setBackgroundResource(R.drawable.double_b);
} else if(room.getRoom_status().equals("0") && room.getRoomType().getRoom_type_name().equals("1")){
view.setEnabled(false);
view.setBackgroundResource(R.drawable.doubleg);
}
else
view.setEnabled(true);
The right way is to write a Boolean value, and let it based on a Boolean value to determine whether to jump.
private boolean checkedIntent = false;
if (roomstate.equals("0") && roomtype.equals("0")) {
checkedIntent = false;
} else if (roomstate.equals("1") && roomtype.equals("0")) {
checkedIntent = true;
} else if (roomstate.equals("1") && roomtype.equals("1")) {
checkedIntent = true;
} else if (roomstate.equals("0") && roomtype.equals("1")) {
checkedIntent = false;
}
if (checkedIntent == true) {
Intent intent = new Intent(RoomList.this, BookRoomDetail.class);
intent.putExtras(mBundle);
startActivity(intent);
}
I'm trying to build a pager to display images, sequentially. But I am getting this error.
The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged!
Expected adapter item count: 0, found: 1 Pager id:.
Please someone guide to fix it.
This is my code:
MatChedUserProfile Activity
public class MatChedUserProfile extends Activity implements OnClickListener {
private static final String TAG = "MatChedUserProfile";
private static boolean mDebugLog = true;
private static String mDebugTag = "MatChedUserProfile";
private ExtendedGallery imageExtendedGallery;
private LinearLayout image_count;
private TextView usernametextivew, ueragetextviw, distancetextview,
activetimetextview, abouttextview, abouttextviewvalues,
viewMatchedProfiletextview, statusTextView;
private RelativeLayout Aboutuseragelayout, likedislikebuttonlayout;
private Button likeButton, dislikebutton;
private ArrayList<GellaryData> imageList;
//private ImageAdapterForGellary mAdapterForGellary;
private ProgressDialog mDialog;
private int[] imageHeightandWIdth;
private ConnectionDetector cd;
private RelativeLayout.LayoutParams layoutParams;
private int count;
private TextView[] page_text;
private SharedPreferences preferences;
//new viewpager....
private ViewPager viewPager;
private MyViewPagerAdapter mAdapterForGellary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matcheduserprofile);
//Thread.setDefaultUncaughtExceptionHandler(new CrashLogger(getApplicationContext()));
cd = new ConnectionDetector(this);
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
preferences = PreferenceManager.getDefaultSharedPreferences(this);
initLayoutResource();
imageList = new ArrayList<GellaryData>();
//listOfItems=new ArrayList<GellaryData>();
mAdapterForGellary = new MyViewPagerAdapter(imageList);
//imageExtendedGallery.setAdapter(mAdapterForGellary);
viewPager.setAdapter(mAdapterForGellary);
Ultilities ultilities = new Ultilities();
imageHeightandWIdth = ultilities
.getImageHeightAndWidthForProfileGellary(this);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.getBoolean(Constant.isFromChatScreen)) {
likedislikebuttonlayout.setVisibility(View.GONE);
} else {
}
}
Settings.addLoggingBehavior(LoggingBehaviors.INCLUDE_ACCESS_TOKENS);
try {
likeButton.setOnClickListener(this);
dislikebutton.setOnClickListener(this);
} catch (Exception e) {
}
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
imageHeightandWIdth[1], imageHeightandWIdth[0]);
rlp.addRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams = ultilities.getRelativelayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams.setMargins(0, 5, 0, 0);
layoutParams = ultilities.getRelativelayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams.setMargins(0, 5, 0, 0);
cd = new ConnectionDetector(getApplicationContext());
if (cd.isConnectingToInternet()) {
getUserProfile();
// getUserShareeInterest();
} else {
AlertDialogManager
.internetConnetionErrorAlertDialog(MatChedUserProfile.this);
}
//myViewPagerAdapter = new MyViewPagerAdapter(imageList);
viewPager.setAdapter(mAdapterForGellary);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(viewPagerPageChangeListener);
/* imageExtendedGallery
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
for (int i = 0; i < count; i++) {
page_text[i]
.setTextColor(android.graphics.Color.GRAY);
}
page_text[pos]
.setTextColor(android.graphics.Color.LTGRAY);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});*/
}
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i = 0; i < count; i++) {
page_text[i]
.setTextColor(android.graphics.Color.GRAY);
}
page_text[position]
.setTextColor(android.graphics.Color.LTGRAY);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void initLayoutResource() {
viewMatchedProfiletextview = (TextView) findViewById(R.id.viewMatchedProfiletextview);
likeButton = (Button) findViewById(R.id.likeButton);
dislikebutton = (Button) findViewById(R.id.dislikebutton);
//imageExtendedGallery = (ExtendedGallery) findViewById(R.id.imageExtendedGallery);
viewPager = (ViewPager)findViewById(R.id.viewPager);
image_count = (LinearLayout) findViewById(R.id.image_count);
usernametextivew = (TextView) findViewById(R.id.usernametextivew);
ueragetextviw = (TextView) findViewById(R.id.ueragetextviw);
distancetextview = (TextView) findViewById(R.id.distancetextview);
activetimetextview = (TextView) findViewById(R.id.activetimetextview);
statusTextView = (TextView) findViewById(R.id.txtMatchedUserStatus);
// userfriendgallery = (HorizontalListView)
// findViewById(R.id.userfriendgallery);
// userIntestedgallery = (HorizontalListView)
// findViewById(R.id.userIntestedgallery);
abouttextview = (TextView) findViewById(R.id.abouttextview);
Aboutuseragelayout = (RelativeLayout) findViewById(R.id.Aboutuseragelayout);
Aboutuseragelayout.setVisibility(View.GONE);
likedislikebuttonlayout = (RelativeLayout) findViewById(R.id.likedislikebuttonlayout);
abouttextviewvalues = (TextView) findViewById(R.id.abouttextviewvalues);
Typeface HelveticaInseratLTStd_Roman = Typeface.createFromAsset(
getAssets(), "fonts/HelveticaInseratLTStd-Roman.otf");
Typeface HelveticaLTStd_Light = Typeface.createFromAsset(getAssets(),
"fonts/HelveticaLTStd-Light.otf");
viewMatchedProfiletextview.setTypeface(HelveticaLTStd_Light);
viewMatchedProfiletextview.setTextColor(Color.rgb(255, 255, 255));
viewMatchedProfiletextview.setTextSize(20);
usernametextivew.setTypeface(HelveticaInseratLTStd_Roman);
usernametextivew.setTextColor(Color.rgb(124, 124, 124));
((TextView) findViewById(R.id.txtst))
.setTypeface(HelveticaInseratLTStd_Roman);
((TextView) findViewById(R.id.txtst)).setTextColor(Color.rgb(124, 124,
124));
statusTextView.setTypeface(HelveticaInseratLTStd_Roman);
statusTextView.setTextColor(Color.rgb(124, 124, 124));
// usernametextivew.setTextSize(20);
ueragetextviw.setTypeface(HelveticaLTStd_Light);
ueragetextviw.setTextColor(Color.rgb(124, 124, 124));
abouttextview.setTypeface(HelveticaInseratLTStd_Roman);
abouttextview.setTextColor(Color.rgb(92, 92, 92));
abouttextview.setTextSize(15);
abouttextviewvalues.setTypeface(HelveticaInseratLTStd_Roman);
abouttextviewvalues.setTextColor(Color.rgb(131, 131, 131));
abouttextviewvalues.setTextSize(15);
distancetextview.setTypeface(HelveticaInseratLTStd_Roman);
distancetextview.setTextColor(Color.rgb(92, 92, 92));
distancetextview.setTextSize(15);
activetimetextview.setTypeface(HelveticaInseratLTStd_Roman);
activetimetextview.setTextColor(Color.rgb(131, 131, 131));
activetimetextview.setTextSize(15);
}
private void getUserProfile() {
SessionManager mSessionManager = new SessionManager(this);
String macheduserFacebookid = mSessionManager
.getMatchedUserFacebookId();
AppLog.Log(TAG, "Matched UserFacebook ID:" + macheduserFacebookid);
// String userSessionToken = mSessionManager.getUserToken();
String userDeviceId = Ultilities.getDeviceId(this);
if (macheduserFacebookid != null && macheduserFacebookid.length() > 0) {
// String[] params = { userSessionToken, userDeviceId,
// macheduserFacebookid };
String[] params = { macheduserFacebookid };
new BackGroundTaskForUserProfile().execute(params);
} else {
ErrorMessageMandetoryFiledMissing(
getResources().getString(R.string.alert), getResources()
.getString(R.string.retriedmessage));
}
}
private class BackGroundTaskForUserProfile extends
AsyncTask<String, Void, Void> {
Ultilities mUltilities = new Ultilities();
private String getProfileResponse;
private List<NameValuePair> userProfileNameValuePairList;
private userProFileData mUserProFileData;
private GellaryData mGellaryData;
#Override
protected Void doInBackground(String... params) {
try {
userProfileNameValuePairList = mUltilities
.getUserProfileParameter(params);
getProfileResponse = mUltilities.makeHttpRequest(
Constant.getProfile_url, Constant.methodeName,
userProfileNameValuePairList);
// logDebug("BackGroundTaskForUserProfile getProfileResponse "+getProfileResponse);
Gson gson = new Gson();
mUserProFileData = gson.fromJson(getProfileResponse,
userProFileData.class);
String[] images = mUserProFileData.getImages();
for (int i = 0; i < images.length; i++) {
mGellaryData = new GellaryData();
mGellaryData.setImageUrl(images[i]);
imageList.add(mGellaryData);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mDialog != null) {
mDialog.dismiss();
}
page_text = new TextView[imageList.size()];
count = imageList.size();
image_count.removeAllViews();
for (int i = 0; i < imageList.size(); i++) {
page_text[i] = new TextView(MatChedUserProfile.this);
page_text[i].setText(".");
page_text[i].setTextSize(45);
page_text[i].setTypeface(null, Typeface.BOLD);
page_text[i]
.setTextColor(android.graphics.Color.GRAY);
image_count.addView(page_text[i]);
}
//Log.d("shanImage", Array.toString(mUserProFileData.getImages()));
mAdapterForGellary.notifyDataSetChanged();
if (mUserProFileData.getStatus() != null
&& !mUserProFileData.getStatus().equals("")) {
statusTextView
.setText(mUserProFileData.getStatus());
} else {
statusTextView.setText("N/A");
}
ueragetextviw.setText("" + mUserProFileData.getAge());
usernametextivew.setText(""
+ mUserProFileData.getFirstName());
viewMatchedProfiletextview.setText(""
+ mUserProFileData.getFirstName());
SessionManager sessionManager = new SessionManager(
MatChedUserProfile.this);
String DistanceUinit = null;
if (sessionManager.getDistaceUnit().equals("Km")) {
DistanceUinit = "Km.";
} else {
DistanceUinit = "Mi.";
}
distancetextview.setText("Less than "
+ mUserProFileData.getDistance() + " "
+ DistanceUinit + " away");
String gmtTime = mUserProFileData.getLastActive();
// gmtTime=gmtTime.replaceAll("-", " ");
String localTime = UltilitiesDate.getLocalTime(gmtTime);
Ultilities ultilities = new Ultilities();
// String
// curentTime=ultilities.getCurrentDateYYYYMMdd();
String dataString = UltilitiesDate
.datesString(localTime);
UltilitiesDate ultilitiesDate = new UltilitiesDate();
int days = ultilitiesDate.getDays();
int hours = ultilitiesDate.getHours();
activetimetextview.setText("active " + days + " -d "
+ hours + "- Hour ago");
if (mUserProFileData.getPersDesc() != null
&& mUserProFileData.getPersDesc().length() > 0) {
Aboutuseragelayout.setVisibility(View.VISIBLE);
abouttextview.setText("About " + ""
+ mUserProFileData.getFirstName());
abouttextviewvalues.setText(""
+ mUserProFileData.getPersDesc());
} else {
Aboutuseragelayout.setVisibility(View.GONE);
}
}
});
} catch (Exception e) {
AppLog.Log(TAG,
"BackGroundTaskForUserProfile doInBackground Exception"
+ e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
if (mDialog != null) {
mDialog.dismiss();
}
} catch (Exception e) {
AppLog.Log(TAG,
"BackGroundTaskForUserProfile onPostExecute Exception "
+ e);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = mUltilities.GetProcessDialog(MatChedUserProfile.this);
mDialog.setMessage("Please Wait..");
mDialog.setCancelable(false);
mDialog.show();
}
}
ImageAdapterForGellary Adapter
private class ImageAdapterForGellary extends PagerAdapter {
Activity mActivity;
private LayoutInflater mInflater;
private Ultilities mUltilities = new Ultilities();
private int[] imageheightandWidth = mUltilities
.getImageHeightAndWidthForGellary(MatChedUserProfile.this);
public ImageAdapterForGellary(
List<GellaryData> objects) {
//mActivity = context;
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public GellaryData getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleritem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
// holder.mProgressBar = (ProgressBar) convertView
// .findViewById(R.id.pbGalleryItemImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.mProgressBar.setId(position);
holder.imageview.setId(position);
Picasso.with(MatChedUserProfile.this) //
.load(getItem(position).getImageUrl()) //
.error(R.drawable.error) //
.resize(imageHeightandWIdth[1], imageHeightandWIdth[0]) //
.into(holder.imageview);
return convertView;
}
class ViewHolder {
ImageView imageview;
// ProgressBar mProgressBar;
}
}
MyViewPagerAdapter Adapter
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
//private ArrayList<Integer> items;
private List<GellaryData> items;
public MyViewPagerAdapter(List<GellaryData> objects) {
this.items = objects;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.galleritem, container,false);
ImageView galleimageview = (ImageView) view
.findViewById(R.id.thumbImage);
Picasso.with(MatChedUserProfile.this) //
.load(imageList.get(position).getImageUrl()) //
.error(R.drawable.error) //
.resize(imageHeightandWIdth[1], imageHeightandWIdth[0]) //
.into(galleimageview);
((ViewPager) container).addView(view);
return view;
}
#Override
public int getCount() {
return items.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View)obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View)object;
((ViewPager) container).removeView(view);
}
}
#Override
public void onStart() {
super.onStart();
// Session.getActiveSession().addCallback(statusCallback);
// FlurryAgent.onStartSession(this, Constant.flurryKey);
}
#Override
public void onStop() {
super.onStop();
// Session.getActiveSession().removeCallback(statusCallback);
// FlurryAgent.onEndSession(this);
}
}
And this is my error:
FATAL EXCEPTION: main
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 1 Pager id: com.crushmatic.pro:id/viewPager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.fresh.slidingmenu.MatChedUserProfile$MyViewPagerAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:1000)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
at android.view.View.measure(View.java:16677)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16677)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16677)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16677)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5286)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16677)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1927)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1119)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1301)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1006)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5652)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
for (int i = 0; i < images.length; i++) {
mGellaryData = new GellaryData();
mGellaryData.setImageUrl(images[i]);
imageList.add(mGellaryData);
}
this is what is causing the crash you can't add multiple objects to an array that is attached to an adapter inside a for loop
move this
mAdapterForGellary = new MyViewPagerAdapter(imageList);
//imageExtendedGallery.setAdapter(mAdapterForGellary);
viewPager.setAdapter(mAdapterForGellary);
to on post execute of the task
add this to your pager adapter
// Trying to add data dynamically
public void addData(#NonNull List<Object> data) {
mData.addAll(data);
notifyDataSetChanged();
}
after that in your main method
MyAdapter myAdapter = new MyAdapter(getContext());
myViewPager.setAdapter(myAdapter);
myViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
myViewPager.setPageTransformer(false, new UltraDepthScaleTransformer());
// Runs after data loaded from server (in the future):
myAdapter.addData(myData)
i hope this helps.
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 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?