Android add view to fragment and bind adapters to views - android

Hello I'm playing around with fragments as of now, and I can't seem to find a solution to this issue..
This is what I have tried so far:
FragmentReceivingStocksHeader.class
public class FragmentReceivingStocksHeader extends Fragment {
EditText etVanTransferDocument, etDocumentNumber;
Spinner spLocationFrom, spLocationTo;
Button btExit, btProcess;
ArrayAdapter<String> adapterFrom, adapterTo;
String[] locationsFromArray, locationsToArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
initControls();
View rootView =
inflater.inflate(R.layout.fragment_receivingstocks_transactionheader, container, false);
return rootView;
}
private void initControls() {
// TODO Auto-generated method stub
spLocationFrom = (Spinner) findViewById (R.id.spLocationFrom);
spLocationFrom.setEnabled(false);
spLocationTo = (Spinner) findViewById (R.id.spLocationTo);
spLocationTo.setEnabled(false);
locationsFromArray = getResources().getStringArray(R.array.locations);
locationsToArray = getResources().getStringArray(R.array.locationsto);
adapterFrom = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
spLocationFrom.setAdapter(adapterFrom);
spLocationFrom.setSelection(1);
spLocationTo.setAdapter(adapterTo);
spLocationTo.setSelection(0);
}
But I have errors on this line:
spLocationFrom = (Spinner) findViewById (R.id.spLocationFrom);
Error Message:
The method findViewById(int) is undefined for the type FragmentReceivingStocksHeader
And also these lines:
adapterFrom = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
Error Message:
The constructor ArrayAdapter<String>(FragmentReceivingStocksHeader, int, String[]) is undefined
What am I doing wrong in here? I need your help guys. Thanks.

In your initControls method, make the following modifications :
spLocationFrom = (Spinner) view.findViewById (R.id.spLocationFrom);
spLocationTo = (Spinner) view.findViewById (R.id.spLocationTo);
and
adapterFrom = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
Explanation : findViewById is not available in Fragment like it is in Activity, so you need to use the View.findViewById method.
And the constructor or ArrayAdapter takes a Context as first argument, so Activity works but not Fragment.

The problem is, that Fragment class doesnt have method like findViewById, like Activity does. You need to use your inflated rootView.findViewById.
As for your adapters, similarly, the constructor doesnt accept Fragment type, but Context. Activity class extends Context, and you can access your activity from Fragment with getActivity() method.
See your code updated below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView =
inflater.inflate(R.layout.fragment_receivingstocks_transactionheader, container, false);
initControls(rootView);
return rootView;
}
private void initControls(View view) {
// TODO Auto-generated method stub
spLocationFrom = (Spinner) view.findViewById (R.id.spLocationFrom);
spLocationFrom.setEnabled(false);
spLocationTo = (Spinner) view.findViewById (R.id.spLocationTo);
spLocationTo.setEnabled(false);
locationsFromArray = getResources().getStringArray(R.array.locations);
locationsToArray = getResources().getStringArray(R.array.locationsto);
adapterFrom = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
spLocationFrom.setAdapter(adapterFrom);
spLocationFrom.setSelection(1);
spLocationTo.setAdapter(adapterTo);
spLocationTo.setSelection(0);
}

Related

Adding items on a spinner using a cutom function in a fragment

How do i add items to a spinner in a fragment using a custom method since i have many spinners and setting each on the create view makes the code have unprofessional looking
This is what i have tried but returns an error
I had also declared the provincespinner
private Spinner provincespinner, districtspinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_basicinfo, container, false);
addItemsOnProvinceSpinner(rootView); //this is what i would like to add items
...i have other methods to add other spinners here
return rootView;
}
This is the method that should add but returns an error
public void addItemsOnProvinceSpinner(View rootview) {
provincespinner = (Spinner) rootview.findViewById(R.id.fivms_farmerprovince);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list); //This returns an error
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
provincespinner.setAdapter(dataAdapter);
}
How do i go about this
Modify your line like this:
ArrayAdapter<String> dataAdapter = new
ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, list);
the first parameter is context and you are passing this which works for activity

How to implement a simple to do list using a listview?

I'm trying to implement a simple to do list using this solution Add user input into a ListView on button click, but when I implement the onCreate of the solution I get the following errors http://pastebin.com/9CBCMrjv I'm using fragments in this application and I'm wondering could this be causing the errors as maybe the constructors don't apply to fragments.
Can someone make sense of the errors or where I'm going wrong with this implementation? My understanding of the errors is that this solution can't be applied to my class as it is linked to a fragment instead of a plain activity.
This is the complete class to give you a better understanding of the problem:
public class TopRatedFragment extends Fragment implements OnClickListener {
ListView mListView;
EditText mValue;
Button mAdd;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_top_rated);
mAdd = (Button)findViewById(R.id.newList);
mAdd.setOnClickListener(this);
mValue = (EditText)findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)findViewById(R.id.listView);
mListView.setAdapter(adapter);
}
public void onClick(View v)
{
String input = mValue.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
}
}
The errors
The method setContentView(int) is undefined for the type TopRatedFragment
The method findViewById(int) is undefined for the type TopRatedFragment
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (TopRatedFragment)
The method findViewById(int) is undefined for the type TopRatedFragment
The constructor ArrayAdapter<String>(TopRatedFragment, int, ArrayList<String>) is undefined
The method findViewById(int) is undefined for the type TopRatedFragment
setContentView(R.layout.fragment_top_rated);
wrong
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mAdd = (Button)rootView.findViewById(R.id.newList);
mAdd.setOnClickListener(this);
mValue = (EditText)rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity, android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)rootView.findViewById(R.id.listView);
mListView.setAdapter(adapter);
return rootView;
}
You need to inflate a view in onCreateView and return the view
Also you use the inflated view object to initialize your views
The constructor ArrayAdapter<String>(TopRatedFragment, int, ArrayList<String>) is undefined
So change to
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, list);
get rid of the codes in onCreate

ListView data not showing in fragment

Here's the code that's producing unexpected results. If anyone can please guide me to what I'm doing wrong here
public static class LaunchpadSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
ListView moviesList= (ListView) rootView.findViewById(R.id.movies_list);
ArrayAdapter<String> moviesAdapter;
List<String> Testing = new ArrayList<String>();
Testing.add("Hey");
Testing.add("Hey");
Testing.add("Hey");
Testing.add("Hey");
moviesAdapter= new MyAdapter(getActivity(),android.R.layout.simple_list_item_1,Testing);
moviesList.setAdapter(moviesAdapter);
return rootView;
}
Ok after playing around a Lot going through documentation I finally found a workaround to this.
This is what I did
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
super.onActivityCreated(savedInstanceState);
Log.d("CreatedActivity", "LaunchpadFragment");
ListView moviesList= (ListView) getActivity().findViewById(R.id.movies_list);
// Gets the ListView from the View list of the parent activity
// Gets a CursorAdapter
ArrayAdapter<String> moviesAdapter;
List<String> Testing = new ArrayList<String>();
Testing.add("Hey");
Testing.add("Hey Do");
Testing.add("Hey It");
Testing.add("Hey Please");
moviesAdapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, Testing);
moviesList.setAdapter(moviesAdapter);
}
Note the over-ridden method here, it is
onActivityCreated
Android documentation states
If your view of the fragment is a listview that is being filled by a data adapter, you should override the onActivityCreated method and do the filling in there.
I don't have a documentation link to this blockquote though:|

The constructor ArrayAdapter<String>(LayoutNext, int, String[]) is undefined

I try to implement the items to a Spinner from a android.support.v4.app.Fragment class. I always get the compiler Error
The constructor ArrayAdapter(LayoutNext, int, String[]) is undefined
How can I fix this?
Here is the code:
public class LayoutNext extends Fragment
implements OnClickListener,OnItemSelectedListener{
TimePicker timepicker;
private Spinner spinner_next;
public ArrayAdapter<String> adapter;
public static Fragment newInstance(Context context) {
LayoutNext f = new LayoutNext();
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_next, null);
timepicker = (TimePicker) root.findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);
timepicker.setCurrentHour(0);
timepicker.setCurrentMinute(0);
String[] items_next = { "Next", "From to"};
spinner_next = (Spinner) root.findViewById(R.id.sp_next);
spinner_next.setOnItemSelectedListener(this);
// Here I get the error
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items_next);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_next.setAdapter(adapter);
return root;
}
Unlike Activities, Fragments are not subclasses of Context so you cannot use this where a Context is required. Simply use getActivity() instead.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_spinner_item,
items_next);

How to set ArrayAdapter for spinner in Fragment

I am trying to add items to spinner in fragment. But i am having problem with the context. Because in fragment there is no context. Here how i am doing
public class DetailFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View scrollView = inflater.inflate(R.layout.myscrollview , container, false);
LinearLayout linearLayout = (LinearLayout) scrollView.findViewById(R.id.mylayout1);
for (int i=0; i<questionList.size(); i++) {
View verticalLinearLayout = inflater.inflate(R.layout.mylistrow, null);
View horizontalLInearLaoyout = verticalLinearLayout.findViewById(R.id.questionRow);
TextView tv = (TextView) horizontalLInearLaoyout.findViewById(R.id.question);
Spinner spinner = (Spinner) horizontalLInearLaoyout.findViewById(R.id.spinner);
//Problem: how to define this in fragment createFromResource(this,...)
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.options_array, android.R.layout.simple_spinner_item);
EditText editText = (EditText) verticalLinearLayout.findViewById(R.id.txtMultiLine);
String question = questionList.get(i).question;
tv.setId(i);
tv.setText(i + question);
spinner.setId(i);
editText.setId(i);
linearLayout.addView(verticalLinearLayout);
}
return scrollView;
} //end of onCreateView()
} //end of class DetailFrag
In fragments, context is not available the way you expected in your code. Instead of this, use the following:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getBaseContext(),
R.array.options_array,
android.R.layout.simple_spinner_item);
Since there we are in a Fragment,'this', won't work thus:
Using getActivity().getBaseContext() should be used to replace 'this';
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(getActivity().getBaseContext(),
android.R.layout.simple_spinner_dropdown_item,
listItems);
Note on older versions of Android there is getContext() which will return context of the fragment as well, but for new versions it might not return context. Thus using getActivity() you are turned a Activity which is a context.
We use getActivity() which gets the current activity you are in followed by getBaseContext() since there can be multiple Context initiated in the Activity. We want to get the one that the Activity itself uses.
do something like :
private Context myContext = null;
public DetailFrag(Context ctx){
myContext = ctx;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
myContext, R.array.options_array, android.R.layout.simple_spinner_item);
//
}

Categories

Resources