The application's PagerAdapter changed the adapter's contents - android

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.

Related

How to update the value of the textview inside the fragment on the click of the button present in the adapter class in android?

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.

listview hide on orientation change android

I am using custom list view inside fragment(From Api). on orientation change data is still in array list and also list view get notified but it hides when screen rotates.
here is the code:
public class FragNotice extends Fragment implements View.OnClickListener {
ListAdapter listAdapter;
ListView listView;
EditText editTextNotice;
private Button btnSearch;
private Button btnClear;
private int incre = 1;
private boolean boolScroll = true;
public FragNotice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
setRetainInstance(true);
search(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return init(inflater.inflate(R.layout.notice_activity, container, false));
}
private View init(View view) {
editTextNotice = (EditText) view.findViewById(R.id.editTextNotice);
btnSearch = (Button) view.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
btnClear = (Button) view.findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
listView = (ListView) view.findViewById(R.id.listViewNotice);
listView.setOnScrollListener(onScrollListener());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), new ArrayList<ListRowItem>());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
AsyncRequest.OnAsyncRequestComplete onAsyncRequestComplete = new AsyncRequest
.OnAsyncRequestComplete() {
#Override
public void asyncResponse(String response, int apiKey) {
switch (apiKey) {
case 1:
listView(response);
break;
}
}
};
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnClear) {
incre = 1;
boolScroll = true;
editTextNotice.setText(null);
if (listAdapter != null)
listAdapter.clear();
search(true);
} else if (v.getId() == R.id.btnSearch) {
String std = editTextNotice.getText().toString();
if (std.trim().length() > 1) {
incre = 1;
boolScroll = true;
if (listAdapter != null)
listAdapter.clear();
try {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(new View(getActivity()).getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
// TODO: handle exception
}
search(false);
} else
Toast.makeText(getActivity(),
"Please enter atleast two character.", Toast.LENGTH_LONG)
.show();
}
}
class ListAdapter extends ArrayAdapter<ListRowItem> {
private final Context context;
public ListAdapter(Context asyncTask, java.util.List<ListRowItem> items) {
super(asyncTask, R.layout.notice_listitem, items);
this.context = asyncTask;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final ListRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notice_listitem, parent, false);
holder = new ViewHolder();
holder.txtSno = (TextView) convertView.findViewById(R.id.txtSno);
holder.txtNoticePublishDate = (TextView) convertView.findViewById(R.id
.txtNoticePublishDate);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.txtNoticeDescription = (TextView) convertView.findViewById(R.id
.txtNoticeDescription);
holder.txtNoticeName = (TextView) convertView.findViewById(R.id.txtNoticeName);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtSno.setText(String.valueOf(position + 1));
holder.txtNoticeDescription.setText(new AppUtility().TitleCase(rowItem.getDescription
()));
holder.txtNoticeName.setText(new AppUtility().TitleCase(rowItem.getFileTitle()));
try {
holder.txtNoticePublishDate.setText(String.valueOf((new SimpleDateFormat("dd MMM " +
"yyyy HH:mm:ss", Locale.US)).format((new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss", Locale.US)).parse(rowItem.getUpdateDate()))));
} catch (ParseException e) {
holder.txtNoticePublishDate.setText(new AppUtility().TitleCase(rowItem
.getUpdateDate()));
}
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return convertView;
}
/*private view holder class*/
private class ViewHolder {
TextView txtSno;
TextView txtNoticeName;
TextView txtNoticeDescription;
TextView txtNoticePublishDate;
Button btnView;
}
}
class ListRowItem {
private final String FileTitle;
private final String Description;
private final String ContentType;
private final int DocumentUploadID;
private final String UpdateDate;
ListRowItem() {
this.FileTitle = "";
this.Description = "";
this.ContentType = "";
this.DocumentUploadID = 0;
this.UpdateDate = "";
}
ListRowItem(String fileTitle, String description, String contentType, int
documentUploadID, String updateDate) {
this.FileTitle = fileTitle;
this.Description = description;
this.ContentType = contentType;
this.DocumentUploadID = documentUploadID;
this.UpdateDate = updateDate;
}
public String getFileTitle() {
return FileTitle;
}
public int getDocumentUploadID() {
return DocumentUploadID;
}
public String getUpdateDate() {
return UpdateDate;
}
public String getDescription() {
return Description;
}
public String getContentType() {
return ContentType;
}
}
private void listView(String response) {
try {
ArrayList<ListRowItem> lstItem;
if(listAdapter==null){
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
listAdapter = new ListAdapter(getActivity(), lstItem);
} else {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
listAdapter.addAll(lstItem);
} else {
for (ListRowItem items : lstItem) {
listAdapter.add(items);
}
}
}
if (listAdapter != null)
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 5;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold) {
if (boolScroll) {
if (editTextNotice.getText().toString().trim().length() > 0)
search(false);
else
search(true);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
private void search(boolean bool) {
String URL;
if (bool) {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/0/" + incre;
incre = incre + 1;
} else {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/" +
editTextNotice.getText().toString().trim() + "/" + incre;
incre = incre + 1;
}
AsyncRequest asyncRequest;
if (incre > 2)
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
null, 1);
else
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
"Fetching data", 1);
asyncRequest.execute(URL);
}
}
You need to load the data into the ListView again. You are binding the ListView to an adapter, you need to do it in onConfigurationChanged() method.
When orientation changes the activity reloads again.So you have to override onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Your Code Here
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Your Code Here
}
}
create a directory layout-land in the resources copy the your .xml file there align and set the Edittext and Button according to landscape layout .may be it solved your problem if the listview doest not get enough space to show in landscape layout
In onViewCreated(View view, Bundle savedInstanceState) method above you are setting new empty arraylist every time. So the previous items which are loaded are removed from adapter even though it is retained by setRetainInstance(true)
So you should have a Field that holds the arraylist and pass that field to adapter
private ArrayList<ListRowItem> listItems = new ArrayList<>()
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), listItems);//pass the Arraylist here
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
Then in private void listView(String response) method, add items to that listview created above as
listItems = new Gson().fromJson(response, listType);
listAdapter.notifyDataSetChanged();

How to refresh fragment from out of activity or fragment but from baseAdapter class

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

ViewPager InstatiateItem method is calling multiple times

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

Updating list in listfragment with costom adapter

I'm using onScroll onclicklistner to update listview in my listFragment.
public class WishboardFragment extends ListFragment implements OnScrollListener{
private ProgressBar progressBar2;
private TextView finished;
private Context context = null;
private ListAdapter wishAdapter = null;
private final String TAG = "wishboard";
private final String cachedName = "wishboard";
JSONObject jsonObject = null;
JSONArray jsonArray = null;
private Menu optionsMenu;
private Integer pageStart = 1;
private Integer pageEnd = 15;
private Boolean isDownloading = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.context = getActivity();
return inflater.inflate(R.layout.activity_dashboard,container,false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
String url = getWishboardUrl();
sendRequest(url);
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
wishAdapter = new WishRowAdaptor(getActivity(),this.getWishboardCached());
setListAdapter(wishAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
this.optionsMenu = menu;
inflater.inflate(R.menu.dashboard, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
getListView().setOnScrollListener(this);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.btn_refresh:
Common.setRefreshActionButtonState(true,optionsMenu);
String url = getWishboardUrl();
sendRequest(url);
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendRequest(String url) {
new SendRequest().execute(url);
}
private class SendRequest extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... requestURL) {
String data = "";
HttpURLConnection httpUrlConnection = null;
try {
URL url = new URL(requestURL[0]);
URLConnection connection = url.openConnection();
connection.setUseCaches(true);
Object response = connection.getContent();
Log.i(TAG, "Requesting http "+requestURL[0]);
if (response instanceof Bitmap) {
}
InputStream in = new BufferedInputStream(
connection.getInputStream());
data = Common.readStream(in);
} catch (MalformedURLException exception) {
Log.e(TAG, "MalformedURLException");
} catch (IOException exception) {
Log.e(TAG, "IOException");
} finally {
if (null != httpUrlConnection)
httpUrlConnection.disconnect();
}
return data;
}
protected void onPostExecute(String jsonString) {
jsonObject = Common.getObjectFromJsonString(jsonString,3);
ArrayList<HashMap<String, String>> wishList = Common.parseJson(jsonObject);
if (pageEnd > Constants.limit) {
wishAdapter = new WishRowAdaptor(getActivity(),wishList);
}else{
Common.cacheResponse(context,cachedName,jsonString);
wishAdapter = new WishRowAdaptor(getActivity(),wishList);
setListAdapter(wishAdapter);
Common.setRefreshActionButtonState(false, optionsMenu);
}
isDownloading = false;
}
}
private ArrayList<HashMap<String, String>> getWishboardCached() {
String jsonString = Common.getCachedResponse(context,cachedName);
try {
jsonObject = Common.getObjectFromJsonString(jsonString,3);
ArrayList<HashMap<String, String>> wishList = Common.parseJson(jsonObject);
return wishList;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (view.getAdapter() != null
&& ((firstVisibleItem + visibleItemCount) >= totalItemCount)
&& isDownloading == false) {
pageStart = pageEnd + 1;
pageEnd = pageStart + (Constants.limit -1);
String url = getUrl();
sendRequest(url);
isDownloading = true;
}
}
}
In the above code If use setListAdapter(wishAdapter); in onPostExecute() after user has reached end of list. Listview gets updated but all the preveious entries goes away.
Here is my custom adapter
public class WishRowAdaptor extends BaseAdapter {
public WishRowAdaptor(Context context,
ArrayList<HashMap<String, String>> arrayList) {
// TODO Auto-generated constructor stub
this.mData = arrayList;
this.context = context;
this.listAq = new AQuery(context);
// mKeys = mData.keySet().toArray(new String[arrayList.size()]);
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtWishName;
ImageButton btn_touchwood;
ImageButton btn_addwish;
TextView tvGesture;
TextView tvNotes;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final HashMap<String, String> rowItem = (HashMap<String, String>) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_wish, null);
holder = new ViewHolder();
holder.txtWishName = (TextView) convertView
.findViewById(R.id.tvwishname);
holder.imageView = (ImageView) convertView
.findViewById(R.id.ivWishImage);
holder.btn_touchwood = (ImageButton) convertView
.findViewById(R.id.btn_touchwood);
holder.btn_addwish = (ImageButton) convertView
.findViewById(R.id.btn_addwish);
holder.tvGesture = (TextView) convertView
.findViewById(R.id.tvGestures);
holder.tvNotes = (TextView) convertView
.findViewById(R.id.tvNotesText);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
}
How do update listview so that it should push new changes to list instead replacing all the content.
you are changing the adapter of the list adapter after each websevice call. just call notifyDataSetChanged after changing the items of your array list. Also dont replace the items of the array list. add the new to your arraylist.

Categories

Resources