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.
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.
I'm trying to retrieve the item name and quantity from my listview,
and display it onto the new class: Details.java.
Here are my codes for listview.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
//create items to display in customized listview (Arraylist)
displayiteminfo.add(new SalesItemInformationLV("Bread", 2));
displayiteminfo.add(new SalesItemInformationLV("Butter", 9));
displayiteminfo.add(new SalesItemInformationLV("Margarine", 8));
//New array adapter for customised ArrayAdapter
final ArrayAdapter<SalesItemInformationLV> adapter = new itemArrayAdapter(this, 0, displayiteminfo);
//displayiteminfo - the ArrayList of item objects to display.
//Find the list view, bind it with custom adapter
final ListView listView = (ListView)findViewById(R.id.customListview);
listView.setAdapter(adapter);
//Selecting the listview item!
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SalesItemInformationLV saleitem = (SalesItemInformationLV) listView.getSelectedItem();
String namevalue = saleitem.getItemname(); ---> WHERE ERROR OCCURS
int qtyvalue = saleitem.getItemquantity();
Intent myintent = new Intent(ListView.this, Details.class);
myintent.putExtra("itemname", namevalue);
myintent.putExtra("itemqty", qtyvalue);
startActivity(myintent);
}
});
}
//custom Arrayadapter
class itemArrayAdapter extends ArrayAdapter<SalesItemInformationLV>
{
private Context context;
private List<SalesItemInformationLV> item;
//constructor, call on creation
public itemArrayAdapter(Context context, int resource, ArrayList<SalesItemInformationLV> objects) {
//chaining to "default constructor" of ArrayAdapter manually
super(context, resource, objects);
this.context = context;
this.item = objects;
}
//called to render the list
public View getView(int position, View convertView, ViewGroup parent)
{
//get the item we are displaying
SalesItemInformationLV iteminfo = item.get(position);
//get the inflater and inflate the xml layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_layout, null);
//Each component of the custom item_layout
TextView name = (TextView) view.findViewById(R.id.ItemNameSales);
TextView qty = (TextView)view.findViewById(R.id.ItemNameQty);
//set the name of item - access using an object!
name.setText(String.valueOf(iteminfo.getItemname()));
//set the quantity of item - access using an object!
qty.setText(String.valueOf(iteminfo.getItemquantity()));
return view;
//Now return to onCreate to use this cuztomized ArrayAdapter
}
}
Upon implementing the above codes, I got an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ... on a null object reference
Clicked and Selected are different things.
Replace
SalesItemInformationLV saleitem = (SalesItemInformationLV) listView.getSelectedItem();
with
SalesItemInformationLV saleitem = displayiteminfo.get(position)
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));
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);
I have an object:
private ArrayList<HashMap<String, String>> customerDataList;
Which I populate with data retrieved from a web service call. The below is inside a loop iterating over the retrieved json data:
HashMap<String, String> customer = new HashMap<>();
//snip
customer.put("CustomerName", customerName);
//snip
customerDataList.add(customer);
//rinse and repeat
Then I display this in a list view in my activity with:
ListAdapter adapter = new SimpleAdapter(Activity.this, customerDataList,
R.layout.list_item, new String[] {"CustomerName"}, new int[] { R.id.customerName });
setListAdapter(adapter);
However I am wondering if there is a way I can use a List instead.
I created my customer class, created a List of it like so:
private List<Customer> customerList;
However when it comes to setting the ListAdapter I am unsure of what to put. I replaced customerDataList with customerList but I receive errors.
Edit: The error is
SimpleAdapter() in SimpleAdapter cannot be applied to:
Expected data: java.util.Map<java.lang.String.?>>
Actual arguments: customerList <Customer>
Edit: my class structure
private class Customer
{
private int customerID;
private String customerName;
private String customerLocation;
private String runningTime;
private double distance;
}
If you want a use a list of custom objects you need to use another adapter e.g. ArrayAdapter:
List<Customer> customerList = null;
ArrayAdapter<Customer> customerAdapter = new ArrayAdapter<Customer>(this,
R.layout.list_item, customerList);
Now since ArrayAdapter expects strings to come out of your custom objects, override a toString method in your class:
class Customer {
String customerName;
#Override
public String toString() {
return customerName;
}
}
If your customer class has multiple fields that will need to be used in your adapter, you will need a custom adapter, something like this:
// Turns out that when the layout is not a TextView, you need to provide the id
// of the TextView the adapter can bind to
ArrayAdapter<Customer> customerAdapter = new ArrayAdapter<Customer>(this,
R.layout.list_item, R.id.customer_name, customerList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView name = view.findViewById(R.id.customer_name);
TextView surname = view.findViewById(R.id.customer_surname);
name.setText(getItem(position).customerName);
surname.setText(getItem(position).customerSurname);
return view;
}
};
You can google to find some performance adjustments for custom adapters.
You can use
List<Customer>
but you need to go for a custom adapter instead of Simple adapter.
The data containing the customer object need to be set, the simple adapter can only accept the name value pare map. So you need to extend the adapter/Basadpter class the requirement.
The easiest way is to assign the values from Customer object to views in your list row layout is to create a custom Adapter extending the ArrayAdapter class:
public class CustomAdapter extends ArrayAdapter<Customer> {
private final Context context;
private final Customer[] values;
public MySimpleArrayAdapter(Context context, Customer[] values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listviewrowlayout, parent, false);
}
TextView customerName= (TextView) convertView.findViewById(R.id.customerName);
TextView customerAge= (TextView) convertView.findViewById(R.id.customerAge);
customerName.setText(values[position].getName());
customerAge.setText(values[position].getAge());
return convertView;
}
}