using "this" in a fragment gives me an error - android

public class Home extends Fragment {
ArrayList<String> notes = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ListView listView = (ListView) getActivity().findViewById(R.id.listView);
notes.add("Example note");
ArrayAdapter arrayAdapter =new ArrayAdapter(this, android.R.layout.simple_list_item_1,notes);
listView.setAdapter(arrayAdapter);
return inflater.inflate(R.layout.home,container,false);
}
when i use this it gives me an error, tried using getactivity or getcontext and both crash the app when i do it
where did i go wrong
any suggestions are welcomed and thanks in advance <3

You must get corresponding fragment view by below 2 lines
View myView = inflater.inflate(R.layout.fragment_view, container, false);
ListView lv = myView.findViewById(R.id.listView);

getActivity() may be null while your fragment is in process of preparation.
Just inflate your fragment layout in onCreateView and place ListView logic to onViewCreated() or onActivityCreated
Get listview from fragment by inflate, not from parent activity

ArrayAdapter needs a context as the first parameter, so either use this.getContext() or this.getActivity() instead of passing this, which is a fragment.
Furthermore, you should move the code into onViewCreated method, as the view must be inflated before you access its elements.
And you have to use view.findViewById() instead of getActivity().

For some reason Fragments do not inherit the context from an Activity. Try this:
ListView listView = ((ListView) getActivity()).findViewById(R.id.listView);
Same works for getContext.
Context context = ((ListView) getActivity)).getApplicationContext();

Related

Updating the ListFragment

#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_schedule, container, false);
// array adapter + list fragment
arrayAdapter = new ArrayAdapter<>(getActivity(),
R.layout.simple_list_item_1_custom,
schedules.get(getArguments().getInt(ARG_SECTION_NUMBER) - 1)); //
arrayAdapter.setNotifyOnChange(true);
setListAdapter(arrayAdapter);
return rootView;
}
This is the onCreateView of my class that extends ListFragment, I am trying to update the contents of the list from my activity, so far I've tried clearing the arrayAdapter and calling notifyDataSetChanged on it, and it doesn't work. The only way I can get my list to update is if I swipe two tabs and go back again, then it shows all the changed values. Any suggestions?
This is the onCreateView of your fragment. This is fired every time when you create your fragment or swipe between tabs. As I understand, you just add values to the db onClick and when you go and come back your fragment you see the new values.
Please, try adding new values to your adapter on onClick button then try updating your list in the same scope with the NotifyDataChanged mechanisim of the adapter.
If I get wrong idea about whay you are doing pleas share more code.

getListView is missing

I have created a ListView to list all the activities but when I wanna call the method, I can't find getListView
My activity_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/ListActivity"
android:layout_width="wrap_content"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
and in my MainActivity.java seems like there's an error with
getListView
method, I've no idea why
You can use getListView() when working with ListActivity not the usual Activity. In your code you got it wrong and made the ListView with id "a special identifier to the view" ListActivity, so to access it in your code you simply
ListView lv = (ListView) findViewById(R.id.ListActivity);
Your activity must inherit from a ListActivity. Your class should start with
public class MyListAdapter extends ListActivity {
...
}
Then you can use the method
getListView()
This is the official documentation
Second solution
If you use a fragment, then you can access your ListView by using
ListView lv = (ListView) rootView.findViewById(R.id.id_of_your_listView);
The rootView is the view you get in your onCreateView Method of the Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.example_fragment, container, false);
return rootView;
}
Try using (ListView)findViewById(R.id.ListActivity) instead of getListView()
If you have the ListView in the fragment you can use:
ListView list = (ListView)findViewById(android.R.id.list);
But if you want to use getListView directly you must call the ListView's id as
android:id="#android:id/list"
Hope this help.
also note that you dont pass your ListView to the adapter but you pass the adapter to the ListView
ListView list = (ListView)findViewById(R.id.ListActivity);
list.setAdapter(adapter);
You can't extend ListActivity because 1) You are wanting to use Fragments and 2) there isn't a method setSupportActionBar for the ListActivity class...
Anyways... in your question
My activity_fragment.xml
<!-- XML code -->
You can't use findViewById to get that ListView within the Activity class because your ListView isn't within activity_main.xml.
You have to do it from within the Fragment.
public class YourFragment extends Fragment {
private ListView yourListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_fragment, container, false);
this.yourListView = (ListView) v.findViewById(R.id.listView);
// adapter stuff...
return v;
}
}

JSONPARSING error in findViewById

Here's my code in the main activity don'tn know why error in findViewById occurs
.. this is just my first time in JSON paarsing .
public class HomeFragment extends Fragment{
public HomeFragment(){}
View rootView;
ListView list;
ActorsAdapter adapt;
ArrayList<Actors> actorslist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
list = (ListView)findViewById(R.id.listFeeds);
actorslist = new ArrayList<Actors>();
return rootView;
new ActorsAsynTask().execute("http://jcasim.5gbfree.com/Project/login.php");
}
listFeeds It's a component I'm pretty sure is a component that lives in your fragment. Since you haven't return the root view yet, the findViewById is not going to find it. you have to wait until it's on screen to ask for it using findViewById (in onStart() method) or ask it form the root view before you return it.
it would be list = (ListView)rootView.findViewById(R.id.listFeeds);
The View of the Fragment is not set before the onCreateView() returns. Therefore the findViewById() tries to find the specified R.id.listFeedsfrom a null reference.
Try this instead list = (ListView)rootView.findViewById(R.id.listFeeds);

why we access like that getActivity().findViewById()

When a layout , which is defined for a Fragment and used inside setContentView() method and it has no relation with Activity .
then why we need Activity Reference to access it .
so I want to create a ListView , inside a Fragment . than i have to create it inside Activity layout or inside Fragment layout .
Hey Neil , i have a question because every time I have made a mistake because , i am performing this
TextView txt = ( TextView ) getActivity().findViewById(R.id.txt);
txt.setText("nayak nahi , khalnayak hun mein");
inside oncreateView() so it is creating problem but when ever i am implementing this inside
onActivityCreated() , it is working , so can you please tell me Why this is happening .
if you want to find the view by getActivity(), you should do that after onCreateView is called, because till onCreateView is called the view of fragment is null. So you can do:
#Override
public void onResume() {
super.onResume();
TextView txt = ( TextView ) getActivity().findViewById(R.id.txt);
txt.setText("nayak nahi , khalnayak hun mein");
}
You can define a ListView in a layout for your Fragment. Try something like this in your fragment to define a alternative layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
_baseView = inflater.inflate(R.layout.yourlayout, null); //where base view is your upper most parent in your layout
return _baseView;
}
Then in your onActivityCreated you can use _baseView.findViewById('yourListView') to set your ListView. I don't know if this is best practice but it works perfectly for me.
In Fragment you should use its View but getActivity:
public View onCreateView(…){
View rootView = inflater.inflate(R.layout.listview_xml_file, container, false);
ListView ListNewsBelarus = (ListView) rootView.findViewById(R.id.listViewId);
return rootView;
}

Error populating spinner in a fragment

I have a Activity with two fragments. One of them hava a spinner. When I populate it the app crashes.
I don't know why. In android developers it's confused how do it in fragments, it seems is diferent like normal activity.
Thanks!
public class InstrumentsFrag extends Fragment {
TextView tv1;
Spinner sp;
String[] os = {"Cupcake v1.5", "Donut v1.6", "Éclair v2.0/2.1", "Froyo v2.2",
"Gingerbread v2.2", "Honeycomb v3.0/3.1"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.instruments, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = (Spinner) getActivity().findViewById(
R.id.spinner1);
ArrayAdapter <CharSequence>adapter = ArrayAdapter.createFromResource( getActivity(), R.array.sections , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
I had the same problem where my app crashed when populating a spinner. In my case, the spinner I was populating was defined in the fragment's XML file, so the trick was getting findViewById() to find it. I see in your case you tried to use getActivity():
sp = (Spinner) getActivity().findViewById(R.id.spinner1);
I also tried using both getActivity() and getView(), and both caused crashes (null spinner, and NULL Pointer exception respectively).
I finally got this to work by replacing getActivity() with the fragment's view. I did this by populating the spinner when onCreateView() is called. Here are some snippets from my final code:
private Spinner spinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.myFragmentXmlFile, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
...
}
private void setSpinnerContent( View view )
{
spinner = (Spinner) view.findViewById( R.id.mySpinner );
...
spinner.setAdapter( adapter );
...
}
So I passed the fragment view into my function and referenced that view to configure the spinner. That worked perfectly. (And quick disclaimer - I'm new to Android myself, so perhaps some of the above terminology can be corrected or clarified if needed by more experienced people.)
Hope it helps!

Categories

Resources