I have an activity and already made fragment. In my activity, when I click on login button then the loader will show. After the loader become invisible, then I just need to attach that fragment. The fragment has already been created in some other class. I just need to attach that fragment when the circular loader become invisible and my fragment has already been created in some other class but I need to just attach that fragment.
MainActivity.java
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
if (loader_fragment != null) {
AVLoadingIndicatorView loader = loader_fragment.getView().findViewById(R.id.loder_login);
loader.setVisibility(View.INVISIBLE);
timer.cancel();
}
Home_Screen home_screen = (Home_Screen) getFragmentManager().findFragmentById(R.id.Home_screen_fragment);
fragmentManager1 = getFragmentManager();
fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.setCustomAnimations(
R.animator.slide_in_left,
R.animator.slide_out_left,
R.animator.slide_in_right,
R.animator.slide_out_right);
Home_screen_student home_screen_student = new Home_screen_student();
fragmentTransaction1.attach(R.id.Home_screen_fragment, home_screen_student);
fragmentTransaction1.commit();
}
};
HomeScreenFragment.java
package com.example.user.attendance;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.NavigationView.OnNavigationItemSelectedListener;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Home_Screen extends Fragment implements OnNavigationItemSelectedListener {
DrawerLayout navigation_drawer;
NavigationView navigationView;
Button logout_Yes_button,logout_no_button, home_screen_take_attendance_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View Home_screen = inflater.inflate(R.layout.navigation_drawer,container,false);
android.support.v7.widget.Toolbar toolbar =
(android.support.v7.widget.Toolbar) Home_screen.findViewById(R.id.custom_action_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
navigation_drawer = (DrawerLayout) Home_screen.findViewById(R.id.drawer_layout);
navigationView = (NavigationView) Home_screen.findViewById(R.id.Navigation_view_for_teacher);
Logcat error:
04-22 18:45:31.966 26404-26404/? E/Zygote: no v2
04-22 18:45:54.221 26404-26404/com.example.user.attendance E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.attendance, PID: 26404
java.lang.NullPointerException: Attempt to write to field 'android.app.FragmentManagerImpl android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:461)
at android.app.BackStackRecord.replace(BackStackRecord.java:496)
at android.app.BackStackRecord.replace(BackStackRecord.java:488)
at com.example.user.attendance.MainActivity$3$2.run(MainActivity.java:181)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7402)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Help me.
Do you use viewPager in your activity?
You may need to process from one activity to another
Try this trailer:
ViewPager viewPager = (ViewPager) findViewById(R.id.rew1);
viewPager.setAdapter(new CustomPagerAdapter(this));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
//
public enum CustomPagerEnum {
HomeFragment (R.string.tab_text_1, R.layout.Home_screen_fragment),
private int mTitleResId;
private int mLayoutResId;
CustomPagerEnum(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
//
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
home.CustomPagerEnum customPagerEnum = home.CustomPagerEnum.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(customPagerEnum.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return home.CustomPagerEnum.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
home.CustomPagerEnum customPagerEnum = home.CustomPagerEnum.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
My language is German but I hope I understand your problem well!
Related
I am trying to make an activity which has a fragment inside with a recyclerView and cards on it. Right now, it only shows the activity, the fragment is empty, and I don't know what is going on here.
This is the code of the activity, the fragment, and the adapter
Activity:
package com.laorden.goodreasons.habits;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.NavigationView;
import android.support.test.espresso.IdlingResource;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.Injection;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.statistics.StatisticsActivity;
import com.laorden.goodreasons.util.ActivityUtils;
import com.laorden.goodreasons.util.EspressoIdlingResource;
public class HabitsActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private HabitsPresenter mHabitsPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.habits_act);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Set up the toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
// Set up the navigation drawer.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
HabitsFragment habitsFragment =
(HabitsFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (habitsFragment == null) {
// Create the fragment
habitsFragment = HabitsFragment.newInstance();
ActivityUtils.addFragmentToActivity(
getSupportFragmentManager(), habitsFragment, R.id.contentFrame);
}
// Create the presenter
mHabitsPresenter = new HabitsPresenter(habitsFragment,
Injection.provideUseCaseHandler());
}
/* // Load previously saved state, if available.
if (savedInstanceState != null) {
TasksFilterType currentFiltering =
(TasksFilterType) savedInstanceState.getSerializable(CURRENT_FILTERING_KEY);
mTasksPresenter.setFiltering(currentFiltering);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(CURRENT_FILTERING_KEY, mTasksPresenter.getFiltering());
super.onSaveInstanceState(outState);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Open the navigation drawer when the home icon is selected from the toolbar.
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.list_navigation_menu_item:
// Do nothing, we're already on that screen
break;
case R.id.statistics_navigation_menu_item:
Intent intent =
new Intent(HabitsActivity.this, StatisticsActivity.class);
startActivity(intent);
break;
default:
break;
}
// Close the navigation drawer when an item is selected.
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#VisibleForTesting
public IdlingResource getCountingIdlingResource() {
return EspressoIdlingResource.getIdlingResource();
}
}
Fragment:
package com.laorden.goodreasons.habits;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.ArrayList;
import java.util.List;
public class HabitsFragment extends android.support.v4.app.Fragment implements HabitsContract.View {
private HabitsContract.Presenter mPresenter;
private HabitsAdapter mListAdapter;
private RecyclerView recyclerView;
public HabitsFragment() {
// Requires empty public constructor
}
public static HabitsFragment newInstance() {
return new HabitsFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Habit> habitsList = new ArrayList<>();
habitsList.add(new Habit(R.drawable.smoke,"Quit smoking",300));
habitsList.add(new Habit(R.drawable.books,"Read more",600));
habitsList.add(new Habit(R.drawable.sleep,"Get more sleep",600));
mListAdapter = new HabitsAdapter(getContext(),habitsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setAdapter(mListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return root;
}
#Override
public void onResume() {
super.onResume();
mPresenter.start();
}
#Override
public void setLoadingIndicator(boolean active) {
}
#Override
public void showHabits(List<Habit> habits) {
}
#Override
public void showHabitDetailsUi(String habitId) {
}
#Override
public boolean isActive() {
return false;
}
#Override
public void setPresenter(HabitsContract.Presenter presenter) {
mPresenter = presenter;
}
}
Adapter:
package com.laorden.goodreasons.habits;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.List;
public class HabitsAdapter extends RecyclerView.Adapter<HabitsAdapter.myViewHolder> {
Context mContext;
List<Habit> mData;
public HabitsAdapter(Context mContext, List<Habit> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.card_item,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
holder.background_image.setImageResource(mData.get(position).getBackground());
holder.tv_title.setText(mData.get(position).getHabitName());
holder.tv_nbSubscribers.setText(mData.get(position).getNumSubscribers() + " Joined");
}
#Override
public int getItemCount() {
return 0;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView background_image;
TextView tv_title,tv_nbSubscribers;
public myViewHolder(View itemView) {
super(itemView);
background_image = itemView.findViewById(R.id.card_background);
tv_title = itemView.findViewById(R.id.card_title);
tv_nbSubscribers = itemView.findViewById(R.id.card_numberUsers);
}
}
}
If you need any other code snippets, please tell me (maybe the xml
layouts)
Thanks
That is because you are returning 0 in the getItemCount method
Change this :
#Override
public int getItemCount() {
return 0;
}
To this:
#Override
public int getItemCount() {
return (mData != null ? mData.size():0);
}
you should set layout manager first
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mListAdapter);
return root;
}
also you need to change the getItemCount into
#Override
public int getItemCount() {
if(mData!=null){return mData.size();}else return 0;
}
The reason you are getting empty list because your method getItemCount returns 0.
Here is the modified method.
#Override
public int getItemCount() {
return mData!=null ? mData.size():0;
}
I am making a tour app, it structure is like this:
First activity shows seasons like Summer, Winter, Spring, Autumn. After selecting any season, another activity pops up with locations around the world best suited for that season. After selecting any one location, another activity will pop up with 2 to 3 images with the description, and we will slide through these images. That's it. To make it more accessible, I tried adding this code to NawDrawer activity:
Debugging Error Message Image
Originally the ViewPagerAdapter.java was for Hawaii (check the image), but I created exact same as Yoshimiteadapter.java for Yosemite, but it's not working.
I apologize for the inconvenience caused by the files :) ,it's messy ,but desperate help is needed:
Link to android studio project zip file
There are total 7 java files and 12 activity files although I have an error in yosemiteadapter.Java line no 35 , error message is as follows:
04-16 12:00:09.563 12511-12511/com.example.android.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.myapplication, PID: 12511
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.example.android.myapplication.yoshimiteadapter.instantiateItem(yoshimiteadapter.java:35)
**Code for the app as follows,I have block quoted the line of error **
yoshimiteadapter.java
package com.example.android.myapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by sanchitdeshmukh on 17/03/18.
*/
public class yoshimiteadapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer []images1 ={R.drawable.yosemite1,R.drawable.yoshemite2,R.drawable.yoshemite3};
private Integer []strings1 = {R.string.yoshimite};
public yoshimiteadapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.custom_layout_yos, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
imageView.setImageResource(images1[position]);
TextView textView = (TextView)view.findViewById(R.id.textView);
textView.setText(strings1[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
#Override
public int getCount() {
return images1.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
}
yosemite.java
package com.example.android.myapplication;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class yoshemite extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yoshemite);
viewPager = (ViewPager)findViewById(R.id.yoshimite);
yoshimiteadapter yoshimiteadapter = new yoshimiteadapter(this);
viewPager.setAdapter(yoshimiteadapter);
}
}
ViewPagerAdapter.java
package com.example.android.myapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by sanchitdeshmukh on 17/03/18.
*/
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer []images ={R.drawable.napalicoast,R.drawable.haleakaaa,R.drawable.roadtohana};
private Integer []strings = {R.string.haleaka,R.string.napali,R.string.Paragraph_hawaii};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.custom_layout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
TextView textView = (TextView)view.findViewById(R.id.textView);
textView.setText(strings[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
I found the solution , it's related to this:
textView.setText(strings1[position]);
I have only one string, three images, which causes the error. [position] should be set to '0'; so the modification is like this:
textView.setText(strings1[0]);
This question already has answers here:
Why is my context in my Fragment null?
(4 answers)
Closed 5 years ago.
I tried to find the solution with several resources:
Retrieve Context from a fragment
Using context in a fragment
But I still got the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
Any help will be appreciated. Thanks!
My current codes:
AnalysisActivity.java:
package com.app.component.fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.material.components.R;
import com.material.components.fragment.FragmentTabsEvents;
import com.material.components.fragment.FragmentTabsPerformance;
import com.material.components.fragment.FragmentTabsRecommendation;
import com.material.components.utils.Tools;
import java.util.ArrayList;
import java.util.List;
public class AnalysisActivity extends AppCompatActivity {
private ViewPager view_pager;
private TabLayout tab_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analysis);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Tools.setSystemBarColor(this,R.color.black);
view_pager = findViewById(R.id.view_pager);
setupViewPager(view_pager);
tab_layout = findViewById(R.id.tab_layout);
tab_layout.setupWithViewPager(view_pager);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FragmentTabsPerformance.newInstance(), "PERFORMANCE");
adapter.addFragment(FragmentTabsRecommendation.newInstance(), "RECOMMENDATION");
adapter.addFragment(FragmentTabsEvents.newInstance(), "EVENTS RELATED TO YOU");
viewPager.setAdapter(adapter);
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
FragmentTabsPerformance.java:
package com.app.component.fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.material.components.R;
import com.material.components.utils.Tools;
import java.util.ArrayList;
import java.util.List;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;
public class FragmentTabsPerformance extends Fragment {
private Context context;
public FragmentTabsPerformance() {
this.context = getActivity().getApplicationContext();
List<PointValue> values = new ArrayList<>();
values.add(new PointValue(0, 2));
values.add(new PointValue(1, 4));
values.add(new PointValue(2, 3));
values.add(new PointValue(3, 4));
//In most cased you can call data model methods in builder-pattern-like manner.
Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
List<Line> lines = new ArrayList<>();
lines.add(line);
LineChartData data = new LineChartData();
data.setLines(lines);
LineChartView chart = new LineChartView(this.getContext());
chart.setLineChartData(data);
}
public static FragmentTabsPerformance newInstance() {
FragmentTabsPerformance fragment = new FragmentTabsPerformance();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_tabs_performance, container, false);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_1), R.drawable.image_8);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_2), R.drawable.image_9);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_3), R.drawable.image_15);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_4), R.drawable.image_14);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_5), R.drawable.image_12);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_6), R.drawable.image_2);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_7), R.drawable.image_5);
return root;
}
}
This exception occurred since you called the getActivity() in the construction method when the fragment is not attached to an activity. You may refer to the API guides about the lifecycle methods about fragment with activity. In your case, you may use getContext() instead of getActivity() method to get the context of fragment.
getActivity() only available after Fragment is attached to activity. So, getActivity() in Fragment constructor will return null. Check fragment life cycle for more detail
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Thank you for your time.
MainActivity
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentB fragB = new FragmentB();
FragmentManager fragManager = getFragmentManager();
FragmentTransaction fragTransaction = fragManager.beginTransaction();
fragTransaction.add(R.id.cmll,fragB,"fragB");
fragTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
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);
}
}
My Fragment
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentB extends Fragment {
private Context myContext;
#Override
public void onAttach(Context context) {
myContext=context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView = (ListView) getActivity().findViewById(R.id.listView);
MyBaseAdapter adapter = new MyBaseAdapter(myContext);
listView.setAdapter(adapter);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
My BaseAdapter Class
i know it doesn't use the View Holder design pattern yet but i thought it should still display without crashing.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class MyBaseAdapter extends BaseAdapter {
private Context myContext;
private ArrayList<ListViewInfo> list;
public MyBaseAdapter(Context context) {
myContext = context;
list = new ArrayList<>();
String[] test_10char = {"AaaAaaAaaA","BbbBbbBbbB","CccCccCccC"};
String[] test_3char = {"Aaa","Bbb","Ccc"};
int[] ints = {R.drawable.test_sunny,R.drawable.test_sunny,R.drawable.test_sunny};
for (int i = 0; i < 3; i++) {
list.add(new ListViewInfo(test_10char[i], test_3char[i], ints[i]));
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View singleRowView = inflater.inflate(R.layout.list_item_layout,parent,false);
TextView date = (TextView) singleRowView.findViewById(R.id.textView1);
TextView temp = (TextView) singleRowView.findViewById(R.id.textView2);
ImageView icon = (ImageView) singleRowView.findViewById(R.id.imageView1);
ListViewInfo tempLVI = list.get(position);
date.setText(tempLVI.getDate());
temp.setText(tempLVI.getTemp());
icon.setImageResource(tempLVI.getImageID());
return singleRowView;
}
}
Error Log
03-22 21:42:08.421 4130-4130/com.eli.myweatherapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.eli.myweatherapp, PID: 4130
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.eli.myweatherapp.MyBaseAdapter.getView(MyBaseAdapter.java:52)
at android.widget.AbsListView.obtainView(AbsListView.java:2387)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
at android.widget.ListView.onMeasure(ListView.java:1182)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17485)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
at android.view.View.measure(View.java:17485)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
at android.view.View.measure(View.java:17485)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5875)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5290)
at java.lang.reflect.Method.invoke(Native Method)
at java.lan
I have a ListViewInfo class too but its just three variables and get methods.
Thank you in advance for your help. I have no idea what the problem is.
ViewGroup parent arguments of getView has context info like this: Context context = parent.getContext();
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
to
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
I hope this is helpful for you.
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I'm having problems launching my app (crashes), while there is no errors in code.
This happend after i converted code of List View activity to List Fragment...
My main activity:
package com.example.eronetmarket;
import com.preporuceno_app.AppAdapter;
import android.R.drawable;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.itemmenu, menu);
return true;
}
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
//actionBar.setDisplayShowHomeEnabled(false);
addTabs(actionBar);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
Log.d("VIVZ","onPageScrolled "+i+" "+v+" "+i2);
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
Log.d("VIVZ","onPageSelected "+i);
}
#Override
public void onPageScrollStateChanged(int i) {
if(i==ViewPager.SCROLL_STATE_IDLE)
Log.d("VIVZ","onPageScrollStateChanged scroll state idle "+i);
if(i==ViewPager.SCROLL_STATE_DRAGGING)
Log.d("VIVZ","onPageScrollStateChanged scroll state dragging "+i);
if(i==ViewPager.SCROLL_STATE_SETTLING)
Log.d("VIVZ","onPageScrollStateChanged scroll state settling "+i);
}
});
}
private void addTabs(ActionBar actionBar)
{
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("PREPORUČENO");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("NAJPOPULARNIJE");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionBar.newTab();
tab3.setText("KATEGORIJE");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
// Log.d("VIVZ","onTabSelected "+tab.getText());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabUnselected "+tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabReselected "+tab.getText());
}
}
class MyAdapter extends FragmentStatePagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)
{
fragment=new FragmentA();
}
if(i==1)
{
fragment=new Preporuceno();
}
if(i==2)
{
fragment=new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
And my fragment list:
package com.example.eronetmarket;
import java.io.FileNotFoundException;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Preporuceno extends ListFragment {
private AppAdapter mAdapter;
private ListView siteList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("mobAppModel", "OnCreate()");
View rootView = inflater.inflate(R.layout.activity_preporuceno, container, false);
siteList = (ListView) getActivity().findViewById(R.id.listView1);
siteList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getstoreURL();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
if(isNetworkAvailable()){
Log.i("mobAppModel", "starting download Task");
AppDownloadTask download = new AppDownloadTask();
download.execute();
}else{
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
}
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private class AppDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("http://minores.info/joomla30/stacksites.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount());
}
}
}
Here is my LogCat messages:
In line 38 where LogCat shows error, I have this line public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
I don't understand where I went wrong?
Change this
siteList = (ListView) getActivity().findViewById(R.id.listView1);
to
siteList = (ListView) rootView.findViewById(R.id.listView1);
The view belongs to the inflated layout and you need to use the view object to initialize views.
java.lang.RuntimeException: Your content must have a ListView whose
id attribute is 'android.R.id.list'
ListActivity or ListFragment will have listview which occuppies the entire screen. If you want to have other views in the layout then your layout must have listview with id andorid.R.id.list
http://developer.android.com/reference/android/app/ListFragment.html
QUoting docs
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by
returning your own view hierarchy from onCreateView(LayoutInflater,
ViewGroup, Bundle). To do this, your view hierarchy must contain a
ListView object with the id "#android:id/list" (or list if it's in
code)