I have an array named societies:
List<Society> societies = new ArrayList<>();
That holds the following data:
[{"society_id":1,"name":"TestName1","email":"Test#email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test#email2","description":"TestDes2"},
{"society_id":3,"name":"TestName3","email":"Test#email3","description":"TestDes3"}}
I will be using this to populate a ListView but am having trouble writing the loop that will assign each array of values to its spot in the ListView.
I would like to find a way of pulling the values from the Array and assigning them to each list item by using a loop, can anybody help me with this?
My code (should be sufficient but if you need to see more please ask):
public class SocietySearch extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_society_search);
List<Society> societies = new ArrayList<>();
ServerRequests serverRequest1 = new ServerRequests(SocietySearch.this);
serverRequest1.GetSocietyDataAsyncTask(societies, new GetSocietyCallback() {
#Override
public void done(List<Society> societies) {
ListView lv = (ListView) findViewById(R.id.ListView);
List<ListViewItem> items = new ArrayList<>();
items.add(new ListViewItem() {{
ThumbnailResource = R.drawable.test;
Title = societies.socName;
Subtitle = societies.socDes;
}});
CustomListViewAdapter adapter = new CustomListViewAdapter(SocietySearch.this, items);
lv.setAdapter(adapter);
}
});
}
class ListViewItem {
public int ThumbnailResource;
public String Title;
public String Subtitle;
}
Adapter Class:
public class CustomListViewAdapter extends ArrayAdapter {
LayoutInflater inflater;
List<SocietySearch.ListViewItem> items;
public CustomListViewAdapter(Activity context, List<SocietySearch.ListViewItem> items) {
super(context, R.layout.item_row);
this.items = items;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Auto-generated method stub
ListViewItem item = items.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_row, null);
ImageView test = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubTitle = (TextView) vi.findViewById(R.id.txtSubTitle);
test.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubTitle.setText(item.Subtitle);
return vi;
}
}
So we came to the conclusion, that we need to have the for loop to iterate through all the Society classes in the SocietySearch class:
#Override
public void done(List<Society> societies) {
ListView lv = (ListView) findViewById(R.id.ListView);
List<ListViewItem> items = new ArrayList<>();
for(Society s : societies) {
items.add(new ListViewItem() {{
ThumbnailResource = R.drawable.test;
Title = s.socName;
Subtitle = s.socDes;
}});
}
CustomListViewAdapter adapter = new CustomListViewAdapter(
SocietySearch.this, items);
lv.setAdapter(adapter);
}`
And we also had to fix the ArrayAdapter implementation:
public class CustomListViewAdapter extends ArrayAdapter {
LayoutInflater inflater;
List<SocietySearch.ListViewItem> items;
public CustomListViewAdapter(Activity context, List<SocietySearch.ListViewItem> items) {
super(context, R.layout.item_row, **items**); // the constructor
//needs the reference of the list, even though we use our variable to
//populate the rows. I guess it has to know how many elements it contains to
//iterate then through getView method, which is called for each row
this.items = items;
this.inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
Are you looking for a custom solution? So that you would bind each ListViewItem state to the corresponding column, then you have to create the custom solution like it is here. You would need to have a custom layout for each line and extend the ArrayAdapter where you bind each column for a line.
Is this what you want to know? If not, can you be more specific please.
You are creating an anonymous class and trying to assign values in it's object initializer. Object initializer doesn't have a reference to societies, that's why you are getting the compilation error. Try this instead:
class ListViewItem {
private final int ThumbnailResource;
private final String Title;
private final String Subtitle;
public ListViewItem(int thumbnail, String title, String subtitle) {
ThumbnailResource = thumbnail;
Title = title;
Subtitle = subtitle;
}
}
When adding list items:
items.add(new ListViewItem(R.drawable.test, societies.socName, societies.socDes);
Related
I made adapter for ListView. If I fill the elements array before creating the adapter and linking it to the listView, the elements are displayed.
But if I use the updateItems () method to add items when the button is clicked, nothing happens.
Code of adapter:
public class ListAdapter extends ArrayAdapter<Lf> {
private LayoutInflater inflater;
private int layout;
private List<Lf> lfs;
public ListAdapter(Context context, int resource, List<Lf> lfs) {
super(context, resource, lfs);
this.lfs = lfs;
this.layout = resource;
this.inflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView = inflater.inflate(this.layout, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
Lf lf = lfs.get(position);
viewHolder.name.setText(lf.getLf());
viewHolder.freq.setText((int)lf.getFreq() + "");
return convertView;
}
public void updateItems(List<Lf> lfs) {
this.lfs.clear();
this.lfs.addAll(lfs);
this.notifyDataSetChanged();
}
private class ViewHolder {
final TextView name, freq;
ViewHolder(View view){
name = (TextView) view.findViewById(R.id.text_item_1);
freq = (TextView) view.findViewById(R.id.text_item_2);
}
}
}
Code of MainActivity:
public class MainActivity extends AppCompatActivity {
EditText editText1;
ListView listView;
ListAdapter adapter;
List<Lf> elements = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.edit_text);
listView = (ListView) findViewById(R.id.fragment_list);
// Working... Elements print on screen
for(int i = 0; i < 10; i++) {
Lf temp = new Lf();
temp.setLf("mean");
temp.setFreq(100);
elements.add(temp);
}
adapter = new ListAdapter(this, R.layout.list_item, elements);
listView.setAdapter(adapter);
}
public void activity_button(View view) {
adapter.updateItems(elements);
}
}
If I click on the button, the existing items on the screen are cleared instead of a new one added. But in debug I see that elements normally passed to ListAdapter.
The problem is that your adapter's lfs's field and your activity's elements field both refer to the same List instance. This happens because you pass elements to the ListAdapter constructor, and then simply assign this.lfs = lfs.
So let's look at what happens when you pass elements to updateItems()...
public void updateItems(List<Lf> lfs) {
this.lfs.clear(); // this.lfs and the input lfs are the same list, so this clears both
this.lfs.addAll(lfs); // input lfs is now empty, so addAll() does nothing
this.notifyDataSetChanged();
}
Probably the best thing to do is to create a copy of the list in your adapter's constructor.
this.lfs = new ArrayList<>(lfs);
Now your adapter and activity will reference different lists, so this.lfs.clear() won't accidentally clear out the very list you're passing to it.
How can I update my listView adapter properly when I add a new file? The listView is feed by a an array. I have read a lot and tried several things but nothing works outs. Am I missing something? notifyDataSetChanged is not working for some reason.
activity.java
on create:
ListView list2;
CustomList listAdapter;
String[] ficheros;
final File carpeta = new File("/storage/emulated/0/Android/data/cc.openframeworks.androidMultiOFActivitiesExample/files/xml");
list2=(ListView)findViewById(R.id.listview);
list2.setVisibility(GONE);
list2.setCacheColorHint(Color.TRANSPARENT);
ficheros = list.toArray(new String[list.size()]);
List<String> list = new ArrayList<String>();
listAdapter = new CustomList(OFActivityA.this, ficheros,fecha);
list2.setAdapter(listAdapter);
listarFicherosPorCarpeta(carpeta);
#Override
protected void onResume() {
super.onResume();
public void listarFicherosPorCarpeta(final File carpeta) {
for (final File ficheroEntrada: carpeta.listFiles()) {
if (ficheroEntrada.isDirectory()) {
listarFicherosPorCarpeta(ficheroEntrada);
} else {
System.out.println(ficheroEntrada.getName());
list.add(ficheroEntrada.getName());
}
}
listAdapter.notifyDataSetChanged();
}
CustomList.java
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] ficheros;
private final String[] fecha;
public CustomList(Activity context, String[] ficheros, String[] fecha) {
super(context, R.layout.rowlayout, ficheros);
this.context = context;
this.ficheros = ficheros;
this.fecha = fecha;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.rowlayout, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.listtext);
TextView txtFecha = (TextView) rowView.findViewById(R.id.fechatxt);
txtTitle.setTextColor(Color.parseColor("#015D99"));
txtTitle.setHeight(123);
txtFecha.setText(fecha[position]);
txtTitle.setText(ficheros[position]);
return rowView;
}
notifyDataSetChanged() will work if the content in dataset has changed. You are calling it in onResume() which might get called before your loop in function has finished. Try changing your function call and add notifyDataSetChanged() once your for loop completes.
public void listarFicherosPorCarpeta(final File carpeta) {
for (final File ficheroEntrada: carpeta.listFiles()) {
if (ficheroEntrada.isDirectory()) {
listarFicherosPorCarpeta(ficheroEntrada);
} else {
System.out.println(ficheroEntrada.getName());
list.add(ficheroEntrada.getName());
}
}
listAdapter.notifyDataSetChanged(); //call it here after you have updated your data.
}
I am creating chat application. So I wanted to add number of messages a user get from his friend. To show that I created custom Array adapter because my listview consists of friend name and notification textview.
So, I have the data in my list_of_registerd_users activity:
How I can send this data to custom array adapter class to set the view of notification:
Custom Array Adapter class:
public class CustomArrayAdapter extends ArrayAdapter<String> {
private Context mContext;
private int mRes;
private ArrayList<String> data;
private String numOfMsgs;
public CustomArrayAdapter(Context context, int resource,
ArrayList<String> objects) {
super(context, resource, objects);
this.mContext = context;
this.mRes = resource;
this.data = objects;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = LayoutInflater.from(mContext);
row = inflater.inflate(mRes, parent, false);
String currentUser = getItem(position);
TextView friendName = (TextView) row.findViewById(R.id.tvFriendName);
String Frndname = currentUser;
friendName.setText(Frndname);
TextView notificationView = (TextView) row.findViewById(R.id.tvNotif);
//here i wanted to get the data noOfMsgs
Toast.makeText(mContext, "noOfMsgs:" + numOfMsgs, Toast.LENGTH_LONG).show();
notificationView.setText(noOfMsgs);
return row;
}
}
You just need to initialize the adapter and attach the adapter to the ListView
ArrayList<String> items = new ArrayList<>();
items.add(item1);
items.add(item2);
items.add(item3);
CustomArrayAdapter<String> itemsAdapter = new CustomArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listview.setAdapter(itemsAdapter);
You only need to update the list object which you are passing in CustomArrayAdapter and then notify the list.
adapter.notifyDataSetChanged()
As you are passing the list object to adapter so any changes in list will automatically updated in object 'data'. You have to just update the view.
I have done the code but it appears the Search is not working
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
ListView lv;
SearchView searchView;
ArrayAdapter<String> adapter;
String[] apptitle = {"†orch", "Quiz It!"};
String[] inf = {"click for info", "click for info"};
int[] img = {R.drawable.ic_launcher, R.drawable.ic_launcher};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
lv = (ListView) findViewById(R.id.idlistview);
searchView = (SearchView) findViewById(R.id.idsearch);
Adapterim adapter = new Adapterim(getApplicationContext(), apptitle, inf, img);
lv.setAdapter(adapter);
/*adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, appTitle);
lv.setAdapter(adapter);*/
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
// ArrayAdapter extends, Let's create class
class Adapterim extends ArrayAdapter<String> {
//For the information we need for our content
//Create array variable
int[] img = {};
String[] apptitle = {};
String[] inf = {};
//Context and layoutinflater as required
//Let's create them
Context c;
LayoutInflater inflater;
//The parameters of the generated method
public Adapterim(Context context, String[] apptitle, String[] inf, int[] img) {
//Values to be entered into the super method
//
super(context, R.layout.listview_class, apptitle);
// Equalize the parameters to the variables in this class
this.img = img;
this.apptitle = apptitle;
this.inf = inf;
this.c = context;
}
// Let's create our inner class and
// create our components
public class Viewholder {
TextView attv;
TextView inftv;
ImageView imgim;
}
//With this automatic method, each element in the array can be edited one by one
//We add data to the components in ListView
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_class, null, true);
}
// Create an object from our class we created
final Viewholder holder = new Viewholder();
// And the components we create in our inner structure
//I sync with the components in the layout
holder.attv = (TextView) convertView.findViewById(R.id.custom_textView);
holder.inftv = (TextView) convertView.findViewById(R.id.custom_textView2);
holder.imgim = (ImageView) convertView.findViewById(R.id.custom_imageView);
//In order to assign the array elements as data for each component
//Assign position value to our arrays
//And set the values of our components
holder.imgim.setImageResource(img[position]);
holder.attv.setText(apptitle[position]);
holder.inftv.setText(inf[position]);
//It must be a return value and I will return View
return convertView;
}
}
I have a simple list view where each item is a view that has a title, from an ArrayList of strings and button, so that each entry in the ArrayList creates a new list item.
I also have another ArrayList of corresponding primary keys, which I want to use to delete specific items from an SQLite database but which isn't used in the list view(I don't want to display the ID's, but the strings that poplulate the list might not necessarily be unique so I can't use them to delete).
I have a onClick listener and method in the getView method for the list view, so that when someone clicks the delete button, I know the position in the list that the button was pressed in, so hopefully, I can then call a delete method on the database using id[position], however, I think due to the list view itself being created after the activity it's inside of, it can't resolve the id array, so I can't call delete.
public class TodayListActivity extends AppCompatActivity {
private ArrayList<String> names = new ArrayList<>();
FoodDB Db = null;
int deleteId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todaylist);
ListView lv = (ListView) findViewById(R.id.today_meal_list);
Bundle a = this.getIntent().getExtras();
String[] id = a.getStringArray("idArray"); //used to delete
String[] mealNames = a.getStringArray("mealNamesArray"); //displayed
Collections.addAll(names, mealNames);
//call the list adapter to create views based off the array list 'names'
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, names));
}
protected class MyListAdapter extends ArrayAdapter<String> {
private int layout;
private MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder viewholder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewholder = new viewHolder();
viewholder.title = (TextView) convertView.findViewById(R.id.report_meal_name);
viewholder.delButton = (Button) convertView.findViewById(R.id.button_delete_meal);
viewholder.delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
//int deleteId derived from id[position]
deleteId = Integer.parseInt(id[position]);
idToDelete(deleteId);
//update the list view to exclude the deleted item
names.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(viewholder);
} else {
viewholder = (viewHolder) convertView.getTag();
}
//set string value for title
viewholder.title.setText(getItem(position));
viewholder.delButton.setTag(position);
return convertView;
}
}
public class viewHolder {
TextView title;
TextView delButton;
}
//delete from database
public void idToDelete(int DeleteId){
Db.deleteFoods(deleteId);
}
}
Any suggestions as to how or where to get either the position index out of the list view (to the activity, where the id array is) or get access to the id array inside the listview would be appreciated!
You can pass the id array to the MyListAdapter adapter, by changing this class' constructor to accept it as a parameter. Also, you are already passing the names list as a parameter, you should keep a reference to it so you can access it when the button is pressed.
Here is an example:
protected class MyListAdapter extends ArrayAdapter<String> {
private int layout;
private List<String> names;
private String[] ids;
private MyListAdapter(Context context, int resource, List<String> names, String[] ids) {
super(context, resource, names);
layout = resource;
this.names = names;
this.ids = ids;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
...
viewholder.delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int deleteId = Integer.parseInt(ids[position]);// the "position" variable needs to be set to "final" in order to access it in here.
idToDelete(deleteId);
names.remove(position);
notifyDataSetChanged();
}
});
....
}
}
and here is how you can create an instance of this adapter:
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, names, id));