How should I replace drawables? - java

I have an list adapter which is showing an items (drawable + text).
I added to my code an RoundImage class, to replace drawables with the rounded ones. The code is following:
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// cirlce avatars
ImageView imageView1;
RoundImage roundedImage;
imageView1 = (ImageView)rootView.findViewById(R.id.avatar);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.kamil);
roundedImage = new RoundImage(bm);
imageView1.setImageDrawable(roundedImage);
//end circle avatars
}
next, in the onCreateView I'm using an adapter :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
//button --------------------------
add = (ImageButton) rootView.findViewById(R.id.add_button);
add.setOnClickListener(this);
//button --------------------------
RowBean RowBean_data[] = new RowBean[]{
new RowBean(R.drawable.kamilk, "Kamil "),
new RowBean(R.drawable.bartlomiej, "Bartlomiej "),
new RowBean(R.drawable.krzysztof, "Krzysztof ")
};
CustomAdapter adapter = new CustomAdapter(getActivity().getApplicationContext(), R.layout.list_style, RowBean_data);
ListView lista = (ListView) rootView.findViewById(R.id.lista);
lista.setAdapter(adapter);
return rootView;
}
but I'm getting an error
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialdesign/info.androidhive.materialdesign.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
so my question is, how should I do the adapter showing "roundedImage"?
I think the problem is in the line below, I also tried with getActivity().findViewbyId but it didn't work too.
imageView1 = (ImageView)rootView.findViewById(R.id.avatar);

info.androidhive.materialdesign.activity.HomeFragment.onCreate(HomeFragment.java:41)
This line is causing crash in your application, I found this line contains the below instruction
imageView1 = (ImageView)rootView.findViewById(R.id.avatar);
Reason of crash
The application is getting crash because your rootView is null in the onCreate method because onCreate() executes first before onCreateView() please check the life cycle of the fragment...!
Solution
Don't give any instruction in onCreate method, Use the below code,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
// cirlce avatars
ImageView imageView1;
RoundImage roundedImage;
imageView1 = (ImageView)rootView.findViewById(R.id.avatar);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.kamil);
roundedImage = new RoundImage(bm);
imageView1.setImageDrawable(roundedImage);
//end circle avatars
//button --------------------------
add = (ImageButton) rootView.findViewById(R.id.add_button);
add.setOnClickListener(this);
//button --------------------------
RowBean RowBean_data[] = new RowBean[]{
new RowBean(R.drawable.kamilk, "Kamil "),
new RowBean(R.drawable.bartlomiej, "Bartlomiej "),
new RowBean(R.drawable.krzysztof, "Krzysztof ")
};
CustomAdapter adapter = new CustomAdapter(getActivity().getApplicationContext(), R.layout.list_style, RowBean_data);
ListView lista = (ListView) rootView.findViewById(R.id.lista);
lista.setAdapter(adapter);
return rootView;
}

I repost this new answer (and deleted the former because that was pointless).
If your rootViews in onCreate and in onCreateView are different, the rootView in onCreate is apparently null. That resulted the error.
And if the rootView in onCreate is inflated from another layout (I presume this name avatar.xml) other than the activity_main.xml (which is set as the contentView), you can inflate it by using LayoutInflater.
So, insert View rootView = getLayoutInflater().inflate(R.layout.avatar, null); before you use rootView.
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = getLayoutInflater().inflate(R.layout.avatar, null);
// cirlce avatars
ImageView imageView1;
RoundImage roundedImage;
imageView1 = (ImageView)rootView.findViewById(R.id.avatar);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.kamil);
roundedImage = new RoundImage(bm);
imageView1.setImageDrawable(roundedImage);
//end circle avatars
}

Related

How to stop fragment reload everytime clicked?

I have a bottom navigation which is responsible for switching fragments. So whenever I click the button twice, the fragment reloads the content on it everytime
How to stop that? I want to reload the page by only scrolling upwards
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View Layout = inflater.inflate(R.layout.fragment_profile, container, false);
ConstraintLayout profile = (ConstraintLayout) Layout.findViewById(R.id.ll);
ImageView imageView = (ImageView) Layout.findViewById(R.id.imageView3);
imageView.setClipToOutline(true);
SharedPreferences sharedPref = getActivity().getSharedPreferences("INFORMATION", 0);
String USERNAME = sharedPref.getString("user","");
TextView username = (TextView) Layout.findViewById(R.id.username);
Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto Thin.ttf");
TextView desc = (TextView) Layout.findViewById(R.id.desc);
desc.setTypeface(custom_font);
username.setTypeface(custom_font);
username.setText(USERNAME);
new PostClass(getContext()).execute();
new PostClass_2().execute();
new PostClass_3().execute();
return Layout;
}
This code above gets executed everytime the fragment is changed. I want to reload it by scrolling upwards like in chrome in a fragment. Any help is appreciated
I had this problem a long time ago :/ but I found a simple way to solve the problem :)
Use this to solve the problem :
// Necessary :)
private Context mContext;
private View MyView;
// Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mContext=getActivity();
if(MyView==null){
// Layout View
MyView=LayoutInflater.from(mContext).inflate(R.layout.fragment_profile, null);
// Your views & Codes
ConstraintLayout profile = (ConstraintLayout) MyView.findViewById(R.id.ll);
ImageView imageView = (ImageView) MyView.findViewById(R.id.imageView3);
imageView.setClipToOutline(true);
SharedPreferences sharedPref = getActivity().getSharedPreferences("INFORMATION", 0);
String USERNAME = sharedPref.getString("user","");
TextView username = (TextView) MyView.findViewById(R.id.username);
Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto Thin.ttf");
TextView desc = (TextView) MyView.findViewById(R.id.desc);
desc.setTypeface(custom_font);
username.setTypeface(custom_font);
username.setText(USERNAME);
new PostClass(getContext()).execute();
new PostClass_2().execute();
new PostClass_3().execute();
// Stop fragment reload [ When changing ]
} ViewGroup parent = (ViewGroup) MyView.getParent();
if (parent != null) {
parent.removeView(MyView);
}
return MyView;
}
}
Use this if you want to set a new id : MyView.findViewById(R.id.SetId)
I hope that helps !
Good luck

Find internal views of a dynamically created fragment

I have dynamically added a fragment to another fragment.
I need to find a few views within that fragment.
How do I achieve that?
here is my code:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_educational, container, false);
if (view != null)
{
ButterKnife.inject(this, view);
}
DisposableEducationalFragment disposableEducationalFragment = new DisposableEducationalFragment();
getChildFragmentManager().beginTransaction().add(R.id.fragmentContainer,disposableEducationalFragment).addToBackStack(null).commit();
I want to find these views within that Dynamic fragment:
howItWorks = (RelativeLayout) fragmentView.findViewById(R.id.HowItWorks);
howWeHelp = (RelativeLayout) fragmentView.findViewById(R.id.HowWeHelp);
knowYourBloodPressure = (RelativeLayout) fragmentView.findViewById(R.id.KnowYourBloodPressure);
learnAboutBirthControl = (RelativeLayout) fragmentView.findViewById(R.id.LearnAboutBirthControl);
So, save View view into a temp variable and call it later.
tmpView = view;
and somewhere later:
howItWorks = (RelativeLayout) tempView.findViewById(R.id.HowItWorks);
or , may be, just try it:
howItWorks = (RelativeLayout) getActivity().findViewById(R.id.HowItWorks);

Android Viewpager inside of Viewpager not showing layout

I have been tasked with creating a very unorthodox layout that can only be accomplished with a viewpager inside the second pane of another viewpager, thankfully the outer viewpager needs to be locked so the task was a little more realistic, however the unexpected issue arose where after the inner viewpager was loaded onCreateView is never called, I can see that it is sliding side to side so the inner viewpager is setup but it will not load any inner view for some odd reason, any help will go a long way thanks
Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_fragment);
pagePosition = 0;
setupViews();
}
private void setupViews() {
//setup images to be changed later
ivCategory = (ImageView) findViewById(R.id.ivCatergory);
ivHome = (ImageView) findViewById(R.id.ivHome);
ivProfile = (ImageView) findViewById(R.id.ivProfile);
//setup the viewpager
pager = (CustomViewPager) findViewById(R.id.viewpager);
//add fragments to the fragment array
pageList.add(NavigationFragment.newInstance(0, getApplicationContext(), this));
pageList.add(NavigationFragment.newInstance(1, getApplicationContext(), this));
pageList.add(NavigationFragment.newInstance(0, getApplicationContext(), this));
// initialize the page adapter
pageAdapter = new FragmentHomeAdapter(getSupportFragmentManager(), pageList);
//set the page adapter to the viewpager
pager.setAdapter(pageAdapter);
//set homepage to be first
pager.setCurrentItem(1);
//disable swiping to mimic iphone behaviour
pager.setPagingEnabled(false);
}
viewpager
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int pageType = getArguments().getInt(PAGE_TYPE);
View v;
if (pageType == 1) {//all inner fragments will happen here
v = inflater.inflate(R.layout.fragment_container, container, false);
//setup the inner viewpager
pager = (CustomViewPager) v.findViewById(R.id.viewpager);
pageList.add(HomeFragment.newInstance(0, context, getActivity()));
pageList.add(HomeFragment.newInstance(1, context, getActivity()));
// initialize the page adapter
pageAdapter = new FragmentHomeAdapter(getActivity().getSupportFragmentManager(), pageList);
//set the page adapter to the viewpager
pager.setAdapter(pageAdapter);
pager.setPagingEnabled(true);
}
return v;
}
inner viewpager
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v;
v = inflater.inflate(R.layout.fragment_list_feed, container, false);
lv = (ListView) v.findViewById(R.id.lvFeed);
listAdapter = new ListHomeAdapter(getArguments().getInt(PAGE_TYPE), feedListItems, getActivity());
//add header
header = (ViewGroup) inflater.inflate(R.layout.list_item_header, lv, false);
lv.addHeaderView(header, null, false);
lv.setAdapter(listAdapter);
if (getArguments().getInt(PAGE_TYPE) == 0) {
new getFeedListItems().execute();
} else {
new getFeedListItems().execute();
}
Toast.makeText(context, "This never shows",
Toast.LENGTH_SHORT).show();
return v;
}
When showing Fragments inside another Fragment, use getChildFragmentManager() instead of getSupportFragmentManager()
Initialize your pageAdapter this way:
pageAdapter = new FragmentHomeAdapter(getChildFragmentManager(), pageList);

FlipView Adapter not Updating

The adapter of a flipview is set onCreate. Everything works fine. The user is meant to select some items on another activity which would update the items on the flipview. I implemented this by changing the adapter of the flipView when onResume is called and the dismiss activity is the selectionActivity. The code is executed but it does not reflect on the flipView items.
What i do on onCreate
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.flip_main, container, false);
mFlipView = (FlipView) rootView.findViewById(R.id.flip_view);
mAdapter = new FlipAdapter(getActivity(),getHomeItems(), getFragmentManager());
mAdapter.setCallback(this);
mFlipView.setAdapter(mAdapter);
mFlipView.setOnFlipListener(this);
if (isFirstShown) {
mFlipView.peakNext(false);
isFirstShown = false;
}
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(getActivity().findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
return rootView;
}
what is called after the user makes selection
FlipAdapterTest mAdapter = new FlipAdapterTest(getActivity(), getHomeItems(), getFragmentManager());
mFlipView.removeAllViews();
mFlipView.setAdapter(mAdapter);

Fragment content does not show up until I switch it and select it again

I've got a problem with my Android app: my fragment content doesn't show up until I switch it and I select it again. What should load just at the fragment start is a list of Cards.
Here you got the onCreate method of the Fragment that loads everything:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
debts = bundle.getParcelableArrayList("list");
adapter = new CardAdapter(getActivity(), android.R.color.holo_blue_dark);
for (int i=0; i<debts.size();++i) {
Debt d = debts.get(i);
Card card = new Card(d.getSecondUser(),d.getSubject());
adapter.add(card);
}
}
And here the onActivityCreated method where i set the adapter for the list:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CardListView list = (CardListView) getView().findViewById(R.id.newCard);
list.setCardTheme(CardTheme.Light);
list.setAdapter(adapter);
}
It works if I use an ArrayList of Cards already loaded, but not this way.
I tried nearly everything... thank you very much.
UPDATE: Even I tried with the solutions you gave me, it keeps happening, my code now:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
debts = bundle.getParcelableArrayList("list");
adapter = new CardAdapter(getActivity(), android.R.color.holo_blue_dark);
for (int i=0; i<debts.size();++i) {
Debt d = debts.get(i);
Card card = new Card(d.getSecondUser(),d.getSubject());
adapter.add(card);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_debts, container,
false);
CardListView list = (CardListView) rootView.findViewById(R.id.newCard);
list.setCardTheme(CardTheme.Light);
list.setAdapter(adapter);
return rootView;
}
You should initialize your cardListView inside the onCreateView() method. onCreateView() gets called before the onActivityCreated() method. onCreateView() should be the point when the view of your fragment is initialized.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//use your layout file instead of R.layout.fragment_main
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
CardListView list = rootView.findViewById(R.id.newCard);
list.setCardTheme(CardTheme.Light);
list.setAdapter(adapter);
}
Please take a look at the lifecycle of Fragments.

Categories