Adapter is multiplying with the same data android - android

I have a SwitchTabActivty with 4 items. In my case, I use the second item to get some data from the web through a recyclerview. The problem is that when I press the fourth item (it contains a button that's starting an activity) and I go back to my second tab , my recycler view is multiplied with the same data again.
Switchtabactivity :
public class SwitchTabActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private boolean pressToExit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.weather_tab);
tabLayout.getTabAt(1).setIcon(R.drawable.events);
tabLayout.getTabAt(2).setIcon(R.drawable.details_tab);
tabLayout.getTabAt(3).setIcon(R.drawable.settings_tab);
setColorTab(tabLayout);
}
private void setColorTab(TabLayout tab) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors, null));
} else {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (!pressToExit) {
Toast.makeText(this, "Press back again to exit.", Toast.LENGTH_SHORT).show();
pressToExit = true;
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onResume() {
super.onResume();
pressToExit = false;
}
#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_switch_tab, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return WeatherFragment.newInstance(position);
case 1:
return EventFragment.newInstance(position);
case 2:
return OwnEventFragment.newInstance(position);
case 3:
return SettingsFragment.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Weather";
case 1:
return "Events";
case 2:
return "My Events";
case 3:
return "Settings";
}
return null;
}
}
EventFragment :
public class EventFragment extends Fragment implements EventResponse {
private String latitude, longitude;
private static final String ARG_SECTION_NUMBER = "section_number";
private RecyclerView eventList;
private EventAdapter adapter;
private TextView ifNullEvents;
private final ArrayList<EventData> eventsData = new ArrayList<>();
private UserDataBase db;
private List<String> latLonList;
private ProgressBar progressBar;
public EventFragment() {
}
public static EventFragment newInstance(int sectionNumber) {
EventFragment fragment = new EventFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.event_fragment, container, false);
initView(rootView);
db = new UserDataBase(getContext());
checkLocationChanged();
latLonList = db.getLatLon();
latitude = latLonList.get(0);
longitude = latLonList.get(1);
String EVENT_BRITE_URL_PARSE = "MY_URL";
String EVENT_BRITE_TOKEN = "MY_TOKEN";
new EventBriteApi(this, getContext()).execute(EVENT_BRITE_URL_PARSE + EVENT_BRITE_TOKEN);
setupRecyclerView();
setLocationMessage();
return rootView;
}
private void initView(View view) {
eventList = (RecyclerView) view.findViewById(R.id.event_recycler_view);
ifNullEvents = (TextView) view.findViewById(R.id.text_null_location);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar_event);
}
private void checkLocationChanged() {
if (WePrefs.isLocationChanged) {
eventsData.clear();
ifNullEvents.setText(getResources().getString(R.string.waiting_for_data));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
WePrefs.setIsLocationChanged(false);
} else {
progressBar.setVisibility(View.GONE);
ifNullEvents.setVisibility(View.GONE);
}
if (WePrefs.isNullEventLocation) {
ifNullEvents.setText(getResources().getString(R.string.no_events_found));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
WePrefs.setIsNullEventLocation(false);
}
}
private void setupRecyclerView() {
eventList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
eventList.setLayoutManager(linearLayoutManager);
adapter = new EventAdapter(getActivity(), eventsData);
adapter.setHasStableIds(true);
eventList.setAdapter(adapter);
}
#Override
public void onResume() {
checkLocationChanged();
setLocationMessage();
super.onResume();
}
private void setLocationMessage() {
if (eventsData.isEmpty()) {
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
} else {
ifNullEvents.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
progressBar.setVisibility(View.GONE);
}
#Override
public void getArray(ArrayList<EventData> data) {
eventsData.clear();
eventsData.addAll(new ArrayList<>(new LinkedHashSet<>(data)));
}
}
Adapter :
ublic class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventHolder> {
ArrayList<EventData> data;
Context context;
public EventAdapter(Context context, ArrayList<EventData> events) {
this.context = context;
data = events;
}
#Override
public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RelativeLayout layout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.single_event_view, parent, false);
return new EventAdapter.EventHolder(layout);
}
#Override
public void onBindViewHolder(EventHolder holder, int position) {
holder.eventName.setText(data.get(position).getEventName());
if (data.get(position).getEventImageUrl() != null) {
Picasso.with(context).load(data.get(position).getEventImageUrl()).into(holder.eventPic);
} else {
holder.eventPic.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.no_image));
}
}
#Override
public int getItemCount() {
return data.size();
}
public class EventHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView eventName;
ImageView eventPic;
RelativeLayout layout;
public EventHolder(View itemView) {
super(itemView);
eventName = (TextView) itemView.findViewById(R.id.event_name);
eventPic = (ImageView) itemView.findViewById(R.id.event_image);
layout = (RelativeLayout) itemView.findViewById(R.id.event_layout);
layout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
//context.startActivity(new Intent(context, WebViewActivity.class));
}
}
}
Those are some of my java classes that I use for this kind of thing.
Anyway, another problem is that, when I change the location ( to receive my events) I must go to another tab and after that to come back to see my events list ( I think it needs to recreate the view ) so , because of that I called onResume, but it does not help.

Related

how to fix" 3 fragment in One activity with viewPager need validation first two page then possible to go third page"

I want to create a createOrderActivity where has three fragments like Service info, ScheduleInfo, confirmation
the service info fragment has editText
if click NextButton(which is situated CreateOrderActivity) check validation editText first. then move ScheduleFragment page.
if first two pages validation ok then move to Confirmation Fragment page.
Here is the FragmentViewpagerAdapter class
public class FragmentViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public FragmentViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
In CreateOrderActivity class
#Override
public void onPageSelected(int position) {
boolean checkSch= false;
if (position == 1) {
ServiceInfoFragment serviceInfoFragment = new ServiceInfoFragment();
//checking validation from ServiceInfoFragment fragment Class
if (serviceInfoFragment.checkServiceValidation()) {
checkSch = true;
//Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
}else {
checkSch = false;
// Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-1);
}
}
if (position == 2) {
if (checkSch){
ScheduleFragment scheduleFragment = new ScheduleFragment();
if (scheduleFragment.checkScheduleValidation()) {
Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(CreateOrderActivity.this, "Please check S validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-1);
}
}else {
Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-2);
}
}
}
//checking checkScheduleValidation() in ScheduleFragment class. return null exception
*bellow mehtod declear in Fragment *
public boolean checkServiceValidation(){
return true;
}
I upload this Image
I used this Reference
I found a solution in my way. I have loaded three fragments in a viewpager. In the second fragment, there is one edittext. on clicking the next button, there is a validation for checking email. On the basis of validation next fragment is loaded. All the Fragments are loaded as singleton . You might have caused null pointer exception , because of multiple instance of fragments.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private FragmentTwo fragmentTwo;
private ViewPager mViewPager;
Button back, next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
back = findViewById(R.id.back);
next = findViewById(R.id.next);
next.setOnClickListener(this);
back.setOnClickListener(this);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.vp_viewpager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
if (i==2){
if (!fragmentTwo.checkEditText()) {
Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_LONG).show();
mViewPager.setCurrentItem(i-1);
return;
}
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private void changeViewPagerPosition(int position) {
int totalCount = mViewPager.getAdapter().getCount();
if (position < 0 || position >= totalCount) {
return;
}
mViewPager.setCurrentItem(position);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View view) {
int currentViewpagerPosition = mViewPager.getCurrentItem();
switch (view.getId()) {
case R.id.back:
changeViewPagerPosition(currentViewpagerPosition - 1);
break;
case R.id.next:
if (currentViewpagerPosition==1){
if (!fragmentTwo.checkEditText()) {
Toast.makeText(getApplicationContext(),"Falsee",Toast.LENGTH_LONG).show();
return;
}
}
changeViewPagerPosition(currentViewpagerPosition + 1);
break;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentOne.newInstance(position);
case 1:
return fragmentTwo=FragmentTwo.getInstance();
case 2:
return FragmentThree.newInstance(position);
default:
return FragmentThree.newInstance(position);
}
}
#Override
public int getCount() {
return 3;
}
}
}
The Fragment 2
public class FragmentTwo extends Fragment {
EditText email;
private static FragmentTwo fragment=null;
public FragmentTwo() {
}
public static FragmentTwo getInstance() {
if (fragment == null){
fragment = new FragmentTwo();
}
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
email = getView().findViewById(R.id.editText);
}
public boolean emailValidator()
{
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-" +
"9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email.getText().toString());
return matcher.matches();
}
public Boolean checkEditText(){
if (emailValidator()){
return true;
}
return false;
}
}

how to not load all tab in FragmentStatePagerAdapter

i have a Page adapter that i called in activity,
it have 3 tabs , each tabs call a web service to full fill the ListView. besides, i have a sharedpreference to in every tabs.
the problem is, when i access the page from index, it took me a long time and in the log cat said that "I/Choreographer: Skipped 633 frames! The application may be doing too much work on its main thread."
I assume its because they load the 3 tab at the same time, so the it make the process more hard. is there any way to do load tabs only whenever i clicked that tab ?
page adapter class
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
private Context context;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
MyRequest myReq = new MyRequest();
return myReq;
case 1:
ListApproval myApp = new ListApproval();
return myApp;
case 2:
ListApprovalHistory myAppHis = new ListApprovalHistory();
return myAppHis;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
List Activity :
public class Workflow extends AppCompatActivity{
private static String URLService;
private static final String ARG_SECTION_NUMBER = "section_number";
private static String userId;
private static String DirectSuperiorName;
private static String rowsPerPage;
private static SharedPreferences pref;
boolean _areLecturesLoaded = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workflow_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("My Request"));
tabLayout.addTab(tabLayout.newTab().setText("My Approval"));
tabLayout.addTab(tabLayout.newTab().setText("My Approval History"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(0);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
URLService = getString(R.string.URLService);
getSuperior();
//GET SESSION USERID
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", "");
rowsPerPage = pref.getString("rowsPerPage","");
DirectSuperiorName = pref.getString("DirectSuperiorName","");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_workflow, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Intent intent = new Intent(this, Index.class);
startActivity(intent);
return true;
case 0:
getSuperior();
if(DirectSuperiorName != "") {
SharedPreferences.Editor editor = pref.edit();
editor.putString("PageType", "NewRequest");
editor.commit();
Intent i = new Intent(Workflow.this, WorkflowActivity.class);
startActivity(i);
}
else
{
AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
builder2.setMessage("Cannot create new request, Please set DirectSuperior !")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder2.create();
builder2.show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.add(Menu.NONE,0,0,"Create New").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
/*if(DirectSuperiorName != ""){
menu.add(Menu.NONE,0,0,"Create New").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
else{
menu.clear();
}*/
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onBackPressed() {
Intent i = new Intent(this, Index.class);
startActivity(i);
super.onBackPressed();
}
}
this is my fragment child code:
public class ListApproval extends android.support.v4.app.Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private static String userId;
private static String rowsPerPage;
private SwipeRefreshLayout swipeContainer;
private List<ListApprovalItem> mItems;
private ListApprovalItem item;
private static SharedPreferences pref;
private Handler mHandler;
private static String URLService;
private String Enc_Pass="";
private boolean isDataLoaded;
// TODO: Rename and change types of parameters
public static ListApproval newInstance(int sectionNumber) {
ListApproval fragment = new ListApproval();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public ListApproval() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list_approval, container, false);
setHasOptionsMenu(true);
this.mHandler = new Handler();
this.mHandler.postDelayed(getData,500);
URLService = getString(R.string.URLService);
Enc_Pass = getString(R.string.password_encryption);
//GET SESSION USERID
pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", getActivity().MODE_PRIVATE);
userId = pref.getString("userId", "");
rowsPerPage = pref.getString("rowsPerPage","");
final ListView lv = (ListView) view.findViewById(R.id.lvApproval);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new BigProccess(getActivity(), ProgressDialog.STYLE_SPINNER).execute();
item = new ListApprovalItem();
item = mItems.get(position);
SharedPreferences.Editor editor = pref.edit();
editor.putString("PermitID", item.permitid);
editor.putString("PageType", "MyApproval");
editor.putString("LeaveType", item.tipe);
editor.commit();
Intent i = new Intent(getActivity(), WorkflowActivity.class);
getActivity().startActivity(i);
}
});
getApprovalList(); // i call my api here , when oncreateview start
if (mItems==null)
{
/* Toast.makeText(getActivity().getApplicationContext(), "Internet connection appears to be offline",
Toast.LENGTH_LONG).show();*/
}
else
{
lv.setAdapter(new ListApprovalAdapter(getActivity(), mItems));
}
swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getApprovalList();
if (mItems==null)
{
/* Toast.makeText(getActivity().getApplicationContext(), "Internet connection appears to be offline",
Toast.LENGTH_LONG).show();*/
}
else
{
lv.setAdapter(new ListApprovalAdapter(getActivity(), mItems));
}
swipeContainer.setRefreshing(false);
}
});
return view;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#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 == 0) {
/* SharedPreferences.Editor editor = pref.edit();
editor.putString("PageType", "ApprovalHistory");
editor.commit();
Fragment newFragment = ListApprovalReimbursementHistory.newInstance(6);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.flApproval, newFragment).commit();*/
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
// getActivity().getMenuInflater().inflate(R.menu.index, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
// menu.clear();
// menu.add(Menu.NONE,0,0,"History").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
super.onPrepareOptionsMenu(menu);
}
private final Runnable getData = new Runnable() {
#Override
public void run() {
getApprovalList();
}
};
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
//getListView().setDivider(null);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
}
i am not sure where is the problem,
can you guys help me ?
any help would be appreciate
One way is to override setUserVisibleHint method of Fragment -
Adding piece of code how you should do that,
public class ListApproval extends android.support.v4.app.Fragment {
private boolean isDataLoaded;
public static ListApproval newInstance(int sectionNumber) {
ListApproval fragment = new ListApproval();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list_approval, container, false);
setHasOptionsMenu(true);
// Do your UI related stuffs here...
return view;
}
/*
* Set a hint to the system about whether this fragment's UI is currently visible to the user.
*/
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// isDataLoaded is to prevent multiple calls
if (isVisibleToUser && !isDataLoaded ) {
loadData(); // Make an api call to bind data into your list
isDataLoaded = true;
}
}
}
More about setUserVisibleHint() Click here

Update RecyclerView from menu

I have a MainActivity with two fragments. The second fragment has RecyclerView. There is TextView ( lesson name) and ImageView(show lesson status, if it is done or not) in RecyclerView . When you click TextView, it calls another Activity with lesson. After you make the lesson you will go back to MainActivity. After that lessons ImageView will be changed from nothing to resourse 'ic_lessondone'. Also there is a menu in MainActivity. Menu have item 'Reset lessons'. When you press 'Reset lessons' all ImageViews wont show any images. So there are two problems. 1) if I do, for example , only 6th lesson. I will have image 'lessondone'. When i press 'Reset lessons' image will disappear. But when i go back to menu again and press 'Reset lessons', Image will appear again and rise to previous lesson ( 5th). 2) If i switch off display, image will also appear to previous lessons till to 0th.
Its seems i have a problem with onResume.
Help me please.
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null)
{
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
{
setupViewPager(viewPager);
}
// Круглая кнопка
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Картинки для табов
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
switch (AppCompatDelegate.getDefaultNightMode())
{
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
}
return super.onOptionsItemSelected(item);
}
private void setNightMode(#AppCompatDelegate.NightMode int nightMode)
{
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11)
{
recreate();
}
}
private void setupViewPager(ViewPager viewPager)
{
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Fragment(), "");
adapter.addFragment(new LessonsListFragment(), "");
viewPager.setAdapter(adapter);
}
// Главное меню
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
if (menuItem.getTitle().equals("Reset lessons"))
{
// Обнуляем файл с рузультатами уроков
LessonsListFragment.sLessonsPref.edit().clear().commit();
// Перерисовываем весь писок уроков
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
// Получаем конкретный фрагмент
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
// Количество фрагментов для viewpager (2)
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
}
Fragment
public class LessonsListFragment extends Fragment
{
// Уроки
// static private Map<String,?> mLessonsKeys ;
static SharedPreferences sLessonsPref;
static RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
loadSharedPreferenses();
rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
// Загружаем список пройденных уроков
public void loadSharedPreferenses()
{
sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
}
// Количество строк в листе
private void setupRecyclerView(RecyclerView recyclerView)
{
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
}
// Задаем Строки
private List<String> getRandomSublist(String[] array, int amount)
{
ArrayList<String> list = new ArrayList<>(amount);
//Random random = new Random();
while (list.size() < amount)
{
list.add(array[list.size()]);
}
return list;
}
//Отработка перерисования окна, при возврате к ней
#Override
public void onResume()
{
super.onResume();
//loadSharedPreferenses();
//Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
if (rv.getAdapter() != null)
{
rv.getAdapter().notifyDataSetChanged();
}
}
// Адаптер
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
{
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
public static class ViewHolder extends RecyclerView.ViewHolder
{
// Номер урока, передается в webactivity
public int mLessonNumber;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view)
{
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString()
{
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position)
{
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
{
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
// Создаем холдер с полезной нагрузкой
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
//Создаем список уроков
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.mLessonNumber = position + 1;
// Увеличиваем позицион на 1 что не было 0 урока
holder.mTextView.setText((position + 1) + " " + mValues.get(position));
// Если урок пройден
String finished = sLessonsPref.getString((position + 1) + "", "");
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
//.load(Cheeses.getRandomCheeseDrawable())
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
holder.mTextView.setTextColor(R.color.black);
// holder.mImageView.setVisibility(View.GONE);
}
// Вызов WebActivity
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Context context = v.getContext();
Intent intent = new Intent(context, WebActivity.class);
// Передаем вебвью номер урока и запускаем ее
intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
context.startActivity(intent);
}
});
}
// Определяем количество выводимых строк
#Override
public int getItemCount()
{
return mValues.size();
}
}
}
Implement a reset() method in the adapter that mark all items as "not done" and then try:
LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();
instead of:
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
inside onNavigationItemSelected.
Also, you shouldn't be using static variables (like static RecyclerView rv), use private vars with getters
The problem was in else statement. I added there this code, and now its ok. notifydatachanged work correctly from navigationview
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
Glide.with(holder.mImageView.getContext()).load(R.color.white)
.fitCenter()
.into(holder.mImageView);
holder.mTextView.setTextColor(R.color.black);
}

Created a gridview in a tablayout and try to update Gridview with a Intent service

I have created a Tabbed layout in a Activity. My Activity as following point for consideration
1. Number of tabs depends on sorting type available for a Source object. There can be max three tabs i.e. Top, Latest and popular.
2. Each tab contains a GridView and it should be updated when IntentService gets data
3. User can choose the Source from toolbar
4. When new Source is selected, number of tabs should be according to new Source and GridView should also update accordingly
TabbedActivity
public class TabbedActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager mViewPager;
private List<Source> allSourceItem;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
context = this;
// register broadcast
IntentFilter statusIntentFilter = new IntentFilter(Asset.ARTICLE_BROADCAST_ACTION);
TabbedActivity.ArticleStateReceiver mDownloadStateReceiver = new TabbedActivity.ArticleStateReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(mDownloadStateReceiver, statusIntentFilter);
// set toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// set tab layout
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
// set the viewpager
mViewPager = (ViewPager) findViewById(R.id.container);
// set up page listner to viewpager
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
startSetUp(getRecentDisplayedData());
}
public void startSetUp(Source src){
int tabsCount = 3;
setTitle(src.getName());
tabsCount = getNumberOfTabs(src.getSortByAvailableTop(),src.getSortByAvailableLatest(),src.getSortByAvailablePopular());
setTabs(tabsCount);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(),tabsCount,src));
}
// handle menus of activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tabbed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SourcesActivity.class);
intent.putExtra("SOURCE_ACTIVITY_ACTION","TABBED");
startActivity(intent);
return true;
}
if(id == R.id.change_src){
//get all selected sources
allSourceItem = Source.getAll();
List<String> listItems = new ArrayList<String>();
for(int i = 0; i < allSourceItem.size(); i++ ){
listItems.add(allSourceItem.get(i).getName());
}
final CharSequence[] items = listItems.toArray(new CharSequence[listItems.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.chnage_news_source);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Source.updateRecentDisplayed(allSourceItem.get(item));
restartActivity();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return super.onOptionsItemSelected(item);
}
// for creatting tabs Fragments
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private GridView mGridView;
private ArticleAdapter mArticleAdapter;
private ArrayList<Article> mGridData = new ArrayList<Article>();
private TextView tv;
private static final String ARG_SECTION_NUMBER = "section_number";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabbed, container, false);
tv = (TextView) rootView.findViewById(R.id.test_tv);
tv.setText("Page counter :: "+getArguments().getInt(ARG_SECTION_NUMBER));
mGridView = (GridView) rootView.findViewById(R.id.article_grid);
update(mGridData);
return rootView;
}
public void update(ArrayList<Article> data){
mArticleAdapter = new ArticleAdapter(getContext(),R.layout.aricle_grid_element,data);
mGridView.setAdapter(mArticleAdapter);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int tabsCount;
Source src;
public SectionsPagerAdapter(FragmentManager fm, int tabsCount, Source src) {
super(fm);
this.tabsCount = tabsCount;
this.src = src;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
if( position == 0){
runArticleService(position+1);
return PlaceholderFragment.newInstance(position + 1);
}else if (position == 1){
runArticleService(position+1);
return PlaceholderFragment.newInstance(position + 1);
}else if (position == 2){
runArticleService(position+1);
return PlaceholderFragment.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return tabsCount;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
private void runArticleService(int tabNumber){
Intent mServiceIntent = new Intent(getBaseContext(), ArticleService.class);
mServiceIntent.setData(Uri.parse(Asset.getSourceArticleURL(src.getUniqueId(),tabNumber)));
startService(mServiceIntent);
}
}
// broadcast receivers handle
private class ArticleStateReceiver extends BroadcastReceiver
{
private ArticleStateReceiver() {
}
// Called when the BroadcastReceiver gets an Intent it's registered to receive
#Override
public void onReceive(Context context, Intent intent) {
String response = intent.getStringExtra(Asset.ARTICLE_EXTENDED_DATA_TYPE);
String sortType = intent.getStringExtra(Asset.ARTICLE_EXTENDED_DATA_SORT);
if(sortType.equals("TOP")){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) sectionsPagerAdapter.getItem(0);
placeholderFragment.update(Asset.getArticleObjectFromJSON(response.toString()));
}else if(sortType.equals("LATEST")){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) sectionsPagerAdapter.getItem(1);
placeholderFragment.update(Asset.getArticleObjectFromJSON(response.toString()));
}else if(sortType.equals("POPULAR")){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) sectionsPagerAdapter.getItem(2);
placeholderFragment.update(Asset.getArticleObjectFromJSON(response.toString()));
}
}
}
// Extra methods
private int getNumberOfTabs(boolean top, boolean latest, boolean popular ){
if( top && latest && popular){
return 3;
}else if( top && latest && !popular ){
return 2;
}else if( top && !latest && !popular ){
return 1;
}else{
return 1;
}
}
private void setTabs(int tabCount){
tabLayout.removeAllTabs();
if(tabCount == 3){
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_1_text)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_2_text)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_3_text)));
}
if(tabCount == 2){
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_1_text)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_2_text)));
}
if(tabCount == 1){
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_1_text)));
}
}
private Source getRecentDisplayedData(){
Source src = Source.getRecentDisplayed();
if(src!=null){
return src;
}else{
src = Source.getRandom();
Source.updateRecentDisplayed(src);
return Source.getRecentDisplayed();
}
}
public void restartActivity(){
Intent myIntent = new Intent(this, TabbedActivity.class);
startActivity(myIntent);
finish();
}
}
IntentService
public class ArticleService extends IntentService {
public String responseStr = null;
public String urlStr = null;
public ArticleService() {
super("ArticleService");
}
#Override
protected void onHandleIntent(Intent intent) {
Uri url = intent.getData();
urlStr = url.toString();
responseStr = Asset.fetchSourceDataFromURL(urlStr);
sendBroadcast();
}
protected void sendBroadcast(){
Intent localIntent = new Intent(Asset.ARTICLE_BROADCAST_ACTION).putExtra(Asset.ARTICLE_EXTENDED_DATA_TYPE,responseStr);
if(urlStr.toLowerCase().contains(Asset.SORT_TOP_URL.toLowerCase())){
localIntent.putExtra(Asset.ARTICLE_EXTENDED_DATA_SORT,"TOP");
}else if (urlStr.toLowerCase().contains(Asset.SORT_LATEST_URL.toLowerCase())){
localIntent.putExtra(Asset.ARTICLE_EXTENDED_DATA_SORT,"LATEST");
}else if (urlStr.toLowerCase().contains(Asset.SORT_POPULAR_URL.toLowerCase())){
localIntent.putExtra(Asset.ARTICLE_EXTENDED_DATA_SORT,"POPULAR");
}
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
}
Error that I am not able to understand
01-26 07:57:29.789 1494-1494/in.co.yogender.newsnick.newsnick E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.co.yogender.newsnick.newsnick, PID: 1494
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.view.LayoutInflater.from(LayoutInflater.java:232)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:181)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
at in.co.yogender.newsnick.newsnick.Adapters.ArticleAdapter.<init>(ArticleAdapter.java:0)
at in.co.yogender.newsnick.newsnick.TabbedActivity$PlaceholderFragment.update(TabbedActivity.java:197)
at in.co.yogender.newsnick.newsnick.TabbedActivity$ArticleStateReceiver.onReceive(TabbedActivity.java:273)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Thanks in advance
I think, you are updating GridView from IntentService where Context is null. Try to pull context from IntentService like below and let me know.
public void update(Context cont, ArrayList<Article> data){
mArticleAdapter = new ArticleAdapter(cont, R.layout.aricle_grid_element,data);
mGridView.setAdapter(mArticleAdapter);
}

ViewPager does not updating the Fragment with updated content

i am suffering for 3 days. I'm using the View Pager from the compatibility library. I have successfully got it displaying several views .My Problem is that when i swap view then do not update data by fragment in its recycler view .But when i closed my application then opened fragments display update content by recycler view.i use all method like setnotifydatachanged() and many more but Fragment in viewpager does not update content.Thankx For any help
this is my main activity
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new MainAdapter(getSupportFragmentManager(),MainActivity.this));
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
addIconsToTab();
}
private void addIconsToTab() {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
int drwableId = -1;
switch (i) {
case 0:
drwableId = R.drawable.home;
break;
case 1:
drwableId = R.drawable.favourite;
break;
case 2:
drwableId = R.drawable.watchlater;
break;
}
tabLayout.getTabAt(i).setIcon(drwableId);
}
}
}
this is my main adapter
public class MainAdapter extends FragmentPagerAdapter {
Context mContext;
public MainAdapter(FragmentManager fm, Context context) {
super(fm);
mContext=context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new AllVideos();
case 1:
return new Favourite();
case 2:
return new WatchLater();
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return mContext.getString(R.string.All_Videos);
case 1:
return mContext.getString(R.string.Favourite);
case 2:
return mContext.getString(R.string.Wtach_Later);
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And this is my Fragment
public class Favourite extends Fragment {
private RecyclerView mRecyclerView;
private FavouriteAdapter favouriteAdapter;
RecyclerView.LayoutManager layoutManager;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview_carpaccio, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
DatabaseHandler db = new DatabaseHandler(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
List<VideoInformationDataModel> videoinfo = db.getAllFavourite();
favouriteAdapter = new FavouriteAdapter(getActivity(),videoinfo);
mRecyclerView.setAdapter(favouriteAdapter);
favouriteAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(),videoinfo.size()+"",Toast.LENGTH_SHORT).show();
}
}
And this is fragmentAdapter
public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.MyViewHolder>
{
private int[] maid = {R.id.deleteoption};
Context context;
private List<VideoInformationDataModel> videoInformationDataModels;
String videoid1;
private FavouriteAdapter favouriteAdapter;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
View root;
protected ImageLoader img_uni_imageLoader;
DatabaseHandler db = new DatabaseHandler(context);
ImageView networkImage,options;
TextView Duration,Videoname;
public MyViewHolder(View view) {
super(view);
root = itemView.findViewById(R.id.videoImage);
Duration= (TextView) itemView.findViewById(R.id.duration);
Videoname= (TextView) itemView.findViewById(R.id.VideoName);
networkImage= (ImageView) itemView. findViewById(R.id.imgNetwork);
options= (ImageView) itemView.findViewById(R.id.deleteoption);
options.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (maid[0] == view.getId()) {
PopupMenu popup = new PopupMenu(context, options);
popup.getMenuInflater().inflate(R.menu.deleteoption, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.delete:
int pos = getAdapterPosition () ;
videoid1= videoInformationDataModels.get(pos).getVideoid();
db.deleteFavourite(videoid1);
videoInformationDataModels.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, getItemCount());
return true;
}
return false;
}
});
popup.show();
}
}
}
public FavouriteAdapter(Context context, List<VideoInformationDataModel> videoinformation) {
this.videoInformationDataModels = videoinformation;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favouritesingleitem, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.Duration.setText(videoInformationDataModels.get(position).getVideoduratio n());
holder.Videoname.setText(videoInformationDataModels.get(position).getVideoinfo() );
holder.img_uni_imageLoader = ImageLoader.getInstance();
.img_uni_imageLoader.init(ImageLoaderConfiguration.createDefault(context));
holder.img_uni_imageLoader.displayImage(videoInformationDataModels.get(position) .getVideoimg(), holder.networkImage);
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, YouTube.class);
Bundle extras = new Bundle();
String Videtittle = videoInformationDataModels.get(position).getVideoinfo();
String videodes = videoInformationDataModels.get(position).getFld_description();
String duration = videoInformationDataModels.get(position).getVideoduration();
String videoid = videoInformationDataModels.get(position).getVideoid();
extras.putString("Videtittle", Videtittle);
extras.putString("videodes", videodes);
extras.putString("duration", duration);
extras.putString("videoid", videoid);
intent.putExtras(extras);
context.startActivity(intent);
}
});
}
#Override
public int getItemViewType(int position)
{
return position;
}
public int getItemCount() {
return videoInformationDataModels.size();
}
}
I am not very sure what issue you are facing, but can you try once by replacing the FragmentPagerAdapter by FragmentStatePagerAdapter (extending by MainAdapter).
I don't clearly understand exactly what your issue is, It might be a result of wrong implementation. But if you have tried favouriteAdapter.notifyDataSetChanged(); and it still doesn't refresh.
You might as well remove the view, refresh it and add the view back and see if that works.
ViewGroup parent = (ViewGroup) viewPager.getParent(); // get the view parent
if (parent != null) {
parent.removeView(viewPager); // remove the view
viewPager.getAdapter().notifyDataSetChanged(); // notify that the data has changed
parent.addView(viewPager); // then, re-add the view
}

Categories

Resources