I have a fragment like this
...
public class Dashboard extends Fragment{
private RecyclerView mTopSellersListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_dashboard, container, false);
mTopSellersListView = (RecyclerView) view.findViewById(R.id.topSellersListView);
return view;
}
public void setTopSellersListView(MyRecycleAdapter adapter){
mTopSellersListView.setHasFixedSize(true);
mTopSellersListView.setAdapter(adapter);
mTopSellersListView.setLayoutManager(new LinearLayoutManager(getActivity()));
mTopSellersListView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
mTopSellersListView.setItemAnimator(new DefaultItemAnimator());
}
}
I have total 4 fragment, all of them can be switch in MainActivity by a bottombar used this method, when user tap on menu, it will replace current fragment with another one (Default: Dashboard):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDashboardFragment = new Dashboard();
mOrdersFragment = new Orders();
mProductsFragment = new Products();
mSettingFragment = new Setting();
settingMenu(savedInstanceState);
}
...
public void selectMenu(String menu){
Fragment fr = null;
switch (menu) {
case "Dashboard":
fr = mDashboardFragment;
break;
case "Orders":
fr = mOrdersFragment;
break;
case "Products":
fr = mProductsFragment;
break;
case "Setting":
fr = mSettingFragment;
break;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
I access the setTopSellersListView() in another class (not activity class)
MainActivity.mDashboardFragment.setTopSellersListView(mProductAdapter);
and got NullPointerExceptions at mTopSellersListView.setHasFixedSize(true)
First set your layoutManager than use setHasFizedSize(true).Since the layoutManager determines the size of your recyclerView.
I've fixed it by call setTopSellersListView() in onStart() in Fragment and it works great
Related
I have image in my fragment. I want click on the picture and... for example change the fragment. I have found the same topic How to setOnclick Listener to button in fragment but ClickListner does not work.
I have tried make the same code in Activity and onClickListner is work, but in the frame it does not work.
Below my code in the Fragment.
public class Fragment2 extends Fragment {
ImageView imageView;
MyListner listner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View getview = inflater.inflate(R.layout.fragment_2, container, false);
imageView = (ImageView) getview.findViewById(R.id.imageView1);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listner.callback();
}
});
return inflater.inflate(R.layout.fragment_2, container, false);
}
Below my interface
public interface MyListner {
public void callback();}
Below my MainActivity
public class MainActivity extends AppCompatActivity implements MyListner {
Fragment2 fragment2;
Fragment1 fragment1;
ImageView imageViewMain;
ImageView imageViewFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment2 = new Fragment2();
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();//начало транзакции объекта
ft.replace(R.id.container, fragment2);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
#Override
public void callback() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();//начало транзакции объекта
ft.replace(R.id.container, fragment1);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}}
Please, let me know where is the problem?
It seems you are inflating your fragment's view twice. Instead of this you need to return the view which you have already inflated as a result of your onCreateView inside Fragment2.
Try changing
return inflater.inflate(R.layout.fragment_2, container, false);
to
return getview;
can anyone point me in the right direction and tell me what I'm doing wrong?
I have here a fragment with a button. When the button is pressed, it needs to replace the current fragment and load a new one. I've figured how to go from Fragment to Activity, and Activity to Fragment, just not Fragment to Fragment. I'm aware this question has been asked a few times but I'm just so new I couldn't figure it out myself.
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}
I think you are not initialising the FragmentManager. Without FragmentManager it is not possible to replace,update,create any fragment. Beacuse it is responsible replace or deleting any fragment. Hope this will help.
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}
i wanna set textView in fragment from another activity which this activity is not MainActivity has fragment transaction ..
already tried some method from the other related article which related with my problem, but got an error..
here's my method inside fragment to recieve from another activity
Fragment A
public class FragmentA extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressDialog pDialog = new ProgressDialog(getContext());
pDialog.setCancelable(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_A, container, false);
//Put Data to id fragment
valueName = (TextView) layout.findViewById(R.id.valueNameNav);
valueStatus = (TextView) layout.findViewById(R.id.valueStatusNav);
}
public void setText(String name, String status){
valueName = (TextView) getView().findViewById(R.id.valueNameNav);
valueName.setText(name);
valueStatus = (TextView) getView().findViewById(R.id.valueStatusNav);
valueStatus.setText(status);
}
}
and this is how i call setText method in fragment from activity
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
FragmentA mFragment = (FragmentA )
getSupportFragmentManager().findFragmentById(R.id.fragment_A);
mFragment.setText(editValueName, lastStatus);
but got an error like this
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.example.study.fragment.fragmentA.setText(java.lang.String,
java.lang.String)' on a null object reference
100% sure there's a data string on string getText
Create a FrameLayout in your activity with id container with height width to MATCH_PARENT
Then add fragment in your activity like this
FragmentA newFragment = new FragmentA ();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment).commit();
and than set your text
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
newFragment .setText(editValueName, lastStatus);
You can useing store SharedPreferences for save your string and load it in every where.Of course, if you like to change your code.
No need to findView in setText method you should do in this way and it will work
public class FragmentA extends Fragment {
TextView valueName,valueStatus ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressDialog pDialog = new ProgressDialog(getContext());
pDialog.setCancelable(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_A, container, false);
//Put Data to id fragment
valueName = (TextView) layout.findViewById(R.id.valueNameNav);
valueStatus = (TextView) layout.findViewById(R.id.valueStatusNav);
return layout;
}
public void setText(String name, String status){
valueName.setText(name);
valueStatus.setText(status);
}
}
Try to do like this and make sure your fragment is attached with activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grupos);
if(savedInstanceState == null)
{
fragment = new FragmentA();
fragment.setTag(R.id.myfragmentId);
getFragmentManager().beginTransaction()
.add(R.id.container, fragment).commit();
}
else
{
if(fragment == null)
{
fragment = (FragmentA) getFragmentManager().findFragmentByTag(R.id.myfragmentId);
}
}
}
In myfragment class witch extends Fragment I'm finding object reference in onCreateView method
private static final String TAG = "CloadLab";
private Cloud dCloud;
private EditText dNameText;
public String dNameHolder = "";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
UUID dreamId = (UUID)getArguments().getSerializable(EXTRA_DREAM_ID);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle("Add new");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_add,parent,false);
dNameText = (EditText) v.findViewById(R.id.dream_name);
return v;
}
public void SaveDream (){
dNameHolder = dNameText.getText().toString();
if (dNameText != null) {
Log.e(TAG,"not null");
}else if (dNameText == null){
Log.e(TAG,"null");
}
}
}
which works fine if I use it within onCreateView method, but for example I want to use dNameText in this method which is in same class
public void SaveDream (){
dNameHolder = dNameText.getText().toString();
}
and now it has null object reference how can I fix that and how can I set references through whole class?
I'm calling this SaveDream() method from Activity which holds this Fragment
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorite:
AddFragment mActivity= new AddFragment();
mActivity.SaveDream();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Every Activity extends SingleFragmentActivity and has these methods in it
private AddFragment mFragment;
#Override
protected Fragment createFragment() {
UUID dreamId = (UUID)getIntent()
.getSerializableExtra(AddFragment.EXTRA_DREAM_ID);
return AddFragment.newInstance(dreamId);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorite:
// AddFragment mActivity= new AddFragment();
// mActivity.SaveDream();
//finish();
mFragment = new AddFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, mFragment);
fragmentTransaction.commit();
mFragment.SaveDream();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
SingleFragmentActivity
protected abstract Fragment createFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
if (fragment == null){
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
You are calling SaveDream method on a new instance of the fragment, not the one which is loaded right now at
AddFragment mActivity= new AddFragment();
mActivity.SaveDream();
Because the view is not created on the new instance (view is created while loading) and you are getting null for EditText. You should keep the loaded instance globally and call the method on that instance.
Follow these steps.
Step 1: Create a class level variable
private AddFragment mFragment;
Step 2: Load Fragment like this
mFragment = new AddFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, mFragment);
fragmentTransaction.commit();
Step 3: Call method like this
mFragment.SaveDream();
Update
Update method like this
#Override
protected Fragment createFragment() {
UUID dreamId = (UUID)getIntent()
.getSerializableExtra(AddFragment.EXTRA_DREAM_ID);
mFragment = AddFragment.newInstance(dreamId);
return mFragment;
}
and
case R.id.action_favorite:
mFragment.SaveDream();
return true;
I m using drawer list for my android application.
Got a issue.
When I click randomly (very fast) then I get forcestop and java.lang.IllegalStateException: Content view not yet created showing in Log.
I m using fragments
I m also getting the following Runtime error
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:32
Here is a part of my code in selecting from drawer list and
Fragment home = new Home();
Fragment feeds = new Feeds_ListView();
.....
private void selectItem(int position)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position)
{
case 0:
setTitle(title[position]);
ft.replace(R.id.content_frame, feeds);
break;
case 1:
setTitle(title[position]);
ft.replace(R.id.content_frame, NewPostFragment);
break;
case 2:
setTitle(title[position]);
ft.replace(R.id.content_frame, SearchDetailsFragment);
break;
case 3:
setTitle(title[position]);
ft.replace(R.id.content_frame, feeds1);
break;
case 4:
setTitle(title[position]);
ft.replace(R.id.content_frame, UserDetailsFragment);
break;
case 5:
setTitle(title[position]);
ft.replace(R.id.content_frame, FBActivity);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
Here is the part of Feeds_ListView();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
context=container.getContext();
rootView = inflater.inflate(R.layout.feeds_listview_layout, container, false);
list = (ListView) rootView.findViewById(android.R.id.list);
mRelativeLayout=rootView.findViewById(R.id.mRelativeLayout);
saveProgress =(ProgressBar) rootView.findViewById(R.id.loadpost);
saveProgress.setVisibility(View.INVISIBLE);
userAdapter = new CustomListAdapter(getActivity(), R.layout.feeds_listview_item,userArray);
mRelativeLayout.setVisibility(View.GONE);
list.setItemsCanFocus(false);
list.setAdapter(userAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SharedPreferences settings =getActivity().getSharedPreferences("newdatabase",0);
String user_id=settings.getString("user_id", "--");
if(user_id.equals("--") || user_id.equals(""))
{ FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, FBActivity);
ft.commit();
}else{
new Onscrollasync().execute();
((PullToRefresh_Master) getListView()).setOnRefreshListener(new OnRefreshListener()
{
#Override
public void onRefresh()
{
new Onscrollasync().execute();
}
});
}
}
The problem is with the code in the Fragment Home that you wrote in the onCreateView. Move the code in your onCreateView() to either onActivityCreated() or onViewCreated(). There are several similar question on StackOverlfow like here.
Try this instead of inflating a container,try to inflate your view without the container ie
rootView = inflater.inflate(R.layout.feeds_listview_layout,null);
Let me know if this works.