I have to display a list of items on recyclerview from a remote network call. I have initialized the recyclerview and set it's layout manager and adapter properly but the list doesn't show.
Here's my adapter class:
public class DashboardAdapter extends RecyclerView.Adapter<HomeDashboardHolder> {
private final Context context;
private List<HomeDashboard> itemsList;
public DashboardAdapter(Context context, List<HomeDashboard> itemsList) {
this.context = context;
this.itemsList = itemsList;
}
#Override
public HomeDashboardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_dashboard_items_layout, parent, false);
return new HomeDashboardHolder(view);
}
#Override
public void onBindViewHolder(HomeDashboardHolder viewholder, int position) {
HomeDashboard dashboard = itemsList.get(position);
viewholder.dashTitle.setText(dashboard.getDashTitle());
Picasso.with(context)
.load(dashboard.getDashIcon())
.placeholder(R.drawable.noimage)
.into(viewholder.dashIcon);
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
}
Here's my activity code so far:
public class HomeActivity extends AppCompatActivity {
private static final String TAG = HomeActivity.class.getSimpleName();
private Toolbar toolbar;
private SwipeRefreshLayout swipeRefresh;
private RecyclerView dashboardRV, recyclerDrawer;
private DrawerLayout drawerLayout;
private List<DrawerItems> itemsList = new ArrayList<>();
private List<HomeDashboard> dashboardsList = new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private RecyclerDrawerAdapter drawerAdapter;
private DashboardAdapter dashboardAdapter;
private String slug;
private int cartLength;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
init();
setSupportActionBar(toolbar);
initDrawer();
setUpDashboard();
}
private void initDrawer() {
recyclerDrawer.setHasFixedSize(true);
recyclerDrawer.setLayoutManager(new LinearLayoutManager(this));
DrawerItems drawerItems = new DrawerItems("Products", R.drawable.basket);
itemsList.add(drawerItems);
DrawerItems drawerItems1 = new DrawerItems("Cart", R.drawable.cart);
itemsList.add(drawerItems1);
DrawerItems drawerItems2 = new DrawerItems("Checkout", R.drawable.check_out);
itemsList.add(drawerItems2);
DrawerItems drawerItems3 = new DrawerItems("Profile", R.drawable.profile);
itemsList.add(drawerItems3);
DrawerItems drawerItems4 = new DrawerItems("Info", R.drawable.info);
itemsList.add(drawerItems4);
DrawerItems drawerItems5 = new DrawerItems("About", R.drawable.about);
itemsList.add(drawerItems5);
drawerAdapter = new RecyclerDrawerAdapter(this, itemsList);
recyclerDrawer.setAdapter(drawerAdapter);
toolbar.setNavigationIcon(R.drawable.burger_menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
setDrawerClickListener();
}
private void setDrawerClickListener() {
recyclerDrawer.addOnItemTouchListener(new RecyclerItemTouchListener(this, recyclerDrawer, new RecyclerClickListener() {
#Override
public void onClick(View view, int position) {
switch (position) {
case 0:
startActivity(new Intent(HomeActivity.this, AllProductsActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 1:
startActivity(new Intent(HomeActivity.this, CartActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 2:
Intent intent = new Intent(HomeActivity.this, CheckOutActivity.class);
startActivity(intent);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 3:
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case 4:
Log.d(TAG, "Info Clicked");
break;
case 5:
startActivity(new Intent(HomeActivity.this, AboutActivity.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void init() {
swipeRefresh = findViewById(R.id.swipeRefresh);
toolbar = findViewById(R.id.toolbar);
dashboardRV = findViewById(R.id.dashboardRV);
recyclerDrawer = findViewById(R.id.recyclerDrawer);
drawerLayout = findViewById(R.id.drawerLayout);
}
private void setUpDashboard() {
dashboardRV.setHasFixedSize(true);
layoutManager = new GridLayoutManager(HomeActivity.this, 2, GridLayoutManager.VERTICAL, false);
dashboardRV.setLayoutManager(layoutManager);
getHomeDash();
}
public void getHomeDash() {
AndroidNetworking.get(Constants.CATEGORIES_ENDPOINT)
.setTag("Get Categories Dashboard")
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Categories Response:\t" + response.toString());
try {
JSONObject jsonObject = new JSONObject(response.toString());
final JSONArray categories = jsonObject.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject object = categories.getJSONObject(i);
String id = object.getString("_id");
String title = object.getString("title");
String image = object.getString("image");
slug = object.getString("slug");
HomeDashboard dashboard = new HomeDashboard();
dashboard.setDashIcon(image);
dashboard.setDashTitle(title);
dashboard.setId(id);
dashboardsList.add(dashboard);
}
dashboardAdapter = new DashboardAdapter(getApplicationContext(), dashboardsList);
dashboardRV.setAdapter(dashboardAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
dashboardAdapter.notifyDataSetChanged();
}
#Override
public void onError(ANError anError) {
Log.d(TAG, "Request Failed:\t" + anError.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_view_cart:
startActivity(new Intent(HomeActivity.this, CartActivity.class));
}
return true;
}
#Override
protected void onResume() {
super.onResume();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
}
}
Here's my sample json response for this activity:
D/HomeActivity: Categories Response: {"success":true,"message":"All Categories","categories":[{"_id":"5aac46d8644ac63f14ffe89b","title":"Shrti","slug":"shrti","image":"http:\/\/res.cloudinary.com\/aapni-dukan\/image\/upload\/v1521239768\/categoryImages\/eBeSBYrG7MP7rW2Sa4qqQd06_lwakio.png"},{"_id":"5aac5b01d224ac3b801b9967","title":"Fruits","slug":"fruits","image":"http:\/\/res.cloudinary.com\/aapni-dukan\/image\/upload\/v1521244929\/categoryImages\/uWQT1XEplligclP4PrNC-Zyf_eamj8u.jpg"}]}
I am initializing and setting the adapter inside the getHomeDash(). I have also called notifyDataSetChanged() but nothing shows.
In the log, to check if the list is empty, I am getting the size as 2 but not able to show any items. I have also tried setting the adapter in onCreate() just after the call to getHomeDash() but still nothing is displayed on the screen.
Viewholder class:
public class HomeDashboardHolder extends RecyclerView.ViewHolder {
public ImageView dashIcon;
public TextView dashTitle;
public HomeDashboardHolder(View itemView) {
super(itemView);
dashIcon = itemView.findViewById(R.id.dashIcon);
dashTitle = itemView.findViewById(R.id.dashTitle);
}
}
Can someone help me out with this pls? Thanks
I think you are operating your UI ( notifyDataSetChanged() ) in a working thread in getHomeDash() JSONObjectRequestListener function.You should invoke this function in a main thread,and check the layout_height and layout_width in XML.
make change for recycler view layoutmanger set used below code..
dashboardRV.setLayoutManager(new GridLayoutManager(this, numberOfColumns,false));
You are calling dashboardAdapter.notifyDataSetChanged(); after creating new object of DashboardAdapter class
notifyDataSetChanged(); is used when there is some changes your list adapter
User this
layoutManager = new GridLayoutManager(HomeActivity.this,2);
Instead of this
layoutManager = new GridLayoutManager(HomeActivity.this, 2, GridLayoutManager.VERTICAL, false);
Related
I am a beginner and I have created a 3 level Multilevel List View inside navigation view, where items and group items are there and each item open's a new activity. The image is attached below.
image
The problem is that there is a group item named Tomorrowland which further has two items, but on click of Tomorrowland Winners it is opening two activities in stack. Like Tomorrowland Winners should open activity A but its opening Activity B and when on back pressed the Activity B the activity A is opened.
The Activity B opens when clicked on Winners.
Home Activity Code:
public class HomeActivity1 extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#BindView(R.id.multi_home)
MultiLevelListView multiLevelListView;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
#BindView(R.id.cvSlider)
CardView cvSlider;
#BindView(R.id.autoSlider)
SliderView autoSlider;
#BindView(R.id.rvClub)
RecyclerView rvClub;
#BindView(R.id.rvProjects)
RecyclerView rvProjects;
Toolbar toolbar;
NavigationView nav_view_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
toolbar = findViewById(R.id.appbarToolbar);
nav_view_home = findViewById(R.id.nav_view_home);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
confMenu();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
toggle.setDrawerSlideAnimationEnabled(true);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
nav_view_home.setNavigationItemSelectedListener(this);
displaySelectedScreen("HOME");
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
private void showItemDescription(Object object, ItemInfo itemInfo) {
if (((BaseItem) object).getName().contains("Home")) {
displaySelectedScreen("HOME");
}
if (((BaseItem) object).getName().contains("We Believe")) {
displaySelectedScreen("WE BELIEVE");
}
if (((BaseItem) object).getName().contains("Workshop")) {
displaySelectedScreen("WORKSHOPS");
}
if (((BaseItem) object).getName().contains("Events")) {
displaySelectedScreen("EVENTS");
}
if (((BaseItem) object).getName().contains("Projects")) {
displaySelectedScreen("PROJECTS");
}
if (((BaseItem) object).getName().contains("Tomorrowland Winners")) {
displaySelectedScreen("TOMORROWLAND WINNERS");
}
if (((BaseItem) object).getName().contains("Tomorrowland Jr.")) {
displaySelectedScreen("TOMORROWLAND JR.");
}
if (((BaseItem) object).getName().contains("Winners")) {
displaySelectedScreen("SPELL BE WINNERS");
}
if (((BaseItem) object).getName().contains("Video Gallery")) {
displaySelectedScreen("VIDEO GALLERY");
}
if (((BaseItem) object).getName().contains("Blog")) {
displaySelectedScreen("BLOG");
}
if (((BaseItem) object).getName().contains("Club")) {
displaySelectedScreen("CLUBS");
}
if (((BaseItem) object).getName().contains("Feed")) {
displaySelectedScreen("FEED");
}
if (((BaseItem) object).getName().contains("Login")) {
displaySelectedScreen("LOGIN");
}
if (((BaseItem) object).getName().contains("Career")) {
displaySelectedScreen("CAREER");
}
if (((BaseItem) object).getName().contains("Inquiry")) {
displaySelectedScreen("INQUIRY");
}
}
#Override
public void onItemClicked(MultiLevelListView parent, View view, Object item, ItemInfo itemInfo) {
showItemDescription(item, itemInfo);
}
#Override
public void onGroupItemClicked(MultiLevelListView parent, View view, Object item, ItemInfo itemInfo) {
showItemDescription(item, itemInfo);
}
};
private void confMenu() {
// custom ListAdapter
ListAdapter listAdapter = new ListAdapter();
multiLevelListView.setAdapter(listAdapter);
multiLevelListView.setOnItemClickListener(mOnItemClickListener);
listAdapter.setDataItems(HomeCustomDataProvider.getInitialItems());
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void displaySelectedScreen(String itemName) {
switch (itemName) {
case "HOME":
drawer.close();
break;
case "WE BELIEVE":
Intent intent = new Intent(HomeActivity1.this,WeBelieveActivity.class);
startActivity(intent);
break;
case "WORKSHOPS":
Intent intent1 = new Intent(HomeActivity1.this,WorkshopsActivity.class);
startActivity(intent1);
break;
case "EVENTS":
Intent intent2 = new Intent(HomeActivity1.this,EventsActivity.class);
startActivity(intent2);
break;
case "PROJECTS":
Intent intent3 = new Intent(HomeActivity1.this,ProjectsActivity.class);
startActivity(intent3);
break;
case "TOMORROWLAND WINNERS":
Intent intent4 = new Intent(HomeActivity1.this, TomorrowLandWinnersActivity.class);
startActivity(intent4);
break;
case "TOMORROWLAND JR.":
Intent intent5 = new Intent(HomeActivity1.this, TomorrowLandJrWinnersActivity.class);
startActivity(intent5);
break;
case "SPELL BE WINNERS":
Intent intent6 = new Intent(HomeActivity1.this,SpellBeWinnersActivity.class);
startActivity(intent6);
break;
case "VIDEO GALLERY":
Intent intent7 = new Intent(HomeActivity1.this,VideoGalleryActivity.class);
startActivity(intent7);
break;
case "BLOG":
Intent intent8 = new Intent(HomeActivity1.this,BlogActivity.class);
startActivity(intent8);
break;
case "CLUBS":
Intent intent9 = new Intent(HomeActivity1.this,ClubActivity.class);
startActivity(intent9);
break;
case "FEED":
Intent intent10 = new Intent(HomeActivity1.this,FeedActivity.class);
startActivity(intent10);
break;
case "LOGIN":
Intent intent11 = new Intent(HomeActivity1.this,LoginActivity.class);
startActivity(intent11);
break;
case "CAREER":
Intent intent12 = new Intent(HomeActivity1.this,CareerActivity.class);
startActivity(intent12);
break;
case "INQUIRY":
Intent intent13 = new Intent(HomeActivity1.this,InquiryActivity.class);
startActivity(intent13);
break;
}
drawer.close();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method display selected screen and passing the id of selected menu
displaySelectedScreen(String.valueOf(item.getItemId()));
//make this method blank
return true;
}
private class ListAdapter extends MultiLevelListAdapter {
#Override
public List<?> getSubObjects(Object object) {
return HomeCustomDataProvider.getSubItems((BaseItem) object);
}
#Override
public boolean isExpandable(Object object) {
return HomeCustomDataProvider.isExpandable((BaseItem) object);
}
#SuppressLint("InflateParams")
#Override
public View getViewForObject(Object object, View convertView, ItemInfo itemInfo) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(HomeActivity1.this).inflate(R.layout.makers_menu_item, null);
viewHolder.nameView = convertView.findViewById(R.id.dataItemName);
viewHolder.arrowView = convertView.findViewById(R.id.dataItemArrow);
viewHolder.levelBeamView = convertView.findViewById(R.id.dataItemLevelBeam);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.nameView.setText(((BaseItem) object).getName());
if (itemInfo.isExpandable()) {
viewHolder.arrowView.setVisibility(View.VISIBLE);
viewHolder.arrowView.setImageResource(itemInfo.isExpanded() ?
R.drawable.ic_arrow_up : R.drawable.ic_bottom_arrow);
} else {
viewHolder.arrowView.setVisibility(View.GONE);
}
viewHolder.levelBeamView.setLevel(itemInfo.getLevel());
return convertView;
}
private class ViewHolder {
TextView nameView;
ImageView arrowView;
LevelBeamView levelBeamView;
}
}
}
The HomeCustomDataProvoder Code is below:
public class HomeCustomDataProvider {
private static final int MAX_LEVELS = 3;
private static final int LEVEL_1 = 1;
private static final int LEVEL_2 = 2;
private static final int LEVEL_3 = 3;
private static List<BaseItem> mMenu = new ArrayList<>();
Context context;
public static List<BaseItem> getInitialItems() {
List<BaseItem> rootMenu = new ArrayList<>();
rootMenu.add(new Item("Home"));
rootMenu.add(new Item("We Believe"));
rootMenu.add(new GroupItem("Echo"));
rootMenu.add(new Item("Video Gallery"));
rootMenu.add(new Item("Blog"));
rootMenu.add(new Item("Clubs"));
rootMenu.add(new Item("Feeds"));
rootMenu.add(new Item("Login"));
rootMenu.add(new GroupItem("Connect"));
return rootMenu;
}
public static List<BaseItem> getSubItems(BaseItem baseItem) {
List<BaseItem> result = new ArrayList<>();
int level1 = ((GroupItem) baseItem).getLevel() + 1;
int level2 = ((GroupItem) baseItem).getLevel() + 2;
String menuItem = baseItem.getName();
GroupItem groupItem = (GroupItem) baseItem;
if (groupItem.getLevel() >= MAX_LEVELS) {
return null;
}
if (level1 == LEVEL_1) {
switch (menuItem.toUpperCase()) {
case "ECHO":
result = getListEcho();
break;
case "CONNECT":
result = getListConnect();
break;
}
}
if (level2 == LEVEL_2) {
switch (menuItem.toUpperCase()) {
case "TOMORROWLAND":
result = getListTomorrowland();
break;
case "SPELL BE":
result = getListSpellBe();
break;
}
}
return result;
}
public static boolean isExpandable(BaseItem baseItem) {
return baseItem instanceof GroupItem;
}
private static List<BaseItem> getListEcho() {
List<BaseItem> list = new ArrayList<>();
list.add(new Item("Workshops"));
list.add(new Item("Events"));
list.add(new Item("Projects"));
list.add(new GroupItem("Tomorrowland"));
list.add(new GroupItem("Spell Be"));
return list;
}
private static List<BaseItem> getListTomorrowland() {
List<BaseItem> list = new ArrayList<>();
list.add(new Item("Tomorrowland Winners"));
list.add(new Item("Tomorrowland Jr."));
return list;
}
private static List<BaseItem> getListSpellBe() {
List<BaseItem> list = new ArrayList<>();
list.add(new Item("Winners"));
return list;
}
private static List<BaseItem> getListConnect() {
List<BaseItem> list = new ArrayList<>();
list.add(new Item("Career"));
list.add(new Item("Inquiry"));
return list;
}
}
Any help would be appreciated. Thanks in advance.
Instead of using contains, you should use equals to check for all conditions, in your case, TomorrowLand Winners contains Winners and also Winners contains Winners, hence it is opening both.
//do this for all conditions
if (((BaseItem) object).getName().equals("Tomorrowland Winners")) {
displaySelectedScreen("TOMORROWLAND WINNERS");
}
Model Class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public boolean setSelected(boolean isSelected) {
this.isSelected = isSelected;
return isSelected;
}
}
Recycler Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
}
HealthActivity
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton = (Button) findViewById(R.id.submit_button);
}
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
String serialNo="";
int serialNum=1;
String testListId = "";
int totalPrice = 0;
String testName = "";
String testPrice="";
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
testListId = testListId+ "," + singleStudent.getTestlist_id().toString();
testName = testName + "\n" + "\n" + singleStudent.getTest_name().toString();
testPrice= testPrice+"\n" + "\n" + singleStudent.getTest_price().toString();
serialNo=serialNo + "\n" + "\n"+ Integer.parseInt(String.valueOf(serialNum));
serialNum++;
totalPrice= totalPrice+ Integer.parseInt(stList.get(i).getTest_price());
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_id",testListId);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
in.putExtra("total_price",totalPrice);
in.putExtra("serial_number",serialNo);
in.putExtra("patient_id",patientID);
startActivity(in);
}
else
Toasty.error(getApplicationContext(), "Please Select Test Lists", Toast.LENGTH_SHORT, true).show();
}
break;
/* Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+""+testPrice, Toast.LENGTH_LONG)
.show();*/
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/*
* Api Call For Displaying Test Lists
* */
private void loadJSON() {
String centerID=(sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
// .baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists("http://192.168.1.80/aoplnew/api/users/gettestlist/"+centerID);
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
Toast.makeText(HealthServicesActivity.this, "APi Call Back", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
}
}
AmountCartActivity
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener , PaymentResultListener {
SharePreferenceManager<LoginModel> sharePreferenceManager;
/*
*Setting Recycler View
* */
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
/*
* Getting Bundle Values
* */
Bundle extras ;
String testId="";
String testName="";
String testPrice="";
String totalPrice="";
String serialNumber="";
private Button backButton;
/*
* Api Call For DashBoard
* */
String st;
Api webService = ServiceGenerator.getApi();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
progressDialog = new ProgressDialog(AmountCartActivity.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
backButton=(Button) findViewById(R.id.back_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
backButton.setOnClickListener(this);
gettingValues();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
startActivity(new Intent(getApplicationContext(), HealthServicesActivity.class));
//finish();
break;
default:
break;
}
}
/*
* Getting Bundle Values and Setting Recycler View
* */
private void gettingValues() {
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
bundle = getIntent().getExtras();
if (bundle != null) {
testId=bundle.getString("test_id");
testName = bundle.getString("test_name");
testPrice = bundle.getString("test_price");
totalPrice= String.valueOf(bundle.getInt("total_price"));
serialNumber=bundle.getString("serial_number");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestId(testId);
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setSerialNumber(serialNumber);
mydataList.add(mydata);
totalPriceDisplay.setText("Total Amount : "+totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
}
Recycler Adapter for AmountCart
/*
* Recycler Adapter
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
How to maintain the checkbox state across the activities. I am displaying checkbox using recycler view in rest api call. I am selecting checkboxes from HealthActivity and clicking on submit button then the whole list is displaying in AmountCartActivity but when I m clicking on back button then i m not getting those selected checkboxes. And when I add or remove any checkbox then it should give the result as per selection only. How to maintain the state of the selected checkboxes?
In your AmountCartActivity when you listen for back button clicks you do this:
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
startActivity(new Intent(getApplicationContext(), HealthServicesActivity.class));
//finish();
break;
default:
break;
}
}
You are opening a brand new HealthServicesActivity and you don't persist the data anywhere. (When you open a new HealthServicesActivity it does not know anything about your old list). So I think what you aim to do is finishing the AmountCartActivity and resuming the previous HealthServicesActivity like this:
#Override
public void onClick(View v) {
switch (v.getId()) {
/*
* back Button Click
* */
case R.id.back_button:
finish(); //JUST FINISH THE ACTIVITY AND RETURN TO THE PREVIOUS ACTIVITY
break;
default:
break;
}
}
EDIT: (added item click listener logic)
As you will be using the same HealthServiceActivity every time you submit and go back, I think you should implement an interface to keep your checkbox states updated. Make below changes in your respective methods (Please see my comments)
RecylerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
private OnItemClickListener onItemClickListener; //ADD THIS GLOBAL FIELD
/** THIS METHOD IS TO BIND YOUR NEW ITEM CLICK LISTENER **/
public void setOnItemClickListener(OnItemClickListener onItemClickListener)
{
this.onItemClickListener = onItemClickListener;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
//YOU DON'T HAVE TO DEAL WITH TAGS, JUST USE BELOW CODE TO SET YOUR
// ITEM CLICK LISTENER TO EACH CHECKBOX
holder.chkSelected.setOnClickListener(v ->
onItemClickListener.onClickItem(position);
}
// THIS METHOD WILL SWITCH YOUR SELECT STATES AND UPDATE ITEMS ACCORDINGLY
public void updateCheckboxState(int position){
TestListModel listItem = android.get(position);
listItem.setSelected(!listItem.isSelected());
notifyDataSetChanged();
}
// ADD THIS INTERFACE
public interface OnItemClickListener {
void onClickItem(int position);
}
}
HealthServicesActivity:
//DON'T FORGET TO IMPLEMENT RecylcerAdapter.OnItemClickListener
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener, RecyclerAdapter.OnItemClickListener {
/*
* Api Call For Displaying Test Lists
* */
private void loadJSON() {
{ ... }
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
madapter.setOnItemClickListener(this); // SET YOUR LISTENER HERE
recyclerView.setAdapter(madapter);
Toast.makeText(HealthServicesActivity.this, "APi Call Back", Toast.LENGTH_SHORT).show();
}
// UPDATE CHECKBOX STATES WHEN AN ITEM IS CLICKED
#Override
public void onClickItem(int position) {
madapter.updateCheckboxState(position);
}
}
I made a navigation in my project, than I have activities, I would made menu from those activities into navigation. so I need to convert those activities into fragments.
This my first activity.java
public class ToDoList extends AppCompatActivity implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.to_do_list);
// Navigator
FoldingTabBar tabBar = (FoldingTabBar) findViewById(R.id.folding_tab_bar);
tabBar.setOnFoldingItemClickListener(new FoldingTabBar.OnFoldingItemSelectedListener() {
#Override
public boolean onFoldingItemSelected(#NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_profile:
Intent intent0 = new Intent(ToDoList.this, Home.class);
startActivity(intent0);
break;
case R.id.menu_todo:
break;
case R.id.menu_schedule:
Intent intent1 = new Intent(ToDoList.this, TimeTable.class);
startActivity(intent1);
break;
case R.id.menu_settings:
break;
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
((TextView) findViewById(R.id.text_title)).setTypeface(TypefaceUtil.getAvenirTypeface(this));
mRecyclerView = (BatRecyclerView) findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(this, item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
}
I tried to use this code, from Mr Abhi instruction, I just edited a little bit for removing the toolbar, and some I solved.
This is my fragment.java
public class ToDoListFragment extends Fragment implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.todo_list_fragment, null);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
// you can add listener of elements here
/*Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(this); */
((TextView) view.findViewById(R.id.tdl_date)).setTypeface(TypefaceUtil.getAvenirTypeface(getActivity()));
mRecyclerView = (BatRecyclerView) view.findViewById(R.id.tdl_bat_recyclerView);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
view.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(getActivity(), item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
But it crushed when I started the app. the log showed that No view found for id 0x7f09004c (package:id/container) for fragment.
I hope you guys could help me as you teach me. Thanks for the second time.
To convert an Activity to a Fragment, you first have to extend Fragment. then you'll have to make some basic necessary changes in the code like:
1.onCreateView(LayoutInflater, ViewGroup, Bundle) instead of onCreate
2.findViewById() becomes getView().findViewById().
Your sample code:
public class ToDoList extends Fragment implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.todo_list_fragment, null);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
// you can add listener of elements here
/*Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(this); */
// Navigator
FoldingTabBar tabBar = (FoldingTabBar) view.findViewById(R.id.folding_tab_bar);
tabBar.setOnFoldingItemClickListener(new FoldingTabBar.OnFoldingItemSelectedListener() {
#Override
public boolean onFoldingItemSelected(#NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_profile:
Intent intent0 = new Intent(ToDoList.this, Home.class);
startActivity(intent0);
break;
case R.id.menu_todo:
break;
case R.id.menu_schedule:
Intent intent1 = new Intent(ToDoList.this, TimeTable.class);
startActivity(intent1);
break;
case R.id.menu_settings:
break;
}
return false;
}
});
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((TextView) view.findViewById(R.id.text_title)).setTypeface(TypefaceUtil.getAvenirTypeface(this));
mRecyclerView = (BatRecyclerView) view.findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
view.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(this, item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
}
I haven't edited all code and further changes maybe required. Do the changes accordingly.
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 want show website datas in 3 fragments with json! when swipe between TABs not duplicate datas. but when click on TABs, duplicate previous data again!
For send data from from AsyncTask to Fragments i use EventBus component.
Fragment codes:
public class free_fragment extends Fragment {
private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();
private Context context;
private boolean isDataFetched;
private boolean mIsVisibleToUser;
private View view;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_free_layout, container, false);
context = getContext();
if (mIsVisibleToUser) {
LoadData();
}
///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/
if (event.fragmentTag.equals("forfragment1")) {
mAdapter.add(dataModels);
isDataFetched = true;
mAdapter.notifyDataSetChanged();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
mIsVisibleToUser = isVisibleToUser;
if (isVisibleToUser && !isDataFetched && getContext() != null) {
context = getContext();
LoadData(); //Remove this call from onCreateView
}
}
private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
AsyncTask codes:
public class freeDataInfo {
private Context mContext;
private String ServerAddress = freeServer_IP.getFreeIP();
private DiskLruDataCache mDiskLruCache;
public void getFreeDataInfo(Context context) {
mContext = context;
this.mDiskLruCache=new DiskLruDataCache(context);
//new getInfo().execute(ServerAddress + "limit=10");
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels = new ArrayList<>();
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
//infoModels = new ArrayList<>();
// Initiate Progress
dialog = new ProgressDialog(mContext);
this.dialog.setMessage("شکیبا باشید...");
this.dialog.show();
infoModels.clear();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
//.url(ServerAddress + "limit=10")
.url(ServerAddress)
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
if(CheckInternet.isConnected(mContext)) {
response = client.newCall(request).execute();
ou_response = response.body().string();
if (ou_response != null) {
mDiskLruCache.cacheToDisk(ServerAddress, ou_response);
}
response.body().close();
}
else{
ou_response=mDiskLruCache.fetchFromDiskCache(ServerAddress);
}
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
for (int i = 0; i <= postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("full_description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("date");
String url = postObject.getString("url");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "Post url: " + url);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, url, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
//Stop Progress
if (dialog.isShowing()) {
dialog.dismiss();
}
if (result != null) {
bus.post(new MyEvent("forfragment1", infoModels));
} else {
Toast.makeText(mContext, "Check Internet", Toast.LENGTH_LONG).show();
}
}
}
}
Adapter Codes:
public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
private List<DataModel> mDateSet;
private Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public free_recycler_adapter(Context context, List<DataModel> dataSet) {
this.context = context;
this.mDateSet = dataSet;
}
// Create new views (invoked by the layout manager)
#Override
public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_card_layout, parent, false);
// create ViewHolder
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
viewHolder.free_titleText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
Glide.with(context)
.load(mDateSet.get(position).getImage())
.placeholder(R.drawable.ic_download_image)
.crossFade()
.into(viewHolder.free_avatarImage);
viewHolder.free_avatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));
viewHolder.free_descText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
.putExtra("title", mDateSet.get(position).getTitle())
.putExtra("desc", mDateSet.get(position).getDescription())
.putExtra("image", mDateSet.get(position).getImage())
.putExtra("url", mDateSet.get(position).getUrl())
.putExtra("category", mDateSet.get(position).getCategory())
.putExtra("date", mDateSet.get(position).getDate()));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<DataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<DataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView free_titleText, free_descText;
public ImageView free_avatarImage;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);
}
}
}
MainActivity codes:
public class Main_Page extends AppCompatActivity {
private CollapsingToolbarLayout mCollapsingToolbarLayout;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private DrawerLayout mDrawer;
private NavigationView nvDrawer;
private ImageView menuImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main__page);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/iransans.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
//mCollapsingToolbarLayout.setTitle(getResources().getString(R.string.app_name));
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.navigation_drawer);
menuImage = (ImageView) findViewById(R.id.DrawableMenu_image);
menuImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawer.openDrawer(GravityCompat.END);
}
});
}
/**
* Adding custom view to tab
*/
private void setupTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText(R.string.free_fragment_title);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_download_image, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText(R.string.paid_fragment_title);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_paid_download_image, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText(R.string.pdf_fragment_title);
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_pdf_icon, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
}
/**
* Adding fragments to ViewPager
*
* #param viewPager
*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new free_fragment(), "رایگان ها");
adapter.addFrag(new paid_fragment(), "پرداختی ها");
adapter.addFrag(new pdf_fragment(), "مقالات");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.END)) {
mDrawer.closeDrawers();
} else
super.onBackPressed();
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
How can i fix this and not duplicate datas when click on TabLayout ?
I am amateur and i really need this help, please help me. Thanks all<3
Check the commented code : It's causing the dataModels to be added every time to your adapter.
#Subscribe
public void onEvent(MyEvent event) {
List<DataModel> dataModels = event.getInfoModels();
if (event.fragmentTag.equals("forfragment1")) {
//mAdapter.add(dataModels);
isDataFetched = true;
mAdapter.notifyDataSetChanged();
}
}
In your adapter, in add() method, you are adding the data to the list all over again, this is unnecessary, calling notifyDataSetChanged automatically intimates the adapter that the original data has been changed.
Just call notifyDataSetChanged on adapter to refresh the updated data. Hope it helps.