How to get string array from xml to fragment's java file? - java

Below code shows null pointer exception..
public class MyFragment extends Fragment {
private String[] eArray = getActivity()
.getResources()
.getStringArray(R.array.English);
What are the other options, searching in stackoverflow did not give me success..
I am using FragmentPagerAdapter also.. which is not related to this eArray.. but it contains data for images.

getActivity() is returning null because you are using it before fragment get attached to Activity.
You need to initialize this at onCreateView
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
eArray = getActivity().getResources().getStringArray(R.array.English);
}

Related

How to use base activity in fragment?

Here i implemented a emoji-keyboard.
For the use of this library , activity extended to EmojiCompatActivity.
prepareKeyboard(EmojiCompatActivity activity, EmojiEditText input
This is working well in activity. While using in fragment i tried this one
prepareKeyboard((ActivityName)getActivity,input)
Here is my MainActivity
public class MainActivity extends EmojiCompatActivity {}
And fregment class is
public class PagerEmojKeyboard extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.emoji_keyboard, container, false);
EmojiEditText userMessageInput = getActivity().findViewById(R.id.input_message);
EmojiKeyboardLayout emojiKeyboardLayout=(EmojiKeyboardLayout) v.findViewById(R.id.keyboard_emoj);
emojiKeyboardLayout.prepareKeyboard((MainActivity) this.getActivity(),userMessageInput);
return v;
}
}
You can refer to the base activity as this.activity.
Sometimes, while using fragments, the above method also works.
If you are working in the method onCreateView you shouldn't have problems but if you have other method there is a View variable that you must have as a global for use throughout the class.

non-static method <T>findViewById(int) cannot be referenced from a static context

My first app is working fine alone but now I am trying to add tabs following a tutorial but I get stuck.
I've been searching and many users had same issue, I've tried those solutions but still unable to get it working fine.
My App
package es.ea1ddo.antenacubica;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frecuencia = findViewById(R.id.frecuencia);
cal3el = (Button) findViewById(R.id.calcular3);
And now this is where I am trying to copy the previous app
package es.ea1ddo.calculadoraantenascubicas;
public class TabFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v= inflater.inflate(R.layout.tab_fragment_2, container, false);
frecuencia = EditText.findViewById(R.id.frecuencia);
cal3el = (Button) getView().findViewById(R.id.calcular3);
I've been searching around, trying many examples and different ways but I am stuck.
You can see I added getView(). before every findViewById but I am still getting same error:
non-static method findViewById(int) cannot be referenced from a static context where T is a type-variable:
T extends View declared in method findViewById(int)
Please any advice?
Thanks
In your fragment code, you have two problems.
The first, as others have pointed out, is that View.findViewById() is a non-static method, so you would invoke it like myView.findViewById() as opposed to EditText.findViewById().
The second relates to how the Fragment's getView() method works. This method only works after onCreateView() has returned, because getView() returns whatever onCreateView() returned. That means that you can't call getView() from within onCreateView(); it will always return null.
Put together, your code should look like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v= inflater.inflate(R.layout.tab_fragment_2, container, false);
frecuencia = (EditText) v.findViewById(R.id.frecuencia);
cal3el = (Button) v.findViewById(R.id.calcular3);
...
}
replace
frecuencia = EditText.findViewById(R.id.frecuencia);
cal3el = (Button) getView().findViewById(R.id.calcular3);
with
recuencia = (EditText) v.findViewById(R.id.frecuencia);
cal3el = (Button) v.findViewById(R.id.calcular3);
if not work please add full xml code in your question
Replace
EditText.findViewById
with
(ExitText) getView().findViewById
However, this will result in a NullPointerException.
You need to move any code that uses getView() into onViewCreated(), or reference v instead.

How to Use Parse.com Lists in Tabs?

I've got the following function:
public static class ListFragment extends Fragment {
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View rootView = inflater.inflate(R.layout.fragment_list, container, false );
mainAdapter = new ParseQueryAdapter<ParseObject>( this, "Todo" );
mainAdapter.setTextKey("title");
mainAdapter.setImageKey("image");
// Initialize ListView and set initial view to mainAdapter
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(mainAdapter);
mainAdapter.loadObjects();
return rootView;
}
}
The errors returned are:
The constructor ParseQueryAdapter(MainActivity.ListFragment, String) is undefined MainActivity.java
Cannot make a static reference to the non-static method findViewById(int) from the type Activity MainActivity.java
I can assume that the first one due to the change of the object of type this but I would like a more seasoned input on the correct fix.
The second error though thoroughly confounds as it appears to be valid to my eyes.
Appreciate any input.
1) Change the instantiation of ParseQueryAdapter as follows. The code is in a Fragment, but ParseQueryAdapter requires a Context object.
mainAdapter = new ParseQueryAdapter<ParseObject>( this.getActivity(), "Todo" );
2) Remove the static modifier from your class definition.

FragmentStatePagerAdapter NullException

I have two fragments that contains ViewPager. The first fragment that contain viewPager works very well. As I come to second fragment that contain ViewPager, I start to get FragmentStatePagerAdapter NullException. I knew what is the problem, I need to implement onDetach function to get rid this problem. I search around the internet, there is a lots of solutions. And I'm currently using API 19. So maybe this solution very suitable for me. But I don't know how to use the solution.
getSupportFragmentManager().beginTransaction().detach(mFragment1).replace(R.id.main, mFragment2).attach(mFragment2).addToBackStack(null).commit();
What is exactly mFragment1 and mFragment2 and R.id.main ?
Fragment 1
public class fragment1 extends fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_restaurantprocess, container, false);
adapter = new RestaurantProcessPageAdapter(getActivity().getSupportFragmentManager());
...
}
}
Fragment 2
public class fragment2 extends fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_feedpage, container, false);
adapter = new RestaurantFeedPageFragment(getActivity().getSupportFragmentManager());
...
}
}
I'm using slide animation to fragment
public void changeFragment_toRight(Fragment frag) /* Slide to right screen */ {
if (getSupportFragmentManager().findFragmentByTag("frag")!=null)
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.right_slide_in, R.anim.right_slide_out).replace(R.id.container, frag, "frag").commit();
else
getSupportFragmentManager().beginTransaction().add(R.id.container, frag, "frag").commit();
}
changeFragment_toRight(new fragment1());
changeFragment_toRight(new fragment2());
Source: Click here to view the source
It looks like the problem is that you are manually using a FragmentTransaction to change fragments. A ViewPager will do this automatically when you supply it with an adapter, so when you change fragments, you are trying to remove a fragment that has already been removed.

How did I stop IllegalStateExceptions from being thrown with LayoutInflater().inflate(int resource, ViewGroup root, boolean attachToRoot)?

I recently recently ran into an issue while setting up a viewpager with 3 fragments. When the application ran it crashed with a
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
Here is the code for creating list list of fragments to pass to the pageAdapter.
private Vector<Fragment> getFragments() {
Vector<Fragment> list = new Vector<Fragment>();
list.add(new Fragment1());
list.add(new Fragment2());
list.add(new Fragment3());
return list;
Each of the fragments were essentially the same except for a being created with different layouts. Here was the original code I had for one of the fragments.
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment1, container);
return v;
}
}
But when I ran it like this it kept crashing with the IllegalStateException. I found that the issue was coming from the fragments being created. After some Googling I tried changing the code for the fragment to this.
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment1, container, false);
return v;
}
}
This resolved the issue and I no longer got the IllegalStateException except I have no idea how this worked. What exactly does this boolean do? And what does this exception mean? I had tried adding the method call like it suggusted but that did not resolve it. Also I tried changing this boolean to true and I got the same error again. The android docs say its attachToRoot but isn't that what I want to do? Attach my 3 fragments to the rootview, which is the viewpager? If anyone could explain this it would be greatly appreciated.
The boolean parameter of the 3-arg version of LayoutInflater.inflate() determines whether the LayoutInflater will add the inflated view to the specified container. For fragments, you should specify false because the Fragment itself will add the returned View to the container. If you pass true or use the 2-arg method, the LayoutInflater will add the view to the container, then the Fragment will try to do so again later, which results in the IllegalStateException.

Categories