My adapter item is removed in arraylist but listview not updating still showing deleted item from database. it has bug only when navigated from other fragments to this fragment.
any help please. dunno where went wrong. have been calling
following is my fragment file.
public class SupplierViewFragment extends Fragment {
private ArrayList<Supplier> suppliers = new ArrayList<>();
ListView lvListView;
FunDapter adapter;
ListView lvSupplierList;
TextView tvSupplierViewMessage;
private FragmentTransaction fragmentTransaction;
ViewPager pager;
private AdapterView.AdapterContextMenuInfo info;
BindDictionary<Supplier> dictionary = new BindDictionary<>();
public SupplierViewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_supplier_view, container, false);
tvSupplierViewMessage = (TextView) view.findViewById(R.id.tvSupplierViewMessage);
tvSupplierViewMessage.setVisibility(View.INVISIBLE);
getData("supplier-view-servlet");
dictionary = new BindDictionary<>();
dictionary.addStringField(R.id.tvSupplierListID, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return "ID: " + item.getSupplierID();
}
});
dictionary.addStringField(R.id.tvSupplierListCompanyName, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierCompanyName();
}
});
dictionary.addStringField(R.id.tvSupplierListName, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return "(" + item.getSupplierName() + ")";
}
});
dictionary.addStringField(R.id.tvSupplierListAddress, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierAddress();
}
});
dictionary.addStringField(R.id.tvSupplierListTelp, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierTelp();
}
});
dictionary.addStringField(R.id.tvSupplierListMobile, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierMobile();
}
});
dictionary.addStringField(R.id.tvSupplierListEmail, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return item.getSupplierEmail();
}
});
dictionary.addStringField(R.id.tvSupplierListCity, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return getCityName("cities-servlet?city-id=" + item.getSupplierCity());
}
});
dictionary.addStringField(R.id.tvSupplierListCountry, new StringExtractor<Supplier>() {
#Override
public String getStringValue(Supplier item, int position) {
return getCountryName("countries-servlet?city-id=" + item.getSupplierCity());
}
});
adapter = new FunDapter(SupplierViewFragment.this.getActivity(),suppliers,R.layout.supplier_list_layout,dictionary);
lvSupplierList = (ListView) view.findViewById(R.id.lvSupplierView);
lvSupplierList.setAdapter(adapter);
adapter.notifyDataSetChanged();
registerForContextMenu(lvSupplierList);
pager = (ViewPager) getActivity().findViewById(R.id.pager);
return view;
}
public void refreshApi(){
suppliers.clear();
adapter.resetData();
getData("supplier-view-servlet");
lvSupplierList.setAdapter(adapter);
adapter.notifyDataSetChanged();
lvSupplierList.invalidate();
//adapter = new FunDapter(SupplierViewFragment.this.getActivity(),suppliers,R.layout.supplier_list_layout,dictionary);
Log.d("REFRESH", suppliers.size()+" -------------------");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String text = null;
switch (item.getItemId()){
case R.id.supplier_view_delete_id:
AlertDialog.Builder builder = new AlertDialog.Builder(SupplierViewFragment.this.getActivity());
builder.setMessage("Are sure to delete selected supplier?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Supplier supplier = new Supplier(suppliers.get(info.position).getSupplierID());
try {
Log.d("Supplier Size:",suppliers.size() + "to delete:" + info.position);
deleteData("supplier-delete-servlet?supplier-id=" + supplier.getSupplierID() );
suppliers.clear();
refreshApi();
Log.d("Supplier AFTER:",suppliers.size() + "to delete:" + info.position);
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
pager.setCurrentItem(0);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(SupplierViewFragment.this.getActivity(),"Supplier Deleted",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No",null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
case R.id.supplier_view_edit_id:
//StaffEditFragment staffEditFragment = new StaffEditFragment.newInstance("Some1","Some2");
Log.d("Current Position:",""+info.position);
Supplier supplierEdit = suppliers.get(info.position);
Bundle bundle = new Bundle();
bundle.putInt("supplierID",supplierEdit.getSupplierID());
SupplierEditFragment supplierEditFragment = new SupplierEditFragment();
supplierEditFragment.setArguments(bundle);
fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,supplierEditFragment);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Edit Supplier");
fragmentTransaction.commit();
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.supplier_context_menu,menu);
}
public void deleteData(String servletAddress){
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
}
public String getCountryName(String servletAddress){
String countryName = null;
try {
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
for (int i = 0; i < jsonArray.length(); i++) {
countryName = jsonArray.getJSONObject(i).getString("country-name").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("cityName:",countryName);
return countryName;
}
public String getCityName(String servletAddress){
String cityName = null;
try {
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
for (int i = 0; i < jsonArray.length(); i++) {
cityName = jsonArray.getJSONObject(i).getString("city-name").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("cityName:",cityName);
return cityName;
}
public void getData(String servletAddress){
JsonRequestHelper requestHelper = new JsonRequestHelper();
JSONArray jsonArray = requestHelper.getJsonArrayViaGET(servletAddress);
Supplier supplier = new Supplier();
if (jsonArray == null) {
//Log.d("Reach000","#####################");
tvSupplierViewMessage.setVisibility(View.VISIBLE);
tvSupplierViewMessage.setText("Error Connecting Database");
Toast.makeText(SupplierViewFragment.this.getActivity(), "Error Connection", Toast.LENGTH_SHORT).show();
}
else {
tvSupplierViewMessage.setVisibility(View.INVISIBLE);
tvSupplierViewMessage.setText("");
try {
for (int i = 0; i < jsonArray.length(); i++) {
supplier = new Supplier();
supplier.setSupplierID(Integer.parseInt(jsonArray.getJSONObject(i).get("id").toString()));
supplier.setSupplierCompanyName(jsonArray.getJSONObject(i).get("company-name").toString());
supplier.setSupplierName(jsonArray.getJSONObject(i).get("name").toString());
supplier.setSupplierAddress(jsonArray.getJSONObject(i).get("address").toString());
supplier.setSupplierCity(Integer.parseInt(jsonArray.getJSONObject(i).get("city-id").toString()));
supplier.setSupplierEmail(jsonArray.getJSONObject(i).get("email").toString());
supplier.setSupplierTelp(jsonArray.getJSONObject(i).get("telp").toString());
supplier.setSupplierMobile(jsonArray.getJSONObject(i).get("mobile").toString());
suppliers.add(supplier);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
You can add a updateDataset(ArrayList suppliers) method in adapter and call it whenever you want to update listview content.
Add below method in adapter,
public void updateDataset(ArrayList<Supplier> suppliers) {
this.suppliers = suppliers;
notifyDatasetChanged();
}
When you delete item from database,fetch new data and call,
adapter.updateDataset(ArrayList<Supplier> suppliers)
problem solved by replacing it as a new fragment everytime it deletes an item. not sure if it's the right way but at least work for the moments. Thanks for the response guys. hope it helps for others looking for similiar problems.
fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new SupplierFragment());
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("View Supplier");
fragmentTransaction.commit();
return super.onContextItemSelected(item);
Related
I have an app that displays my e-mail via microsoft graph api.
Everything but 1 things i working fine so far. When the list first loads in, all info is correctly displayed, but when i scroll down, then back up. The imageview of the attachement sits on the wrong rows. It just displays on rows without attachement. In the adapter i have an if clausule which says to only show the image in the row if the hasAttachement value is "true".. I really don't get why it is redrawin the image in the wrongs rows..
The method where i set the attachement is called:
setBijlage() in MessagesAdapter
EDIT: If i click the row in my app, that row displays correctly again (gains an icon if it has attachement, and deletes it if it doesn't)
MailActivity.java
public class MailActivity extends AppCompatActivityRest implements SwipeRefreshLayout.OnRefreshListener, MessagesAdapter.MessageAdapterListener {
private String currentFolder;
private String currentUser;
private List<Message> messages = new ArrayList<>();
private RecyclerView recyclerView;
private MessagesAdapter mAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private ActionModeCallback actionModeCallback;
private ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_mail);
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentFolder = getString(R.string.inbox);
currentUser = getIntent().getStringExtra("USER_EMAIL");
setActionBarMail(currentFolder, currentUser);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
actionModeCallback = new ActionModeCallback();
// show loader and fetch messages
swipeRefreshLayout.post(
new Runnable() {
#Override
public void run() {
getAllMails(15);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void processResponse(OutlookObjectCall outlookObjectCall, JSONObject response) {
switch (outlookObjectCall) {
case READUSER: {
System.out.println("reading user");
} break;
case READMAIL: {
messages.clear();
JSONObject list = response;
try {
JSONArray mails = list.getJSONArray("value");
Type listType = new TypeToken<List<Message>>() {
}.getType();
messages = new Gson().fromJson(String.valueOf(mails), listType);
for (Message message : messages) {
message.setColor(getRandomMaterialColor("400"));
}
System.out.println(messages.get(2).getFrom().getEmailAddress().getName());
mAdapter = new MessagesAdapter(this, messages, this);
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
break;
case SENDMAIL: {
System.out.println("Just send a mail." );
}
}
}
#Override
public void onRefresh() {
// swipe refresh is performed, fetch the messages again
getAllMails(15);
}
#Override
public void onIconClicked(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
#Override
public void onIconImportantClicked(int position) {
// Star icon is clicked,
// mark the message as important
Message message = messages.get(position);
message.setImportance("normal");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
}
#Override
public void onMessageRowClicked(int position) {
// verify whether action mode is enabled or not
// if enabled, change the row state to activated
if (mAdapter.getSelectedItemCount() > 0) {
enableActionMode(position);
} else {
// read the message which removes bold from the row
Message message = messages.get(position);
message.setIsRead("true");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: " + message.getBodyPreview(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRowLongClicked(int position) {
// long press is performed, enable action mode
enableActionMode(position);
}
private void enableActionMode(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
private void toggleSelection(int position) {
mAdapter.toggleSelection(position);
int count = mAdapter.getSelectedItemCount();
if (count == 0) {
actionMode.finish();
} else {
actionMode.setTitle(String.valueOf(count));
actionMode.invalidate();
}
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_action_mode, menu);
// disable swipe refresh if action mode is enabled
swipeRefreshLayout.setEnabled(false);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// delete all the selected messages
deleteMessages();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mAdapter.clearSelections();
swipeRefreshLayout.setEnabled(true);
actionMode = null;
recyclerView.post(new Runnable() {
#Override
public void run() {
mAdapter.resetAnimationIndex();
// mAdapter.notifyDataSetChanged();
}
});
}
}
// deleting the messages from recycler view
private void deleteMessages() {
mAdapter.resetAnimationIndex();
List<Integer> selectedItemPositions =
mAdapter.getSelectedItems();
for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
mAdapter.removeData(selectedItemPositions.get(i));
}
mAdapter.notifyDataSetChanged();
}
private void setActionBarMail(String title, String subtitle) {
getSupportActionBar().setTitle(title);
getSupportActionBar().setSubtitle(subtitle);
}
private void getAllMails(int aantalMails) {
swipeRefreshLayout.setRefreshing(true);
try {
new GraphAPI().getRequest(OutlookObjectCall.READMAIL, this, "/inbox/messages?$top=" + aantalMails);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
MessagesAdapter.java
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MyViewHolder> {
private Context mContext;
private List<Message> messages;
private MessageAdapterListener listener;
private SparseBooleanArray selectedItems;
// array used to perform multiple animation at once
private SparseBooleanArray animationItemsIndex;
private boolean reverseAllAnimations = false;
// index is used to animate only the selected row
// dirty fix, find a better solution
private static int currentSelectedIndex = -1;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener {
public TextView from, subject, message, iconText, timestamp;
public ImageView iconImp, imgProfile, imgBijlage;
public LinearLayout messageContainer;
public RelativeLayout iconContainer, iconBack, iconFront;
public MyViewHolder(View view) {
super(view);
from = (TextView) view.findViewById(R.id.from);
subject = (TextView) view.findViewById(R.id.txt_primary);
message = (TextView) view.findViewById(R.id.txt_secondary);
iconText = (TextView) view.findViewById(R.id.icon_text);
timestamp = (TextView) view.findViewById(R.id.timestamp);
iconBack = (RelativeLayout) view.findViewById(R.id.icon_back);
iconFront = (RelativeLayout) view.findViewById(R.id.icon_front);
iconImp = (ImageView) view.findViewById(R.id.icon_star);
imgProfile = (ImageView) view.findViewById(R.id.icon_profile);
messageContainer = (LinearLayout) view.findViewById(R.id.message_container);
iconContainer = (RelativeLayout) view.findViewById(R.id.icon_container);
imgBijlage = (ImageView) view.findViewById(R.id.icon_attachement);
view.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(getAdapterPosition());
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
}
public MessagesAdapter(Context mContext, List<Message> messages, MessageAdapterListener listener) {
this.mContext = mContext;
this.messages = messages;
this.listener = listener;
selectedItems = new SparseBooleanArray();
animationItemsIndex = new SparseBooleanArray();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Message message = messages.get(position);
// displaying text view data
holder.from.setText(message.getFrom().getEmailAddress().getName());
holder.subject.setText(message.getSubject());
holder.message.setText(message.getBodyPreview());
System.out.println("EMAIL: " + position + " HAS ATTACHEMENT: " + message.getHasAttachments());
setBijlage(message, holder);
try {
setDate(message, holder);
} catch (ParseException e) {
e.printStackTrace();
}
// displaying the first letter of From in icon text
holder.iconText.setText(message.getFrom().getEmailAddress().getName().substring(0, 1));
// change the row state to activated
holder.itemView.setActivated(selectedItems.get(position, false));
// change the font style depending on message read status
applyReadStatus(holder, message);
// handle message star
applyImportant(holder, message);
// handle icon animation
applyIconAnimation(holder, position);
// display profile image
applyProfilePicture(holder, message);
// apply click events
applyClickEvents(holder, position);
}
private void setDate(Message message, MyViewHolder holder) throws ParseException {
String stringDate = message.getReceivedDateTime();
String COMPARE_FORMAT = "yyyy/MM/dd";
String OUTPUT_FORMAT_NOT_TODAY = "dd MMM";
String JSON_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat dateFormat = new SimpleDateFormat(COMPARE_FORMAT);
SimpleDateFormat formatter = new SimpleDateFormat(JSON_FORMAT);
SimpleDateFormat defaultFormat = new SimpleDateFormat(OUTPUT_FORMAT_NOT_TODAY);
//today date (check if today)
Date today = new Date();
String currentDate = dateFormat.format(today);
//hours (if today
Date date = formatter.parse(stringDate);
formatter.applyPattern(COMPARE_FORMAT);
String mailDate = formatter.format(date);
//dd/month (if not today)
boolean is24 = DateFormat.is24HourFormat(mContext);
if (mailDate.equals(currentDate)) {
if (is24) {
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
holder.timestamp.setText(outputFormat.format(date));
} else {
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a");
holder.timestamp.setText(outputFormat.format(date));
}
} else {
holder.timestamp.setText(defaultFormat.format(date));
}
}
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}
}
private void applyClickEvents(MyViewHolder holder, final int position) {
holder.iconContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconClicked(position);
}
});
holder.iconImp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconImportantClicked(position);
}
});
holder.messageContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onMessageRowClicked(position);
}
});
holder.messageContainer.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(position);
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
});
}
private void applyProfilePicture(MyViewHolder holder, Message message) {
holder.imgProfile.setImageResource(R.drawable.bg_circle);
holder.imgProfile.setColorFilter(message.getColor());
holder.iconText.setVisibility(View.VISIBLE);
}
private void applyIconAnimation(MyViewHolder holder, int position) {
if (selectedItems.get(position, false)) {
holder.iconFront.setVisibility(View.GONE);
resetIconYAxis(holder.iconBack);
holder.iconBack.setVisibility(View.VISIBLE);
holder.iconBack.setAlpha(1);
if (currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, true);
resetCurrentIndex();
}
} else {
holder.iconBack.setVisibility(View.GONE);
resetIconYAxis(holder.iconFront);
holder.iconFront.setVisibility(View.VISIBLE);
holder.iconFront.setAlpha(1);
if ((reverseAllAnimations && animationItemsIndex.get(position, false)) || currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, false);
resetCurrentIndex();
}
}
}
// As the views will be reused, sometimes the icon appears as
// flipped because older view is reused. Reset the Y-axis to 0
private void resetIconYAxis(View view) {
if (view.getRotationY() != 0) {
view.setRotationY(0);
}
}
public void resetAnimationIndex() {
reverseAllAnimations = false;
animationItemsIndex.clear();
}
#Override
public long getItemId(int position) {
return messages.get(position).getAutoId();
}
private void applyImportant(MyViewHolder holder, Message message) {
if (message.getImportance().toLowerCase().equals("high")) {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_selected));
} else {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_border_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_normal));
}
}
private void applyReadStatus(MyViewHolder holder, Message message) {
if (message.getIsRead().toLowerCase().equals("true")) {
holder.from.setTypeface(null, Typeface.NORMAL);
holder.subject.setTypeface(null, Typeface.NORMAL);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.message));
} else {
holder.from.setTypeface(null, Typeface.BOLD);
holder.subject.setTypeface(null, Typeface.BOLD);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.from));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
}
}
#Override
public int getItemCount() {
return messages.size();
}
public void toggleSelection(int pos) {
currentSelectedIndex = pos;
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
animationItemsIndex.delete(pos);
} else {
selectedItems.put(pos, true);
animationItemsIndex.put(pos, true);
}
notifyItemChanged(pos);
}
public void clearSelections() {
reverseAllAnimations = true;
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
public void removeData(int position) {
messages.remove(position);
resetCurrentIndex();
}
private void resetCurrentIndex() {
currentSelectedIndex = -1;
}
public interface MessageAdapterListener {
void onIconClicked(int position);
void onIconImportantClicked(int position);
void onMessageRowClicked(int position);
void onRowLongClicked(int position);
}
}
Change setBijlage to this..
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}else{
holder.imgBijlage.setVisibility(View.GONE);
}
}
That's occours because the recyclerView reuses the references of the rows and in your case, some rows doesnt have any reference in holder.imgBijlage, causing missbehavior.
To solve this, put holder.imgBijlage.setImageResource(R.drawable.ic_bijlage); inside onBindViewHolder and change setBijlage to:
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
}else {
holder.imgBijlage.setVisibility(View.INVISIBLE);
}
Your icon will be hidden when there is no attachement
I created a new project tabbed view. I want three layout on my main screen 1st home 2nd category 3rd favorite. I have code of Home activity which is fragment activity the code is here
public class HomeFragment extends android.support.v4.app.Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
and I have another activity which is video playlist. I want to show the playlist activity in my home fragment page but I am too confused and new to Android I don't have idea what to do.
The code of video playlist is here. How can I call this code in my homeFragment class? I tried too many ways but got too confused.
Code is here which I want to implement in my home section
public ProgressBar nextBar;
List<String> next_title;
List title;
List vid;
List<String> next_vid;
ArrayList<Videos> videos=new ArrayList<Videos>();
Videos video;
ArrayList<Videos> toclear=new ArrayList<Videos>();
List<Videos> fav = new ArrayList<Videos>();
InterstitialAd mInterstitialAd;
ListView listview;
Toolbar toolbar,favourite;
int menu_id;
LinearLayout layout, no_fav;
private HttpHandler parserVideo;
String nextPageToken;
String apiKey = "AIzaSyDD73ZAzcR6bXa1qOv8YZY3fFmNwfTPs48";
String url;
Main_activity_adapter search;
Main_activity_adapter adapter;
String url_home= "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=15&playlistId=PLQGGrzFoybiOks7f2BReNzNwkRw3cN6RB&key="+apiKey+"";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_sec);
nextBar = (ProgressBar) findViewById(R.id.nextProgress);
layout = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
url = url_home;
listview = (ListView) findViewById(R.id.listview);
no_fav = (LinearLayout)findViewById(R.id.no_favourit);
no_fav.setVisibility(View.GONE);
parserVideo = new HttpHandler();
getVideosPlaylist videosplaylist = new getVideosPlaylist();
videosplaylist.execute();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listview.setOnScrollListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
final String toolbar_name = toolbar.getTitle().toString();
MenuItemCompat.setOnActionExpandListener(myActionMenuItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateList();
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (!s.isEmpty()) {
setSearch();
search.getFilter().filter(s);
}
return false;
}
});
return true;
}// end of toolbar control
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void updateList(){
adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
JSONObject jp_obj;
JSONArray jar_array;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
String toolbar_check = toolbar.getTitle().toString();
switch(view.getId()){
case R.id.listview:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if(toolbar_check!="Favourites") {
OnScrollList onscroll = new OnScrollList();
onscroll.execute();
}
}
}
}
class getVideosPlaylist extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
jp_obj = parserVideo.getJsonFromYoutube(url);
try {
if (jp_obj.has("nextPageToken")) {
nextPageToken = jp_obj.getString("nextPageToken");
}
jar_array = new JSONArray(jp_obj.getString("items"));
if(jp_obj != null) {
JSONObject c = jar_array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
title = new ArrayList<String>(jar_array.length());
vid = new ArrayList<>(jar_array.length());
for (int j = 0; j < jar_array.length(); j++) {
c = jar_array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\\['\\]", ""));
String link = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
video = new Videos(str, link);
videos.add(video);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
updateList();
layout.setVisibility(View.GONE);
cancel(true);
super.onPostExecute(s);
}
}
class OnScrollList extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
if (nextPageToken!=null){
String nextPage = "&pageToken="+nextPageToken+"";
JSONObject next = parserVideo.getJsonFromYoutube(url+nextPage);
try {
JSONArray array = new JSONArray(next.getString("items"));
if (next != null) {
JSONObject c = array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
next_title = new ArrayList<String>(array.length());
next_vid = new ArrayList<String>((array.length()));
for (int j = 0; j < array.length(); j++) {
c = array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\'", ""));
next_title.add(str);
String nextLink = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
next_vid.add(nextLink);
video = new Videos(str, nextLink);
toclear.add(video);
}
}
}if (next.has("nextPageToken")){
nextPageToken = next.getString("nextPageToken");
}else if(!next.has("nextPageToken")){
nextPageToken = null;}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPostExecute(String s) {
videos.addAll(toclear);
adapter.notifyDataSetChanged();
nextBar.setVisibility(View.GONE);
toclear.clear();
cancel(true);
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
nextBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
public void setSearch()
{
search = new Main_activity_adapter(Videos_activity.this, videos, true);
listview.setAdapter(search);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos)search.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
public void favouritList(){
Main_activity_adapter favourit_adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(favourit_adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
Define variable like public static String test=""; in Activity then in Fragment get it like String test1=ActivityName.test; now you have value of test into test1
First of all, you need to understand that Activity contains fragments, not vice versa. So one way to make your idea come true is to make your activity contain three fragments:
1)Home
2)Category
3)Favorite
To send data from activity to fragment usually use Bundle object.
Then create the instance of the fragment and put bundle there by setArguments(yourBundle) method.
It is the main idea, if you want details then read official documentation and use search on SOF.
use a Bundle:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("yourArg","yourType"); //this could be String, int, float,etc
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.yourContainer,fragment).commit();
and in your Fragment's onCreateView:
Bundle bundle = getArguments();
When I try to have Json result, I have all field that I want but without id field. I don't understand this I give you the json result :
[{"id":8671,"dateEvenement":"2017-08-14T16:49:34.404+02:00","type":"Competition","activitePlannings":[{"id":8675,"nomActivite":"Base-ball","idActivite":8654},{"id":8674,"nomActivite":"Balle de Hockey","idActivite":8653},{"id":8676,"nomActivite":"Course d'obstacles","idActivite":8655}],"groupe":{"id":8667,"nomGroupe":"Benjamin","groupeActivites":[{"id":8673,"nomGroupe":"Benjamin","idGroupe":8667,"nomActivite":"Balle de Hockey","idActivite":8653}]},"utilisateurPlannings":[{"id":8679,"nomUtilisateur":"Colart","prenomUtilisateur":"Pierre","type":"RESPONSABLE","datePlanning":"2017-08-14T16:49:34.404+02:00","idDisponibilite":0,"typePlanning":"Competition","nomGroupe":"Benjamin","planningId":8671,"utilisateurId":8651}],"Disponibilites":[],"validate":false}]
And I have this class with setter and getter for sure :
public class Planning {
private int id;
private String dateEvenement;
private Groupe groupe;
private String type;
private List<ActivitePlanning> activitePlannings;
private List<UtilisateurPlanning> utilisateurPlannings;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public Planning() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return dateEvenement;
}
public void setDate(String date) {
Date date2 = null;
try {
date2 = format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
this.dateEvenement = sdf.format(date2.getTime());
}
public ejplanningandroid.ejplanningandroid.Models.Groupe getGroupe() {
return groupe;
}
public void setGroupe(ejplanningandroid.ejplanningandroid.Models.Groupe groupe) {
this.groupe = groupe;
}
public List<UtilisateurPlanning> getUtilisateurPlannings() {
return utilisateurPlannings;
}
public void setUtilisateurPlannings(List<UtilisateurPlanning> utilisateurPlannings) {
this.utilisateurPlannings = utilisateurPlannings;
}
public List<ActivitePlanning> getActivitePlannings() {
return activitePlannings;
}
public void setActivitePlannings(List<ActivitePlanning> activitePlannings) {
this.activitePlannings = activitePlannings;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
I set my Planning Object with this class :
#Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null){
view = LayoutInflater.from(getContext()).inflate(R.layout.rowplanning,parent, false);
}
PlanningViewHolder planningViewHolder = (PlanningViewHolder)view.getTag();
if(planningViewHolder==null){
planningViewHolder= new PlanningViewHolder();
planningViewHolder.Date = (TextView)view.findViewById(R.id.Date);
planningViewHolder.NomActivite =(TextView)view.findViewById(R.id.Activite);
planningViewHolder.NomGroupe = (TextView)view.findViewById(R.id.NomGroupe);
planningViewHolder.Type = (TextView)view.findViewById(R.id.Type);
planningViewHolder.Utilisateur = (TextView)view.findViewById(R.id.Utilisateur);
view.setTag(planningViewHolder);
}
Planning planning = getItem(position);
planningViewHolder.Type.setText("Type : "+planning.getType());
planningViewHolder.NomGroupe.setText("Groupe : "+planning.getGroupe().getNomGroupe());
String nomActivite = setStringFromArrayActivite(planning.getActivitePlannings());
planningViewHolder.NomActivite.setText("Activités : "+nomActivite);
planningViewHolder.Date.setText(planning.getDate());
String nomUtilisateur =setStringFromArrayUtilisateur(planning.getUtilisateurPlannings());
planningViewHolder.Utilisateur.setText("Moniteurs : "+nomUtilisateur);
return view;
}
My Asynctask :
public class PlanningCandidatureTask extends AsyncTask<String,Void,List<Planning>> {
#Override
protected List<Planning> doInBackground(String... params) {
try {
InterfaceService interfaceService = new RestAdapter.Builder()
.setEndpoint(InterfaceService.path).build()
.create(InterfaceService.class);
String login = params[0];
String pass = params[1];
List<Planning> PlanningList = interfaceService.getPlanningByValidation(login, pass);
return PlanningList;
}catch (RetrofitError retrofitError){
return null;
}
}
}
But when want to see if i have an id, this field have a 0 value. I have try to change type to String but it does not work ...
EDITED :
public class CandidatureFragment extends Fragment {
private ListView mListView;
private View view;
private List<Planning> listPlanning = new ArrayList<Planning>();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.candidature_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listViewPlanning2);
PlanningCandidatureTask planningTask =
(PlanningCandidatureTask) new PlanningCandidatureTask()
.execute(((MainActivity) getActivity()).getUtilisateur().getLogin(),
((MainActivity) getActivity()).getUtilisateur().getMotDepasse());
try {
if(planningTask.get() != null) {
for (int i = 0; i < planningTask.get().size(); i++) {
Planning planning=new Planning();
Log.i("Test",planningTask.get().get(i).getGroupe()+"");
planning.setDate(planningTask.get().get(i).getDate());
planning.setType(planningTask.get().get(i).getType());
planning.setGroupe(planningTask.get().get(i).getGroupe());
planning.setActivitePlannings(planningTask.get().get(i).getActivitePlannings());
planning.setUtilisateurPlannings(planningTask.get().get(i).getUtilisateurPlannings());
listPlanning.add(planning);
}
PlanningAdapter adapter = new PlanningAdapter(view.getContext(),listPlanning);
mListView.setAdapter(adapter);
}else
{
Toast.makeText(view.getContext(), "ERREUR DE CONNECTION", Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
final PlanningAdapter adapter = new PlanningAdapter(view.getContext(),listPlanning);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.getContext());
builder.setTitle("Validation");
builder.setMessage("Voulez vous vraiment ajouter une candidature à ce planning ?")
.setCancelable(false).setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Planning selectedFromList = (Planning) parent.getAdapter().getItem(position);
/*PostTask postTask =
(PostTask) new PostTask()
.execute(((MainActivity) getActivity()).getUtilisateur().getLogin(),
((MainActivity) getActivity()).getUtilisateur().getMotDepasse(),
"none","0");*/
dialog.cancel();
Toast.makeText(view.getContext(), "item selectionnné : "+selectedFromList.getId(), Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
});
return view;
}
Get retrofit ::
#GET("/planning/unvalidate/")
List<Planning> getPlanningByValidation(#Query("login") String login, #Query("password") String password);
public class PlanningViewHolder {
public TextView Date;
public TextView NomGroupe;
public TextView Type;
public TextView NomActivite;
public TextView Utilisateur;
}
hi friends i am new to the android development i am developing an app similar to flipkart. i am using the tab layout where there are 4tabs 1.home 2.menu 3.cart 4.settings
Each tab consists of list view where each one is having fragment in it,when i click the menu button and select an item that i want to order,after ordering it, it is not loading in the cart so i am not able to locate the item in the cart
MenuAdapter.Java
public class Second_adapter extends BaseAdapter {
Context context;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin=new Session(context);
if (userloggedin.isLoggedIn()){
addcart();
Cart cart=new Cart();
cart.cartdata();
Toast.makeText(context, "LoggedIn" +itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_process.php?userid="+customid+"&Item="+itembasename+itemde+subtmsub+"&Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
String count=cartobj.getString("count");
loginPrefsEditor.putString("Badge",count);
loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
Cart.Class
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged=new Session(getActivity());
if (cartlogged.isLoggedIn()){
cartdata();
}else {
Toast.makeText(getActivity(),"Not Logged", Toast.LENGTH_SHORT).show();
}
cartdata();
return cartfrag;
}
void cartdata() {
SharedPreferences customerid=getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
subtotal.setText(subtext);
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
TabLayout.java
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
}
MainActivity.java
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
mViewpager.setOffscreenPageLimit(4);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can fix this way by setting setOnPageChangeListener on viewPager:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int index) {
// TODO Auto-generated method stub
if(index==3){
((Cart) mAdapter.getItem(index)).cartdata();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Your cartdata() must be public.
I am using a ViewPager in my application and I have three tabs in it; I am using ViewPager inside a fragment. Now my problem here is, I am getting data correctly while loading the application, but when I go next page and then back to ViewPager, the data is lost and tabs are not working. Please assist me. Below is my code:
import com.devpoint.rprtjobs.R;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.design.widget.TabLayout;
public class MainActivity extends Fragment {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
SwipeViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"OnGoing","UpComing","Expired"};
int Numboftabs =3;
private View rootView;
#SuppressWarnings("deprecation")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.activity_main,
container, false);
adapter = new SwipeViewPagerAdapter(getActivity().getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(3);
pager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if(position ==0)
{
SwipeViewPagerAdapter.Pagename = "ListOnGoing";
}
else if(position ==1)
{
SwipeViewPagerAdapter.Pagename = "ListUpComing";
}
else if(position ==2)
{
SwipeViewPagerAdapter.Pagename = "ListExpired";
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
}
Here is my adapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Edwin on 15/02/2015.
*/
public class SwipeViewPagerAdapter extends FragmentPagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
public static String Pagename="ListOnGoing";
// Build a Constructor and assign the passed Values to appropriate values in the class
public SwipeViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
//Pagename = "ListOnGoing";
ListOnGoing mListOnGoing = new ListOnGoing();
return mListOnGoing;
case 1:
//Pagename = "ListUpComing";
ListUpComing mListUpComing = new ListUpComing();
return mListUpComing;
case 2:
//Pagename = "ListExpired";
ListExpaire mListExpaire = new ListExpaire();
return mListExpaire;
default:
return null;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
And here is one of my fragments:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
#SuppressLint("ShowToast")
public class ListOnGoing extends Fragment implements OnItemClickListener {
Boolean isInternetPresent = false;
ConnectionDetector connectdetector;
public static ListView swipelisview;
Activity activity;
public static ProductListAdapter productListAdapter;
SharedPreference sharedPreference;
String LoggedIn;
boolean fragmentAlreadyLoaded = false;
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.listener = (FragmentActivity) activity;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
try {
super.onViewCreated(view, savedInstanceState);
swipelisview = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.emptyView);
swipelisview.setEmptyView(emptyView);
if (savedInstanceState == null && !fragmentAlreadyLoaded) {
fragmentAlreadyLoaded = true;
repoObject = SplashScreen.getRepo();
session = new SessionManager(getActivity());
HashMap<String, String> Radious = session.getRadiousName();
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
//LoadActivity.Status="";
GPlaces = new GetAllGooglePlaces();
GPlaces.GetOpportunityList("", Radiosname, getActivity());
DisPlayOppList();
}
productListAdapter = new ProductListAdapter(getActivity(),
GetAllGooglePlaces.ArrayListOngoing);
swipelisview.setAdapter(productListAdapter);
productListAdapter.notifyDataSetChanged();
session = new SessionManager(getActivity());
HashMap<String, String> Radious = session.getRadiousName();
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
searchedit = (EditText) rootView.findViewById(R.id.searchbox);
Button searchbtn = (Button) rootView.findViewById(R.id.searchbtn);
searchedit = (EditText) rootView.findViewById(R.id.searchbox);
clearbtn = (Button) rootView.findViewById(R.id.clearbtn);
searchedit.addTextChangedListener(watch);
clearbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LoadActivity.Status="";
searchedit.setText("");
GPlaces.GetOpportunityList("", Radiosname, getActivity());
DisPlayOppList();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
multipleCat = "";
GetAllGooglePlaces.ArrayListOngoing = new CopyOnWriteArrayList<>();
SearchText = searchedit.getText()
.toString();
LoadActivity.Status = "Search";
if (LoadActivity.isOnline) {
GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());
DisPlayOppList();
}
else {
List<OpportunityTable> alloffers = repoObject.roffertable
.getAlloffersbySearchKeyword(SearchText);
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
}
}
});
}
});
HashMap<String, String> user = session.getLogin();
LoggedIn = user.get(SessionManager.KEY_Login);
if (LoggedIn == null) {
LoggedIn = "";
}
connectdetector = new ConnectionDetector(getActivity());
try {
// Check if Internet present
isInternetPresent = connectdetector.isConnectingToInternet();
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
footerlayout = (LinearLayout) rootView.findViewById(R.id.footerlayout);
footerlayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
swipelisview.requestDisallowInterceptTouchEvent(true);
return true;
}
});
swipelisview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
final int position, long id) {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);
try {
final DetailsViewpagerFragment mDetailsViewpagerFragment = new DetailsViewpagerFragment();
String url;
if (LoadActivity.isOnline) {
progresdialog = new ProgressDialog(getActivity());
progresdialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Details..."));
progresdialog.setIndeterminate(false);
progresdialog.setCancelable(false);
progresdialog.show();
ListDetails product = GetAllGooglePlaces.ArrayListOngoing
.get(position);
OpportunityID = product.getOfferID();
url = LoadActivity.BaseUri + "SaveUserViewedOpportunities";
JsonObjectRequest jsObjRequest;
jsObjRequest = new JsonObjectRequest(
Request.Method.POST, url,
getSaveViewUserParams(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pagename = "Userplaceslist";
mDetailsViewpagerFragment
.setClickList(position);
FragmentManager fragment = getFragmentManager();
fragment.beginTransaction()
.replace(R.id.frame_container,
mDetailsViewpagerFragment)
.commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
ModuleFragmentBackStackingClass
.AddtoStack(
mDetailsViewpagerFragment,
EnumModuleTags.SinglePlaceActivity,
getString(R.string.mainfrgment_rprt));
LoadActivity.updateActionbarMenu();
progresdialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
Toast.makeText(getActivity(), "False",
Toast.LENGTH_LONG).show();
progresdialog.dismiss();
}
});
AppController.getInstance().addToRequestQueue(
jsObjRequest);
} else {
mDetailsViewpagerFragment.setClickList(position);
FragmentManager fragment = getFragmentManager();
fragment.beginTransaction()
.replace(R.id.frame_container,
mDetailsViewpagerFragment).commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
ModuleFragmentBackStackingClass.AddtoStack(
mDetailsViewpagerFragment,
EnumModuleTags.SinglePlaceActivity,
getString(R.string.mainfrgment_rprt));
}
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
private JSONObject getSaveViewUserParams() {
JSONObject params = new JSONObject();
HashMap<String, String> UserId = session.getUserID();
String UserIdVal = UserId.get(SessionManager.KEY_UserID);
if (!(UserIdVal == null)) {
UserIdVal = UserId.get(SessionManager.KEY_UserID);
} else {
UserIdVal = "0";
}
try {
params.put("UserId", UserIdVal);
params.put("OpportunityID", OpportunityID);
params.put("UserViewedID", 0);
params.put("Shortlisted", true);
params.put("KeyValue", null);
} catch (JSONException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return params;
}
});
// Click The FavoritesItem on LongPress
swipelisview.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
InputMethodManager imm;
imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);
try {
ImageView button;
button = (ImageView) view
.findViewById(R.id.fav_checkbox);
String tag = button.getTag().toString();
if (tag.equals(getString(R.string.grey_favcolor))) {
sharedPreference.addFavorite(activity,
GetAllGooglePlaces.ArrayListOngoing.get(position));
button.setTag(getString(R.string.red_favcolor));
button.setImageResource(R.drawable.checked);
} else if (tag.equals(getString(R.string.red_favcolor))){
sharedPreference.removeFavorite(activity,
GetAllGooglePlaces.ArrayListOngoing.get(position));
button.setTag(getString(R.string.grey_favcolor));
button.setImageResource(R.drawable.unchecked);
}
return true;
} catch (NotFoundException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
Toast.makeText(getActivity(), e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return true;
}
});
// Code placed here will be executed even when the fragment comes from
// backstack
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
// String APIkey ="AIzaSyCAekTB0o1MuSYvUb-8HTZxhlJHE8yBUfI";
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
//setRetainInstance(true);
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
#SuppressWarnings("static-access")
#SuppressLint({ "CutPasteId", "ClickableViewAccessibility" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
//setRetainInstance(true);
try
{
Tracker t = ((Analytics) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
t.setScreenName("UserPlaces Listview");
t.send(new HitBuilders.AppViewBuilder().build());
}
catch(Exception e)
{
Toast.makeText(getActivity().getApplication(), "Error"+e.getMessage(), 1).show();
}
rootView = inflater.inflate(R.layout.user_places_listview, container,
false);
swipelisview = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.emptyView);
swipelisview.setEmptyView(emptyView);
return rootView;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
TextWatcher watch = new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence s, int a, int b, int c) {
if(c == 0){
clearbtn.setVisibility(View.GONE);
}
else {
clearbtn.setVisibility(View.VISIBLE);
}
}};
protected void LoadSearchPlaces(String searchparam) {
try {
if (LoadActivity.isOnline) {
JsonArrayRequest movieReq = new JsonArrayRequest("http://192.168.2.10/RPRT.WebApi/api/RPRT/" + "SearchPlaces/"+searchparam,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<HashMap<String, String>> aList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject json_data;
try {
json_data = response.getJSONObject(i);
HashMap<String, String> hm = new HashMap<>();
hm.put("Address", json_data.getString("Address"));
hm.put("City", json_data.getString("City"));
hm.put("Latitude", json_data.getString("Latitude"));
hm.put("Longitude", json_data.getString("Longitude"));
aList.add(hm);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String[] from = { "Address"} ;
int[] to = { R.id.tv };
SimpleAdapter adapterId = new SimpleAdapter(getActivity(), aList,
R.layout.user_places_dropdown_listitem, from, to);
//final AutoCompleteTextView autoCompView = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(adapterId);
autoCompView.setThreshold(1);
// Pname.setThreshold(1);
autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> hm = (HashMap<String, String>) parent
.getAdapter().getItem(position);
autoCompView.setText(hm.get("Address"));
SplashScreen.nwLocation.setLatitude(Double.parseDouble(hm.get("Latitude")));
SplashScreen.nwLocation.setLongitude(Double.parseDouble(hm.get("Longitude")));
HashMap<String, String> Radious = session.getRadiousName();
final String Radiosname;
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
multipleCat="";
ProgressDialog progresdialog = new ProgressDialog(getActivity());
progresdialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Details..."));
progresdialog.setIndeterminate(false);
progresdialog.setCancelable(false);
//progresdialog.show();
LoadActivity.Status="";
GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());
DisPlayOppList();
searchdialog.cancel();
}
});
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void DisPlayOppList() {
try {
pdialog = new ProgressDialog(getActivity());
pdialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Details..."));
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
if(LoadActivity.Status.equals("Slidemenulist"))
{
int CategoryId = 0;
switch (CopyOfListOnGoing.multipleCat) {
case "Books":
CategoryId = 1;
break;
case "BeautyandFashion":
CategoryId = 2;
break;
case "Electronic":
CategoryId = 3;
break;
case "Food":
CategoryId = 4;
break;
case "HomeService":
CategoryId = 5;
break;
case "Jobs":
CategoryId = 6;
break;
case "RealEstate":
CategoryId = 7;
break;
case "Vehicles":
CategoryId = 8;
break;
}
List<OpportunityTable> alloffers = repoObject.roffertable
.getAllCatOpp(CategoryId , Radiosname);
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
} else {
List<OpportunityTable> alloffers = repoObject.roffertable
.getAlloffers(Integer.parseInt(Radiosname));
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
}
}
catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
multipleCat = "";
DisPlayOppList();
}
/* #Override
public void onResume() {
Log.e("DEBUG", "onResume of Userplace ListView");
super.onResume();
}*/
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of Userplace ListView");
super.onPause();
}
}
And the remaining fragments look the same. Please help me.
After a little research, I found the solution to my problem.
I was originally calling getactivity().getSupportFragmentmanager(). However, the correct code is getChildFragmentManager()
In you adapter extend FragmentStatePagerAdapter instead of FragmentPagerAdapter it will solve your problem. Let me know if you have any problem.
Reason (quoting from javadoc)
/**
The [android.support.v4.view.PagerAdapter] that will provide
fragments for each of the sections. We use a
{#link FragmentPagerAdapter} derivative, which will keep every
loaded fragment in memory. If this becomes too memory intensive, it
may be best to switch to a
[android.support.v4.app.FragmentStatePagerAdapter].
*/
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setOffscreenPageLimit(2);// no of fragments
public float getPageWidth(int position)
{
if (position == 0 || position == 2)
{
return 0.8f;
}
return 1f;
}
I think your problem has already being solved let this be a help to others.I had this same issue and I solved it by extending the adapter class with FragmentStatePagerAdapter instead of FragmentPagerAdapter. This worked for me perfectly hope it works for you guys as well...