I have a spinner that let user choose a meal from a set of string array in xml. After the user selected the item, I put the selection into the database, and display on a Listview.
In my model, I have a toString(),
#Override
public String toString() {
return id + " " + note +"\n meal: " + this.meal;
}
In the controller class for editing the the meal, I have this,
public class EditNoteFragment extends Fragment implements
OnItemSelectedListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_edit,
container, false);
// populating the spinner with string array of time category
spinner = (Spinner) rootView.findViewById(R.id.spinner_meal_category);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getApplicationContext(), R.array.meal_array,
android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
meal = parent.getItemAtPosition(pos).toString();
Log.i(LOGTAG, "Got the meal: " + meal);
}
public boolean onOptionsItemSelected(MenuItem item) {
// I added the field variable meal into the datebase in this block of code
//note.setMeal(meal.toString());
}
}
I used log to verified that I got the user choice and stored in the field variable "meal" in my class, but when I run the application and the list displays meal as null.
I am certain that I have successfully added the meal into the database.
Here is the view class
public static class NoteFragment extends ListFragment {
TextView tx_list_note;
NoteDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
datasource = new NotesDataSource(getActivity());
datasource.open();
List<Note> notes = datasource.findAll();
if (notes.size() == 0) {
createData();
notes = datasource.findAll();
}
ArrayAdapter<Note> adapter = new ArrayAdapter<Note>(getActivity(),
android.R.layout.simple_list_item_1, notes);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes,
container, false);
return rootView;
}
}
}
in fragment_notes.xml, I have one single listview in the relative layout
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true"
>
</ListView>
Thank you very much for you help in advance. Any suggestion would be appreciated.
Related
I am trying to obtain the selected value from a spinner to store it and use it later. I have tried in two different ways:
return null value
print only the first value of the list, when I select another value it does not print anything.
way 1
public class genera_debate extends Fragment implements AdapterView.OnItemSelectedListener {
public String text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_genera_debate,container,false);
list_of_interest =view.findViewById(R.id.subject_of_interest);
String [] subject = {"Tema de interés","Política","Deporte","Animales","Videojuegos","Economía","Medicina","Cultura","Ciencia","Tecnología","Música","Otros"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, subject);
list_of_interest.setAdapter(adapter);
list_of_interest.setOnItemSelectedListener(this);
Toast.makeText(getActivity(), "value is"+text, Toast.LENGTH_SHORT).show();
return view;}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
text=list_of_interest.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
way 2
public class genera_debate extends Fragment implements AdapterView.OnItemSelectedListener {
public String text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_genera_debate,container,false);
list_of_interest =view.findViewById(R.id.subject_of_interest);
String [] subject = {"Tema de interés","Política","Deporte","Animales","Videojuegos","Economía","Medicina","Cultura","Ciencia","Tecnología","Música","Otros"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, subject);
list_of_interest.setAdapter(adapter);
list_of_interest.setOnItemSelectedListener(this);
text=list_of_interest.getSelectedItem().toString();
Toast.makeText(getActivity(), "value is"+text, Toast.LENGTH_SHORT).show();
return view;}
}
I hope you can help me, regards
Define your Toast inside the onItemSelectedListener method.
The problem here is that the Toast is being called when your view is being created as it is inside the onCreate method which is called once your activity starts hence your Toast is being called only when your view is being created that means only once.
If you want it to be appeared every time you select a new value you need to define it inside the onItemSelectedListener as this method will be called every time you select a new value in the drop down .
Hope this helps you.
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
}
});
}
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 have a ListFragment with some data. I am trying to sort the content of my list depending on which item I select from the menu. How can I update the content of the list when I select one option from the menu? I don't want to create another fragment, I just want to sort by name or by date the info that I have in the list so when I click one item in the menu the list updates immediately depending on whether I click sort by name or sort by date.
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_sort_by_name) {
Fragment currentFragment = this.getFragmentManager().findFragmentById(R.id.fragment1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.Months, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
}
return super.onOptionsItemSelected(item);
}
And then I have the java class for the fragment:
public class EventsListFragment extends ListFragment implements OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
use a Sort (by comparator) or by Filter on array or custom adapter - depending on the complexity of the adapter object
some examples and references:
Sort listview with array adapter
sorting and filtering ListView with custom array adapter with two TextView?
Android filter and sort ListView with adapter set during Async task
How to sort adapter (BaseAdapter) based on current its field
Filtering ListView with custom (object) adapter
Custom Listview Adapter with filter Android
How could i filter the listview using baseadapter
basic example for array adapter:
Adapter.sort(new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return lhs.compareTo(rhs); //Your sorting algorithm
}
});
*Item - class definition for adapter item
array adapter doc ref:
https://developer.android.com/reference/android/widget/ArrayAdapter.html
complete solution for your case:
http://www.worldbestlearningcenter.com/tips/Android-sort-ListView.htm
I have a list of people that I am pulling from the database with a [modified] SimpleCursorAdapter. I then iterate over the cursor and print information out in a ListView in my app. Right now, it is coded so that when I click on a row, my app performs a function. However, what I would like to do is make it so that when I click on an icon within the row, my app will perform the appropriate function.
Where I am having trouble is isolating a cell within the row for the setOnItemClickListener instead of the entire row.
How do I go about isolating an ImageView within the row instead of the entire row itself?
Here is what I have:
Home.java
package myPackage;
public class Home extends Fragment {
private View rootView;
private AlternateRowColorSimpleCursorAdapter mySimpleCursorAdapter;
private ViewPager myViewPager;
private SwipeRefreshLayout studentSwipeRefresh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.home, container, false);
myViewPager = (ViewPager) getActivity().findViewById(R.id.pager);
studentSwipeRefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.student_swipe_refresh);
return rootView;
}
#Override
public void onViewCreated(View rootView, Bundle savedInstanceState) {
super.onViewCreated(rootView, savedInstanceState);
drawTheStudentView();
studentSwipeRefresh.setColorSchemeColors(Color.parseColor(Constants.RED), Color.parseColor(Constants.ORANGE), Color.parseColor(Constants.YELLOW), Color.parseColor(Constants.GREEN), Color.parseColor(Constants.BLUE), Color.parseColor(Constants.INDIGO), Color.parseColor(Constants.VIOLET));
studentSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
studentSwipeRefresh.setRefreshing(false);
drawTheStudentView();
}
});
}
private void drawTheStudentView(){
DatabaseHelper myDBHelper = new DatabaseHelper(getActivity());
Cursor studentCursor = myDBHelper.getStudentsCursor();
String[] fromColumns = {"_id","studentID","status","location"};
int[] toViews = {R.id.student_number_textview, R.id.student_id_textview};
mySimpleCursorAdapter = new AlternateRowColorSimpleCursorAdapter(getActivity(), R.layout.student_layout, studentCursor, fromColumns, toViews, 0);
// Replace the _id column with a student count
mySimpleCursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
String counter = Integer.toString((cursor.getPosition()+1));
TextView modifiedTextView = (TextView) view;
if(columnIndex == 0){
modifiedTextView.setText(counter);
return true;
}
return false;
}
});
ListView myListView = (ListView) rootView.findViewById(R.id.student_row);
// Listen for somebody clicking on a Student ID, and process
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor subCursor = (Cursor) mySimpleCursorAdapter.getItem(position);
String zapNumber = subCursor.getString(subCursor.getColumnIndex("studentID"));
StudentStatus studentStatus = (StudentStatus) getFragmentManager().findFragmentByTag(getFragmentTag(Constants.TAB_INDEX_PATIENT_VITALS));
studentStatus.setZapNumber(zapNumber);
myViewPager.setCurrentItem(Constants.TAB_INDEX_PATIENT_VITALS);
}
});
// Draw the list
myListView.setAdapter(mySimpleCursorAdapter);
myDBHelper.close();
}
// Pass me a tab index (see Constants.java) and I'll return a refrence to that tab.
private String getFragmentTag(int tagID){
return "android:switcher:" + R.id.pager + ":" + tagID;
}
}
AlternateRowColorSimpleCursorAdapter.java
package myPackage;
public class AlternateRowColorSimpleCursorAdapter extends SimpleCursorAdapter {
public AlternateRowColorSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = super.getView(position, convertView, parent);
if(position % 2 == 0){
row.setBackgroundColor(Color.parseColor(Constants.WHITE));
} else {
row.setBackgroundColor(Color.parseColor(Constants.LIGHTGREY));
}
return row;
}
}
student_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="#+id/student_number_textview"
android:typeface="monospace"
android:layout_weight="1"
android:textStyle="bold"
style="#style/StudentStyle" />
<TextView
android:id="#+id/student_id_textview"
android:typeface="monospace"
style="#style/StudentStyle" />
<ImageView
android:id="#+id/student_status_button"
style="#style/studentIconLink"
android:src="#drawable/status_icon"/>
<ImageView
android:id="#+id/student_location_button"
style="#style/studentIconLink"
android:src="#drawable/location_icon"/>
</LinearLayout>
A possibility to define a callback interface for communication between the views created in your Adapter and your Fragment.
Have your Fragment implement this interface and pass in a reference to your Fragment in your Adapter's constructor. In your getView() method in the adapter, you can set an OnClickListener on your ImageView that you want to listen for, and then trigger the callback you passed into your Adapter. Note: you can pass back something like position in this callback so you know which row's ImageView was selected.