i am getting the null pointer exception in adapter - android

I am using listview to inflate navigation menu. I am getting the above error when
main activity is launched. I am sharing the code of adapter and main activity.
public class DrDrawerListAdapter extends BaseAdapter {
Activity activity;
int[] imageId;
private LayoutInflater inflater = null;
ArrayList<String> titles;
public DrDrawerListAdapter(Activity activity, ArrayList<String> titles, int[] icons){
this.titles= titles;
this.activity = activity;
this.imageId = icons;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return titles.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
View view = inflater.inflate(R.layout.dr_drawer_item, null);
holder.iconView = view.findViewById(R.id.im_icon);
holder.titleView = view.findViewById(R.id.tv_title);
holder.titleView.setText(titles.get(position));
Glide.with(activity.getApplicationContext()).load(imageId[position]).into(holder.iconView);
return view;
}
public class Holder{
ImageView iconView;
TextView titleView;
}
}
*** and here is my mainactivity file
package com.example.azim.qphew.Dr.view.uiactivity;
import butterknife.BindView;
import butterknife.ButterKnife;
public class DrMainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = DrMainActivity.class.getSimpleName();
#BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
//NavigationView navigationView;
#BindView(R.id.toolbar) Toolbar toolbar;
#BindView(R.id.lv_drawer) ListView listView;
#BindView(R.id.dr_profile) ImageButton profileButton;
#BindView(R.id.dr_schedule) ImageButton scheduleButton;
#BindView(R.id.live) ImageButton liveButton;
#BindView(R.id.dr_message) ImageButton messageButton;
#BindView(R.id.dr_logout) ImageButton logoutButton;
private ActionBar actionBar;
ArrayList<String> nav_items;
int[] icons = {R.drawable.time, R.drawable.appointment_history, R.drawable.live_appointment, R.drawable.medicine_reminder,
R.drawable.video, R.drawable.blog, R.drawable.faq, R.drawable.live_appointment};
DrDrawerListAdapter listAdapter;
ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dr_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_bar_color)));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.commit();
setDrawer();
init();
initClickListener();
}
private void setDrawer(){
if (toggle == null){
toggle = new ActionBarDrawerToggle(DrMainActivity.this,drawerLayout,R.string.open, R.string.close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
drawerLayout.addDrawerListener(toggle);
}
toggle.syncState();
listAdapter = new DrDrawerListAdapter(DrMainActivity.this, nav_items, icons);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new DrDrawerItemClickListener());
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.live:
setLiveQueue();
break;
case R.id.dr_profile:
setProfile();
break;
case R.id.dr_schedule:
setSchedule();
break;
case R.id.dr_message:
setMessage();
break;
case R.id.dr_logout:
setLogout();
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}switch (item.getItemId()){
default:
return super.onOptionsItemSelected(item);
}
}
private class DrDrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position){
switch (position){
case 0:
setDashBoard();
drawerLayout.closeDrawers();
break;
case 1:
setAppointment();
drawerLayout.closeDrawers();
break;
case 2:
setLiveQueue();
drawerLayout.closeDrawers();
break;
case 3:
setMessage();
drawerLayout.closeDrawers();
break;
case 4:
setVideos();
drawerLayout.closeDrawers();
break;
case 5:
setBlog();
drawerLayout.closeDrawers();
break;
}
}
}
private void initClickListener(){
profileButton.setOnClickListener(this);
scheduleButton.setOnClickListener(this);
liveButton.setOnClickListener(this);
messageButton.setOnClickListener(this);
logoutButton.setOnClickListener(this);
}
private void init(){
nav_items = new ArrayList<>();
nav_items.add("My Account");
nav_items.add("Search");
nav_items.add("Live Appointmet");
nav_items.add("My Appointments");
nav_items.add("Upgrade to Premium");
nav_items.add("FAQ");
nav_items.add("Vedios");
nav_items.add("Blog");
//icons = getResources().getIntArray(R.array.dr_drawer_icons);
}
private void setDashBoard(){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setAppointment(){}
private void setProfile(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_main, new DrProfileFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setLiveQueue(){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DrLiveQueueFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setVideos(){}
private void setMessage(){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DrMessageFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setLogout(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_main, new DrLogoutFragment());
ft.addToBackStack(null);
ft.commit();
}
private void setBlog(){}
private void setFaq(){}
private void setContactUs(){}
private void setSchedule() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DrScheduleFragment());
ft.addToBackStack(null);
ft.commit();
}
}

you should initial your array before call setDrawer method
change init() order line with setDrawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dr_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.app_bar_color)));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.commit();
init();
setDrawer();
initClickListener();
}

Call init() before setDrawer method.Before initialising the arraylist you are setting adapter with null
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dr_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new
ColorDrawable(getResources().getColor(R.color.app_bar_color)));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.menu);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_main, new DashboardFragment());
ft.commit();
init();
setDrawer();
initClickListener();

Related

ViewPager crashes when re-opening: NullPointerException SparseArray.get(int)

I've recently switched my ViewPager's adapter from FragmentPagerAdapter to FragmentStatePagerAdapter. However, whenever I return to my ViewPager the app crashes. This was not happening with FragmentPagerAdapter. The Logcat shows:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.util.SparseArray.get(int)' on a null object reference
I'm in that awkward position where I don't know enough to understand what questions I should be asking. All of my searches have turned up nothing useful.
Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.util.SparseArray.get(int)' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:905)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:216)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1455)
at android.view.View.dispatchRestoreInstanceState(View.java:17706)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3745)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3751)
at android.view.View.restoreHierarchyState(View.java:17684)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:415)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1454)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
MainActivity.java
public class MainActivity extends AppCompatActivity
implements FragmentQuiz_Selection_Instruments.QuizSelectionInterface,
FragmentQuiz_Started.OnQuizExit,
FragmentQuiz_Selection_Topics.StartQuizInterface {
private DrawerLayout mDrawerLayout;
private Fragment mQuizFragment;
private Fragment mInstrumentsFragment;
private Fragment mReferenceFragment;
private ArrayList<String> mQuizSelection;
private ViewModel_ForegroundView viewModel;
private BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialise mQuizSelection
mQuizSelection = new ArrayList<String>();
mQuizSelection.clear();
//Initialise bottomNavigationView
bottomNavigationView = findViewById(R.id.navigation_bottom);
//Set Bottom-Navigation icon
bottomNavigationView.getMenu().getItem(1).setChecked(true);
//Initialise ViewModel_ForegroundView
viewModel = ViewModelProviders.of(this).get(ViewModel_ForegroundView.class);
//Initialise ActionBar
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
//Initialise Top-Navigation Drawer
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.navigation_top);
// Set the onClickListener for the NavigationDrawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// set item as selected to persist highlight
item.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Handle item clicks
int itemId = item.getItemId();
if (itemId == R.id.nav_top_ww) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_WWind");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_WWind.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_WWind");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_br) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_Brass");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_Brass.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_Brass");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_pp) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_PercPit");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_PercPit.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_PercPit");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_pu) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_PercUnp");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_PercUnp.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_PercUnp");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_sp) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_StrPlu");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_StrPlu.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_StrPlu");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_ky) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_Keys");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_Keys.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_Keys");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
} else if (itemId == R.id.nav_top_sb) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_StrBow");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_StrBow.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_StrBow");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, mInstrumentsFragment);
transaction.commit();
//Record foreground-fragment change
viewModel.recordForegroundFragment(mInstrumentsFragment);
//Set 'Quiz Exit' button's visibility to 'false,' set Quiz-Ext button.
viewModel.recordQuizBtnStatus(false);
setQuizExtBtn();
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
drawerView.bringToFront();
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}});
// Bottom-Navigation Menu
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.nav_btm_quiz) {
if (mQuizFragment != null) {
String string = mQuizFragment.toString();
if (string.contains("Started") || string.contains("Topics")) {
viewModel.recordQuizBtnStatus(true);
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mQuizFragment);
fragmentTransaction.commit();
//Record foreground-fragment change
viewModel.recordForegroundFragment(mQuizFragment);
} else {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentQuiz_Selection_Instruments");
if (fragment == null) {
mQuizFragment = FragmentQuiz_Selection_Instruments.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mQuizFragment, "FragmentQuiz_Selection_Instruments");
fragmentTransaction.commit();
viewModel.recordForegroundFragment(mQuizFragment);
} else {
mQuizFragment = fragment;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mQuizFragment);
fragmentTransaction.commit();
viewModel.recordForegroundFragment(mQuizFragment);
}
}
} else if (itemId == R.id.nav_btm_instruments) {
viewModel.recordQuizBtnStatus(false);
if (mInstrumentsFragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mInstrumentsFragment);
fragmentTransaction.commit();
viewModel.recordForegroundFragment(mInstrumentsFragment);
} else {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_WWind");
if (fragment == null) {
mQuizFragment = FragmentInstruments_WWind.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_layout, mQuizFragment, "FragmentInstruments_WWind");
fragmentTransaction.commit();
} else {
mQuizFragment = fragment;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, fragment);
fragmentTransaction.commit();
}
}
} else if (itemId == R.id.nav_btm_reference) {
viewModel.recordQuizBtnStatus(false);
if (mReferenceFragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mReferenceFragment);
fragmentTransaction.commit();
} else {
mReferenceFragment = FragmentReference.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, mReferenceFragment, "FragmentReference");
fragmentTransaction.commit();
}
}
//Set Quiz-Ext button's visibility.
setQuizExtBtn();
//Call 'invalidateOptionsMenu' to set the Quiz-Exit button's visibility.
invalidateOptionsMenu();
return true;
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
/**Display FragmentInstruments_WWind when opening the app for the first time.
* If the app is being resumed, use getForegroundFragment.
*/
if (viewModel.getForegroundFragment() == null) {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FragmentInstruments_WWind");
if (fragment == null) {
mInstrumentsFragment = FragmentInstruments_WWind.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(mInstrumentsFragment, "FragmentInstruments_WWind");
fragmentTransaction.commit();
} else {
mInstrumentsFragment = fragment;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, mInstrumentsFragment);
transaction.commit();
//Record foreground-fragment change
viewModel.recordForegroundFragment(mInstrumentsFragment);
//Set Quiz-Exit Status
viewModel.recordQuizBtnStatus(false);
//Set 'Reference' icon as checked
bottomNavigationView.getMenu().getItem(1).setChecked(true);
} else if (viewModel.getForegroundFragment() != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment foregroundFragment = viewModel.getForegroundFragment();
transaction.replace(R.id.frame_layout, foregroundFragment);
transaction.commit();
//Record foreground-fragment change, set bottom-navigation icon
viewModel.recordForegroundFragment(foregroundFragment);
String fragment = foregroundFragment.toString();
if (fragment.contains("Quiz")) {
bottomNavigationView.getMenu().getItem(0).setChecked(true);
} else if (fragment.contains("Reference")) {
bottomNavigationView.getMenu().getItem(1).setChecked(true);
} else if (fragment.contains("Help")) {
bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}
}
#Override
protected void onPause(){
super.onPause();
//Actions onPause
viewModel.recordInstrumentsFragment(mInstrumentsFragment);
}
//Search function handled here
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
//Set 'Quiz Exit' button's visibility.
boolean status = viewModel.getQuizBtnStatus();
menu.findItem(R.id.ab_quiz_exit).setVisible(status);
return true;
}
//Handle action-bar button clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.ab_quiz_exit:
onQuizExit();
}
return super.onOptionsItemSelected(item);
}
Parent Fragment
public class FragmentInstruments_Brass extends Fragment {
public static FragmentInstruments_Brass newInstance() {
FragmentInstruments_Brass fragment = new FragmentInstruments_Brass();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fragment screen orientation normal both portrait and landscape
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_instruments, container, false);
//Setting ViewPager for each tab
ViewPager viewPager = view.findViewById(R.id.viewPager_instruments);
tabsToViewPager(viewPager);
//Set tabs inside toolbar
TabLayout tabLayout = view.findViewById(R.id.tabLayout_instruments);
tabLayout.setupWithViewPager(viewPager, false);
return view;
}
//Add Fragments to Tabs
private void tabsToViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
//Brass Fragments
adapter.addFragment(new Inst_Br_Frag1(), "Name1");
adapter.addFragment(new Inst_Br_Frag2(), "Name2");
adapter.addFragment(new Inst_Br_Frag3(), "Name3");
adapter.addFragment(new Inst_Br_Frag4(), "Name4");
adapter.addFragment(new Inst_Br_Frag5(), "Name5");
adapter.addFragment(new Inst_Br_Frag6(), "Name6");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentStatePagerAdapter {
//mFragmentList stores ChildFragments
private final List<Fragment> mFragmentList = new ArrayList<>();
//mFragmentTitleList stores the displayed name of each ChildFragment
private final List<String> mFragmentTitleList = new ArrayList<>();
Adapter(FragmentManager manager) {
super(manager);
}
// Return the Fragment associated with a specified position
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
// getCount() returns the number of views available
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
//This method may be called by the ViewPager to obtain a title string to describe the specified page.
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}

Bottom menu bar goes blank by clicking second time on menu options

I have a problem with my Bottom bar in android. when i click on the bottom menu options it goes blank. Please help me out to fine what is the basic problem. Where is am I wrong.
It shows no error or exception in logcat.
Here is my code
public class BottomBarActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_bar);
final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_library:
FragmentLibrary fragmentLibrary = new FragmentLibrary();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame_layout1, fragmentLibrary);
fragmentTransaction.commit();
Toast.makeText(BottomBarActivity.this, "Library", Toast.LENGTH_SHORT).show();
break;
case R.id.action_notification:
//002
Fragment selectedFragmentNotification = FragmentNotification.newInstance();
FragmentTransaction fragmentTransactionNotification = getSupportFragmentManager().beginTransaction();
fragmentTransactionNotification.replace(R.id.frame_layout1, selectedFragmentNotification);
fragmentTransactionNotification.commit();
Toast.makeText(BottomBarActivity.this, "Notifications", Toast.LENGTH_SHORT).show();
break;
case R.id.action_more:
Fragment selectedFragmentMore = FragmentMore.newInstance();
FragmentTransaction fragmentTransactionMore = getSupportFragmentManager().beginTransaction();
fragmentTransactionMore.replace(R.id.frame_layout1, selectedFragmentMore);
fragmentTransactionMore.commit();
Toast.makeText(BottomBarActivity.this, "More", Toast.LENGTH_SHORT).show();
break;
case R.id.action_discovered:
Fragment selectedFragmentMain = FragmentMain.newInstance();
FragmentTransaction fragmentTransactionMain = getSupportFragmentManager().beginTransaction();
fragmentTransactionMain.replace(R.id.frame_layout1, selectedFragmentMain);
fragmentTransactionMain.commit();
Toast.makeText(BottomBarActivity.this, "Discover", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
//Manually displaying the first fragment
Fragment selectedFragment = FragmentMain.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout1, selectedFragment);
fragmentTransaction.commit();
}
}
Here is the Fragment Class Code.
This fragment is called when I click one of the menu item.
public class FragmentLibrary extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
private PagerSlidingTabStrip tabs_L;
private ViewPager pager_L;
public FragmentLibrary() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_library, container, false);
pager_L = (ViewPager) view.findViewById(R.id.pagerL);
pager_L.setAdapter(new MyAdapterLibrary(getFragmentManager()));
tabs_L = (PagerSlidingTabStrip) view.findViewById(R.id.tabsL);
tabs_L.setViewPager(pager_L);
return view;
}
// ADAPTER CLASS
public class MyAdapterLibrary extends FragmentPagerAdapter {
private String[] titles = {
getString(R.string.tab_title_current_reading),
getString(R.string.tab_title_reading_lists),
getString(R.string.tab_title_history)
};
public MyAdapterLibrary(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentCurrentReading.newInstance(position);
case 1:
return FragmentReadingLists.newInstance(position);
case 2:
return FragmentHistory.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}

Backstack in Fragment Android

I am working in an application where i am calling Fragment2 from Fragment1, when I am pressing default back button in Fragment2 it is taking me to Fragment1 but when I am pressing any other button and calling getActivity.finish() it is closing my Activity.
I have added the code below:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AHBottomNavigation bottomNavigation;
Fragment selectedFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigation = (AHBottomNavigation) findViewById(R.id.navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.home, R.drawable.home, R.color.colorAccent);
AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.menu, R.drawable.menu, R.color.colorAccent);
AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.cart, R.drawable.cart, R.color.colorAccent);
AHBottomNavigationItem item4 = new AHBottomNavigationItem(R.string.orders, R.drawable.orders, R.color.colorAccent);
AHBottomNavigationItem item5 = new AHBottomNavigationItem(R.string.settings, R.drawable.setting, R.color.colorAccent);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
bottomNavigation.addItem(item4);
bottomNavigation.addItem(item5);
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
bottomNavigation.setAccentColor(Color.parseColor("#571e19"));
selectedFragment = ItemHomeFragment.newInstance(bottomNavigation);
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
if (position == 0) {
selectedFragment = ItemHomeFragment.newInstance(bottomNavigation);
} else if (position == 4) {
selectedFragment = Fragment1 (bottomNavigation);
}
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout,selectedFragment);
fragmentTransaction.commit();
return true;
}
});
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, ItemHomeFragment.newInstance(bottomNavigation));
fragmentTransaction.commit();
}
public void setNotification(){
bottomNavigation.setNotification("1", 1);
}
}
Fragment1.java
public class Fragment1 extends Fragment {
public static AHBottomNavigation bottomNavigation1;
TextView txtLogout,txtMyProfile,txtTermsCondition,txtRate;
public int LANGUAGE_REQUEST_CODE = 113;
private SharedPreferences prefs ;
Boolean languageBoolean = true;
MyApplication myApplication;
private UIView uiView = UIView.getInstance();
ProgressDialog pDialog;
static int index;
public static ItemSettingsFragment newInstance(AHBottomNavigation bottomNavigation) {
ItemSettingsFragment fragment = new ItemSettingsFragment();
bottomNavigation1 = bottomNavigation;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
showNotificationCounter(32);
View view = inflater.inflate(R.layout.fragment_settings, container, false);
TextView txtLanguage = (TextView) view.findViewById(R.id.txtLanguage);
txtLanguage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), LanguageActivity.class);
startActivity(intent);
}
});
txtMyProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment fragment2 = new ProfileFragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return view;
}
Fragment2.java
public class Fragment2 extends Fragment{
public Fragment2() { }
public static Fragment newInstance() {
Fragment2 profileFragment = new Fragment2();
return profileFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.language, container, false);
TextView fragment2 = (TextView) view.findViewById(R.id.txtLanguage);
fragment2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
return view;
}
}
Don't
getActivity.finish()
finish() clear the Activity.
Do
popBackStack();
Example
FragmentManager fmOBJ= getFragmentManager();
fmOBJ.popBackStack();

Unfortunately stopped when I click on items and open new fragments layout

I read some articles and make a nav drawer and fragments.i want to when I click on items in nav drawer, open fragments layout. but when I click on my fragments, my app crashed and unfortunately has stopped.
Can any one tell me what do I wrong? or what should I do to resolve my problem?
This is my MainActivty.java:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
This is my firstfragment:
public class FirstFragment extends android.support.v4.app.Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FirstFragment() {
}
public static FirstFragment newInstance(String param1, String param2) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Call fragment by using below code;
Fragment fragment = new TaskDiscussionFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.flContent, fragment);
ft.commit();
Add the Listener which you are expecting in in FirstFragment in MainActvity and override the interface method like below,
FirstFragment is expecting OnFragmentInteractionListener in your onAttach method.
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener{
#Override
public void onFragmentInteraction(Uri uri) {
}
}

Fragment implements AbsListView.OnItemClickListener with ArrayAdapter ==> onItemClick Listener is null

My implementation of an AbsListView.OnItemClickListener in a Fragment performs no action and displays no error, when a list item is tapped.
I read the documentation, searched Google & SOF and read the SDK source, but could not solve the problem.
The Activity:
public class VenueActivity extends Activity implements
NBVenuesFragment.OnFragmentInteractionListener,
NBFriendsFragment.OnFragmentInteractionListener,
UploadedPhotosFragment.OnFragmentInteractionListener {
private static final String TAB_KEY_INDEX = "tab_key";
private static final String TAG = "VenueActivity";
private Fragment mCurrentFragment = null;
private Fragment mNewFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_venue);
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab mVenuesFragmentTab = actionbar.newTab().setText(
getString(R.string.ui_nearby_venues_tab));
ActionBar.Tab mNBFriendsFragmentTab = actionbar.newTab().setText(
getString(R.string.ui_nearby_friends_tab));
ActionBar.Tab mUploadedPhotosFragmentTab = actionbar.newTab().setText("Photos Uploaded");
Fragment mVenuesFragment = new NBVenuesFragment();
Fragment mNBFriendsFragment = new NBFriendsFragment();
Fragment mUploadedPhotosFragment = new UploadedPhotosFragment();
mVenuesFragmentTab.setTabListener(new VenueTabsListener(mVenuesFragment,
getApplicationContext()));
mNBFriendsFragmentTab.setTabListener(new VenueTabsListener(mNBFriendsFragment,
getApplicationContext()));
mUploadedPhotosFragmentTab.setTabListener(new VenueTabsListener(mUploadedPhotosFragment,
getApplicationContext()));
actionbar.addTab(mVenuesFragmentTab);
//actionbar.addTab(mNBFriendsFragmentTab);
actionbar.addTab(mUploadedPhotosFragmentTab);
if (savedInstanceState != null) {
actionbar.setSelectedNavigationItem(savedInstanceState.getInt(
TAB_KEY_INDEX, 0));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.venue_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_check_in:
Toast.makeText(this, getString(R.string.action_check_in),
Toast.LENGTH_SHORT).show();
return true;
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.onBackPressed();
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(TAB_KEY_INDEX, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public void onNearByVenueSelection(VenuesDummyData.VenuesDummyItem venueData){
Bundle args = new Bundle();
args.putString("VENUE_ID", venueData.venueId);
args.putString("VENUE_NAME", venueData.venueName);
args.putString("VENUE_ADDRESS", venueData.venueAddress);
args.putString("VENUE_CHECK_INS", venueData.venueCheckIns);
args.putString("VENUE_LIKES", venueData.venueLikes);
args.putString("VENUE_CHECK_INS_FLIRT", venueData.venueCheckInsflirt);
args.putString("VENUE_CHECK_INS_FRIENDS", venueData.venueCheckInsFriends);
args.putString("OMEGA", venueData.omega);
Fragment mVenueDetailsFragment = new VenueDetailsFragment();
mVenueDetailsFragment.setArguments(args);
mCurrentFragment = new NBVenuesFragment();
mNewFragment = mVenueDetailsFragment;
FragmentManager mFragmentManager = getFragmentManager();
String tag = mVenueDetailsFragment.getTag();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.fragment_container, mVenueDetailsFragment, tag);
ft.commit();
}
#Override
public void onNearByFriendSelection(JsonObject mUserInfo){
Bundle args = new Bundle();
args.putString("FRIEND_NAME", mUserInfo.get("name").getAsString());
//args.putString("FRIEND_ID", mUserInfo.friendId);
args.putString("FRIEND_PHOTO", mUserInfo.get("photo_url").getAsString());
//args.putString("VENUE_ID", mUserInfo.venueId);
//args.putString("VENUE_NAME", mUserInfo.venueName);
Fragment mFriendDetailsFragment = new FriendDetailsFragment();
mFriendDetailsFragment.setArguments(args);
mCurrentFragment = new NBFriendsFragment();
mNewFragment = mFriendDetailsFragment;
FragmentManager mFragmentManager = getFragmentManager();
String tag = mFriendDetailsFragment.getTag();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.fragment_container, mFriendDetailsFragment, tag);
//ft.addToBackStack(tag);
ft.commit();
}
#Override
public void onUserSelection(JsonObject mUserInfo){
Log.i(TAG, "onUserSelection");
Log.i(TAG, "mUserInfo ==> " + mUserInfo.toString());
Bundle args = new Bundle();
args.putString("USER_NAME", mUserInfo.get("name").getAsString());
//args.putString("FRIEND_ID", mUserInfo.friendId);
args.putString("USER_PHOTO", mUserInfo.get("photo_url").getAsString());
//args.putString("VENUE_ID", mUserInfo.venueId);
//args.putString("VENUE_NAME", mUserInfo.venueName);
Fragment mUserDetailsFragment = new UserDetailsFragment();
mUserDetailsFragment.setArguments(args);
mCurrentFragment = new UploadedPhotosFragment();
mNewFragment = mUserDetailsFragment;
FragmentManager mFragmentManager = getFragmentManager();
String tag = mUserDetailsFragment.getTag();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.fragment_container, mUserDetailsFragment, tag);
//ft.addToBackStack(tag);
ft.commit();
}
#Override
public void onBackPressed() {
if (mCurrentFragment != null && mNewFragment != null) {
String tag = mCurrentFragment.getTag();
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.remove(mNewFragment);
ft.replace(R.id.fragment_container, mCurrentFragment, tag);
ft.commit();
mCurrentFragment = null;
mNewFragment = null;
} else {
super.onBackPressed();
}
}
}
class VenueTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public VenueTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
//Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
//Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
//Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
ft.remove(fragment);
}
}
The list Fragment:
public class UploadedPhotosFragment extends Fragment implements AbsListView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
private AbsListView mListView;
private JsonObject mUserInfo;
private PhotosAdapter mAdapter;
private JsonArray mDataFromServer;
private String TAG = "UploadedPhotosFragment";
private void getPhotosData() {
Log.i(TAG, "getPhotosData");
AsyncTask<Void, Void, FlefuApiMessagesGetPhotosResponseMessage> photosJsonString;
photosJsonString = new GetPhotos() {
#Override
protected void onPostExecute(FlefuApiMessagesGetPhotosResponseMessage response) {
Log.i(TAG, "#overridden GetPhotos onPostExecute: " + response.getData());
mDataFromServer = (JsonArray)new JsonParser().parse(response.getData());
mUserInfo = new JsonObject();
for (int i = 0; i < mDataFromServer.size(); i++) {
mUserInfo = mDataFromServer.get(i).getAsJsonObject();
mAdapter.add(mUserInfo);
}
}
};
photosJsonString.execute();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPhotosData();
mAdapter = new PhotosAdapter(getActivity());
Log.i(TAG, "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_photo_image, container, false);
//int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
mListView = (AbsListView) view.findViewById(R.id.photos);
//mListView.setNumColumns(3);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private class PhotosAdapter extends ArrayAdapter <JsonObject> {
private LayoutInflater inflater;
private class ViewHolder {
TextView name;
//TextView venue;
ImageView thumb;
}
public PhotosAdapter(Context context) {
super(context, R.layout.uploaded_image);
Log.i(TAG, context.toString());
inflater = LayoutInflater.from(context);
Log.i(TAG, "PhotosAdapter");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView");
ViewHolder holder;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.uploaded_image, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.thumb = (ImageView) convertView.findViewById(R.id.image);
//holder.venueName = (TextView) convertView.findViewById(R.id.venueName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// select the image view
Ion.with(holder.thumb)
.resize(300, 300)
.centerCrop()
//.placeholder(R.drawable.placeholder)
//.error(R.drawable.error)
.load(getItem(position).get("thumb_url").getAsString());
holder.name.setText(getItem(position).get("name").getAsString());
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "parent ==> " + parent.toString());
Log.i(TAG, "view ==> " + view.toString());
if (mListener != null) {
Log.i(TAG, "call to onUserSelection ==> " +
mDataFromServer.get(position).getAsJsonObject().toString());
mListener.onUserSelection(mDataFromServer.get(position).getAsJsonObject());
}
}
public interface OnFragmentInteractionListener {
public void onUserSelection(JsonObject mUserInfo);
}
}
You did not initialized Your mListener value. Your mListener is null and nothing happens when You click a ListView item.

Categories

Resources