This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
New to Android.i try to load fragment which insert value in SQLite database in View_Pager tab_Layout which is in Main_Activity.And tried to display data in 2nd fragment in view_pager 2nd tab.but it crashes when run the App..unable to load the fragment in view_pager . here is my code i don't know what is the problem in this code.why it is not loading.
public class MyAdapter extends FragmentPagerAdapter{
String[] name={"Insert","Show"};
#Override
public CharSequence getPageTitle(int position) {
return name[position];
}
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:InsertFragment im=new InsertFragment();
return im;
case 1:ShowFragment sm=new ShowFragment();
return sm;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
MyAdapter myAdapter;
MyDatabase m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout=(TabLayout) findViewById(R.id.tabLayout1);
viewPager=(ViewPager) findViewById(R.id.viewPager);
myAdapter=new MyAdapter(getSupportFragmentManager());
//viewPager.setCurrentItem(0);
viewPager.setAdapter(myAdapter);
tabLayout.setupWithViewPager(viewPager);
m=new MyDatabase(this);
m.open();
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();
}
});
}
protected void onDestroy() {
super.onDestroy();
m.close();
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
InsertFragment
public class InsertFragment extends Fragment {
EditText name,sub,email;
Button fill1;
public InsertFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_insert, container, false);
name=(EditText)v.findViewById(R.id.name);
sub=(EditText)v.findViewById(R.id.sub);
email=(EditText)v.findViewById(R.id.email);
fill1=(Button)v.findViewById(R.id.fill);
fill1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(name.getText().toString().equals("") || sub.getText().toString().equals("")||
email.getText().toString().equals(""))
{
Toast.makeText(getActivity(), "please Insert data", Toast.LENGTH_SHORT).show();
}
else {
String Name = name.getText().toString().trim();
String Subject = sub.getText().toString().trim();
String Email = email.getText().toString().trim();
MainActivity main = new MainActivity();
main.m.insertStudent(Name, Subject, Email);
name.setText("");
sub.setText("");
email.setText("");
name.requestFocus();
}
}
});
return v;
}
}
showfragment
public class ShowFragment extends Fragment {
RecyclerView rv;
LinearLayoutManager manager;
Cursor c;
MynewAdapter ma;
public class MynewAdapter extends RecyclerView.Adapter<MynewAdapter.ViewHolder>
{
#Override
public MynewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v=getActivity().getLayoutInflater().inflate(R.layout.row,parent,false);
ViewHolder vh=new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MynewAdapter.ViewHolder holder, int position) {
if(c!=null) {
c.moveToPosition(position);
int eno = c.getInt(0);
String name1 = c.getString(1);
String sub1=c.getString(2);
String email1=c.getString(3);
holder.tv1.setText("" + eno);
holder.tv2.setText(name1);
holder.tv3.setText(sub1);
holder.tv4.setText(email1);
}
}
#Override
public int getItemCount() {
if(c!=null)
{
return c.getCount();
}
else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tv1,tv2,tv3,tv4;
public CardView cv;
public ViewHolder(View itemView) {
super(itemView);
tv1=(TextView) itemView.findViewById(R.id.id);
tv2=(TextView) itemView.findViewById(R.id.name);
tv3=(TextView) itemView.findViewById(R.id.sub);
tv4=(TextView) itemView.findViewById(R.id.email);
cv=(CardView) itemView.findViewById(R.id.cv);
}
}
}
public ShowFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_show, container, false);
MainActivity mainActivity=(MainActivity) getActivity();
//mainActivity.m.insertEmp(ename,esal,edesig);
c=mainActivity.m.queryStudent();
ma.notifyDataSetChanged();
rv=(RecyclerView) v.findViewById(R.id.rv);
manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
ma=new MynewAdapter();
rv.setAdapter(ma);
rv.setLayoutManager(manager);
return v;
}
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.sujalvivek.com.viewpagerdatabasrecyclerassignment, PID: 4931
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.sujalvivek.com.viewpagerdatabasrecyclerassignment.ShowFragment$MynewAdapter.notifyDataSetChanged()' on a null object reference
I think the reason your app crashed because of these lines
MainActivity main = new MainActivity();
main.m.insertStudent(Name, Subject, Email);
Instead of these code, you should use Callback. check this link
Your problem is here:
ma.notifyDataSetChanged();//NullPointerException here because ma is not created yet
rv=(RecyclerView) v.findViewById(R.id.rv);
manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
ma=new MynewAdapter();//put this to the top of this block
Related
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.
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);
}
I am using ViewPager inside my Navigation Drawer all are works fine in devices other than marshmallow devices. in marshmallow devices when i clicking toggle button or swiping the navigation drawer (in both direction) feel a stuck(glitch) in the flow, also when i swipe the viewpager into different tabs also found the stuckking. This was found only in marshmallow device. please help me,, thanks in advance....
this is my code
activity class
public class HomeActivity extends AppCompatActivity{
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeViewPagerFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new HomeViewPagerFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
}
return true;
}
});
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
}
ViewPager fragment
public class HomeViewPagerFragment extends Fragment {
ArrayList<Model> mArrayList= new ArrayList<>();
Model model;
TabLayout tabLayout;
ViewPager viewPager;
HomeViewPagerAdapter viewPagerAdapter;
public HomeViewPagerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_view_pager,container,false);
viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
// parsing and add datas into mArrayList
viewPagerAdapter = new HomeViewPagerAdapter(getActivity().getSupportFragmentManager(),mArrayList);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setOffscreenPageLimit(2);
// Give the TabLayout the ViewPager
viewPager.setCurrentItem(Credentials.homeTabSelected);
tabLayout = (TabLayout)rootView.findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab){
Credentials.homeTabSelected = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootView;
}
}
viewpager adapter
public class HomeViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Model> mArrayList = new ArrayList<>();
String tabTitles[] = new String[] { "tab1","tab2" };
public HomeViewPagerAdapter(FragmentManager fm, ArrayList<Model> arrayList) {
super(fm);
mArrayList = arrayList;
}
#Override
public Fragment getItem(int position) {
if(position==0) {
return new HomeCentralFragment();
}
else {
return HomeRecyclerFragment.newInstance(mArrayList);
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
HomeCentralFragment
public class HomeCentralFragment extends Fragment {
public HomeCentralFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_central,null);
//my code is here(buttons, click events etc...)
return rootView;
}
}
HomeRecyclerFragment
public class HomeRecyclerFragment extends Fragment {
RecyclerView recyclerView;
public static ArrayList<Model> mArrayList =new ArrayList<>();
Fragment fragment;
FragmentTransaction fragmentTransaction;
public static HomeRecyclerFragment newInstance(ArrayList<Model> arrayList){
HomeRecyclerFragment fragment = new HomeRecyclerFragment();
mArrayList = arrayList;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_recycler_view,null);
recyclerView = (RecyclerView)rootView.findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
//to make horizontal or vertical listview using recyclerview
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new HomeRecyclerAdapter(getActivity(), mArrayList);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child != null && gestureDetector.onTouchEvent(e)) {
Credentials.selectedPolititian = rv.getChildAdapterPosition(child);
Intent intent = new Intent(getContext(), PersonDetailActivity.class);
intent.putExtra("Class","HomeActivity");
intent.putExtra("array",mArrayList);
startActivity(intent);
getActivity().finish();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
return rootView;
}
}
HomeRecyclerAdapter
public class HomeRecyclerAdapter extends RecyclerView.Adapter<HomeRecyclerAdapter.ViewHolder> {
private ArrayList<Model> profiles;
Context mContext;
public HomeRecyclerAdapter(Context context, ArrayList<Model> profile) {
this.profiles = profile;
this.mContext = context;
}
#Override
public HomeRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_fragment_home_recycler, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(HomeRecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(profiles.get(i).getmName());
int length= profiles.get(i).getmDepartment().size();
int k;
String res ="";
for (k=0;k<length;k++){
res = res + profiles.get(i).getmDepartment().get(k)+"\n";
}
viewHolder.department.setText(res);
}
#Override
public int getItemCount() {
return profiles.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name, department;
//private ImageView imageView;
public ViewHolder(View view) {
super(view);
// imageView = (ImageView) view.findViewById(R.id.image);
name = (TextView) view.findViewById(R.id.p_name);
department = (TextView) view.findViewById(R.id.p_department);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
});
}
}
}
check view fragments layout, avoid .jpeg images (use .png images)...
check the view pager with some simple fragments, if it work smoothly check the layout views..
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
}
This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)
public class MainFragment extends Fragment{
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container, false);
adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Tab1Class tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
Tab2Class tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
Tab2Class:
public class Tab1Class extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tv1 = (TextView) rootView.findViewById(R.id.tv1);
writeText();
}
public void writeText(){
tv1.setText("TV1 text");
}
}
Tab1Class:
public class Tab2Class extends Fragment {
TextView tv2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
tv2 = (TextView) rootView.findViewById(R.id.tv2);
writeText();
}
public void writeText(){
tv2.setText("TV2 text");
}
}
.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
////////////////////////////Added////////////////////
public void callWrite(){
if(tab1 != null)
tab1.writeText();
if(tab2 != null)
tab2.writeText();
}
/////////////
.
.
.
Here's an alternative:
public class BlankFragment extends Fragment {
public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
public static final String EXTRA_STUFF = "this_is_stuff";
public static void notifyStuffHappening(Context context, String stuff){
Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
intent.putExtra(EXTRA_STUFF, stuff);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private StuffHappenedReceiver mStuffListener;
public static class StuffHappenedReceiver extends BroadcastReceiver {
final BlankFragment mFragment;
public StuffHappenedReceiver(BlankFragment fragment) {
this.mFragment = fragment;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {
mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
}
}
}
private void someStuffHappened(String stringExtra) {
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mStuffListener = new StuffHappenedReceiver(this);
}
#Override
public void onDetach() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
mStuffListener = null;
super.onDetach();
}
}
This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.
If the fragment is not attached, it won't be updated.
To update this fragment, call the static method "notifyStuffHappening"