I am trying to have a checkable list view fragment pop up with a button at the top of the list view. After user clicks an item in the navigation menu, the main activity will be populated with my button and list view fragment. I'm getting 'invoke virtual method' error, even though the element in declared. Here's some code.
My list fragment class:
public class ThingsManager extends Fragment {
ArrayList<String> selectedItems;
ListView checkable_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(layout.things_manager_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}
public ThingsManager() {
// Required empty public constructor
}
}
List fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ThingsManager">
<TextView
android:id="#+id/things_manager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Things Manager"
android:textSize="25dp"/>
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/checkable_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Should I be controlling the listview in MainActivity or in the FragmentClass ?
Move your all your view initialization and listview setup code from onActivityCreated to onCreateView method.
And your this statement
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
is wrong. You have to find ListView from the view you have inflated in onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(layout.things_manager_fragment, container, false);
init(rootView);
return rootView;
}
public void init(View rootView){
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list = rootView.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}
Related
I am using fragments in my app. Every fragment has a listview. The ListViews are custom listviews containing a single image view.
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="#android:drawable/ic_notification_overlay" />
The listview items are images. I want to implement searchview. I want to search by name of each listview item eg "jingle bells etc" and also by number i.e "1,2. . . and so on.
My java file containing listview titles is.
public class carolFrag extends Fragment {
//code
public carolFrag() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
private static final String TAG = "carolFrag";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup main_content, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_carol, main_content, false);
final int[] menuImage = {R.drawable.carol_1_title, R.drawable.carol_2_title,R.drawable.carol_3_title,R.drawable.carol_4_title,R.drawable.carol_5_title,R.drawable.carol_6_title,R.drawable.carol_7_title,R.drawable.carol_8_title,R.drawable.carol_9_title,R.drawable.carol_10_title,R.drawable.carol_11_title};
final ListView listView = (ListView) view.findViewById(R.id.CarolList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent1 = new Intent (getActivity(), PackageC.class)
intent1.putExtra("position", position);
startActivity(intent1);
}
});
AdapterCarols adapter = new AdapterCarols(getContext(), menuImage);
listView.setAdapter(adapter);
// Inflate the layout for this fragment
return view;
}
}
I am unable to make any logic as the array has drawables in it.
Because the array is full of drawables, and it's not a database thing or anithing every solution you i'll get will be a work around. The simples, i believe, is to have another array maybe an - String[] - with the names of the drawables in the same order they are in the original - final int[] menuImage - you can make the search in the array of String and save the position of the results. Then use those positions to create a new array ( int[] ) putting in this new array the drawables that matches those positions. Finally change the adapter of the list view, passing the array with the results and notifydatachange(); in the listview for it to update visually.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
main_content, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_carol, main_content, false);
final int[] menuImage = {R.drawable.carol_1_title, R.drawable.carol_2_title,R.drawable.carol_3_title,R.drawable.carol_4_title,R.drawable.carol_5_title,R.drawable.carol_6_title,R.drawable.carol_7_title,R.drawable.carol_8_title,R.drawable.carol_9_title,R.drawable.carol_10_title,R.drawable.carol_11_title};
final ListView listView = (ListView) view.findViewById(R.id.CarolList);
SearchView sv = view.findviewById(R.id.searchview);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String par1)
{
return false;
}
public boolean onQueryTextSubmit(String par1)
{
int [] searchresults = PerformSearch(par1);
AdapterCarols newadapter = new
AdapterCarols(getContext(), searchresults);
listView.setAdapter(adapter);
listview.invalidate(); // don't remember listview refresh method. I work with Recyclerview, they have a notifyDatasetChange(); method.
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent1 = new Intent (getActivity(), PackageC.class)
intent1.putExtra("position", position);
startActivity(intent1);
}
});
AdapterCarols adapter = new AdapterCarols(getContext(), menuImage);
listView.setAdapter(adapter);
// Inflate the layout for this fragment
return view;
}
private int[] PerformSearch(par1)
{
String [] strcarols = {carol_1_title,carol_2_title,carol_3_title,carol_4_title,carol_5_title,carol_6_title,carol_7_title,carol_8_title,carol_9_title,carol_10_title,carol_11_title};
int[] menuImage = {R.drawable.carol_1_title, R.drawable.carol_2_title,R.drawable.carol_3_title,R.drawable.carol_4_title,R.drawable.carol_5_title,R.drawable.carol_6_title,R.drawable.carol_7_title,R.drawable.carol_8_title,R.drawable.carol_9_title,R.drawable.carol_10_title,R.drawable.carol_11_title};
int[] results = new int[];
int carolsresultcount = 0, index =0;
/// simplest way
for(String carol:strcarols)
{
if(carol.contains(par1))
{
results [carolsresultcount++] = menuImage [index];
}
index++;
}
return results;
}
I hope this can solve your problem.
I made a listview and I wanted to make an user input a choice. How can I do this? Atm I only managed to create the ListView and display the data.
Is there an easy way to get the value of a selected item of the ListView and use it later? Something like a ListView RadioButton.
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tiagosilva.amob_android.TubeDataArchive" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_tubeData"
android:choiceMode="singleChoice">
</ListView>
Listview:
public class TubeDataArchive extends Fragment {
public TubeDataArchive() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tube_data_archive, container, false);
ListView tubeDataList = (ListView) view.findViewById(R.id.lv_tubeData);
//load tube data
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
String tubeDataString = settings.getString("tubeData", "");
String[] tubeDataSplit = tubeDataString.split("\n");
List<String> tubeDataItems = new ArrayList<>();
for(int i=0; i<tubeDataSplit.length;i++)
{
tubeDataItems.add(tubeDataSplit[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, tubeDataItems);
// Assign adapter to ListView
tubeDataList.setAdapter(adapter);
return view;
}
}
Is there an easy way to get the value of a selected item of the
ListView and use it later?
Add onItemClickListener after the for loop.
tubeDataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// do whatever you want
Log.d("############","Items " + tubeDataSplit[arg2] );
}
});
Something like a ListView RadioButton
If you want to have a listview with a radio button, then you need to create a custom listview layout.
Add ItemClickListener to your listview
tubeDataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getapplicationcontext(), tubeDataItems.get(id),
Toast.LENGTH_LONG).show();
}
});
I am trying to add 2 spinner in a fragment.These spinners are interconnected.When user select a value,2nd spinner will be populated with value.
Example:1st spinner have 2 values as "Car" & "Bus".
When users select "car",2nd spinner will be populated by color of the car as "Red","Blue".Again,if user select Bus,2nd spinner will be populated by color of bus as "Green","White".
I have made this in mainactivity successfully.But when I try to implement in a fragment ,2nd spinner is not populated and also there is no error showing.
I am providing the code that I have tried to implement in fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_info_form, container, false);
//spCountries = (Spinner) v.findViewById(R.id.idCrimePlace);
//set the spinners
crimePlace = (Spinner) rootView.findViewById(R.id.idCrimePlace);
metro = (Spinner) rootView.findViewById(R.id.idMetro);
crimePlace.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
crimePlace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spCrimePlace= String.valueOf(crimePlace.getSelectedItem());
//Toast.makeText(this, crimePlace, Toast.LENGTH_SHORT).show();
if(spCrimePlace.contentEquals("Car")) {
List<String> list = new ArrayList<String>();
list.add("Red");
list.add("Blue");
list.add("Others");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
metro.setAdapter(dataAdapter);
}
if(spCrimePlace.contentEquals("Bus")) {
List<String> list = new ArrayList<String>();
list.add("Green");
list.add("White");
list.add("Other");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
metro.setAdapter(dataAdapter2);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
Try calling your adapter like:
ArrayAdapter dataAdapter = new ArrayAdapter(this.getActivity(),
android.R.layout.simple_spinner_item, list);
And also use equals() instead of contentEquals
I have one fragment contain list view, buttons and images.Buttons,images and other widget loaded correctly but instead of list view it shows only loading icon
public class ListDetails extends SherlockFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
ListView listView = (ListView)container.findViewById(R.id.list_view2);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
return inflater.inflate(
R.layout.listdetails_fragement, container, false);
}
I have check other Button,Images are Loaded but List view gives error on my ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values); line
here i provided my logcat error.
Here's what I did:
Instead of doing everything in onCreateView(), I used onActivityCreated().
In onActivityCreated(), I just added this code:Here's the implementation:
public class Database extends Fragment {
public ViewPager viewPager;
private AllPagesAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Tab1", "Tab2" };
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
ArrayAdapter<String> mArrayAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View databaseview = inflater.inflate(R.layout.database, container,
false);
return databaseview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
ListView mListView = (ListView)getActivity().findViewById(R.id.databaselist);
mArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
mListView.setAdapter(mArrayAdapter);
}
}
And the layout I used was :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/databaselist"
android:layout_width="match_parent"
android:layout_height="254dp" >
</ListView>
<TextView
android:id="#+id/newmainlist"
android:layout_width="match_parent"
android:layout_height="250dp"
android:gravity="center"
android:text="database" />
</LinearLayout>
Also, here's the image for it:
Hope this helps .. :)
The error because of this line..
ListView listView = (ListView)container.findViewById(R.id.list_view2);
here listview is null
change your code like this..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.listdetails_fragement, container,
false);
ListView listView = (ListView) view.findViewById(R.id.list_view2);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation", "Simple List View In Android",
"Create List View Android", "Android Example",
"List View Source Code", "List View Array Adapter",
"Android Example List View" };
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
.getApplicationContext(), android.R.layout.simple_list_item_1,
android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
return view;
}
Change onCreateView(....) with this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(
R.layout.listdetails_fragement, container, false);
ListView listView = (ListView)v.findViewById(R.id.list_view2);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
return v;
}
I have some issues with a listview in a Fragment.
I want to show a List with Fruits in the Fragment, tried a few things but.
In a later version the String[] should contain data from a json object.
This is the current status:
public class fragmentA extends Fragment
implements View.OnClickListener {
TextView textView;
ViewStub viewStub;
ListFragment listView;
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// das Layout fuer dieses Fragment laden
View view= inflater.inflate(R.layout.fragmenta, container, false);
// inflate layout
Button notfallbtn = (Button) view.findViewById(R.id.notfallbtn);
textView = (TextView) view.findViewById(R.id.textView);
// listView = (ListFragment) view.findViewById(R.id.einkaufsliste);
viewStub = (ViewStub) view.findViewById(R.id.viewStub);
viewStub.setVisibility(View.GONE);
// initialize button using the inflated view object
notfallbtn.setOnClickListener(this);
// listener for button
setListAdapter(new ArrayAdapter<String>(this, R.layout.einkaufsliste,FRUITS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
return view; // return inflated view
}
The error messages I get:
Cannot resolve 'setListAdapter'
Cannot resolve 'einkaufsliste'
Any help will be greatly appreciated.
public class fragmentA extends Fragment
does not extend ListFragment. setListAdapter is a method of ListFragment.
http://developer.android.com/reference/android/app/ListFragment.html
Also you probably need
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,FRUITS)
Instead of this use getActivity() which returns the activity this fragment is associated with.
Also read
http://developer.android.com/reference/android/app/ListActivity.html
Also override onActivityCreated and use ListView lv = getListView().