I have 2 arrays like:
Array 1 :
String[] web = {"Google Plus","Twitter","Windows","Bing","Itunes","Wordpress","Drupal"} ;
Array 2 :
String[] webimage = {"#drawable/img1","#drawable/img2","#drawable/img3","#drawable/img4","#drawable/img5","#drawable/img6","#drawable/img7"} ;
And I want to create ArrayAdapter that uses my Array1 for TextView and uses Array2 for icon of row
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.single_row,R.id.textView,array);
You could create a class to hold the String and the drawable resource
public class Item{
private final String text;
private final int icon;
public Item(final String text, final int icon){
this.text = text;
this.icon = icon;
}
public String getText(){
return text;
}
public Drawable getIcon(final Context context){
return context.getResources().getDrawable(this.icon)
}
}
and then create an array of Items
Item[] items = new Item[1];
item[0] = new Item("Google Plus",R.drawable.img1);
//...etc
create a custom ArrayAdapter for Item
public class ItemAdapter extends ArrayAdapter<Item> {
private Context context;
public ItemAdapter(Context context, Item[] items) {
super(context, 0, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Item item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_row, parent, false);
}
// Lookup view for data population
TextView tvText = (TextView) convertView.findViewById(R.id.tvText);
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
// Populate the data into the template view using the data object
tvText.setText(item.getText());
ivIcon.setImageDrawable(item.getDrawable(this.context));
// Return the completed view to render on screen
return convertView;
}
}
In the example above R.layout.item_row is a layout that you would have to create containing a TextView with id tvText and an ImageView with id ivIcon.
Related
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));
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 app that loads data from a sqllite database, then converts the data to appropriate formats so it could pass on the data to fragment tabs.
Everything works fine except for the images.
In the DB images are stored in full path, for example R.drawable.muntjakas and the images are available in the resource drawable folder.
The app pulls the data from the db and then converts it to int format so it could be passed on. Eclipse is not giving me any errors, but when the app loads images are not displayed. My xml files have the image id set up and displays the images if I assign the values manually for example
flag = new int[] { R.drawable.muntjakas,.... };
What's the problem?
fragmenttab1.java class that loads data from sql and converts it:
public class FragmentTab1 extends SherlockFragment {
ListView list;
ListViewAdapter adapter;
private static final String DB_NAME = "animalsDB.sqllite3";
private static final String TABLE_NAME = "animals";
private static final String ANIMAL_ID = "_id";
private static final String ANIMAL_NAME = "name";
private static final String ANIMAL_PIC = "pic";
public static final String[] ALL_KEYS = new String[] {ANIMAL_ID, ANIMAL_NAME,ANIMAL_PIC };
private SQLiteDatabase database;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(getActivity(), DB_NAME);
database = dbOpenHelper.openDataBase();
Cursor cursor = getAllRows();
ArrayList<String> nameArray = new ArrayList<String>();
ArrayList<Integer> picArray = new ArrayList<Integer>();
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
nameArray.add(cursor.getString(cursor.getColumnIndex(ANIMAL_NAME)));
picArray.add(cursor.getInt(cursor.getColumnIndex(ANIMAL_PIC)));
}
final String[] name = (String[]) nameArray.toArray(new String[nameArray.size()]);
final Integer[] pic = (Integer[]) picArray.toArray(new Integer[picArray.size()]);
final int[] flag = new int[pic.length];
for (int i = 0; i < pic.length; i++ ) {
flag[i] = pic[i];
}
// Locate the ListView in fragmenttab1.xml
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), name, flag);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Capture clicks on ListView items
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(getActivity(), SingleItemView.class);
// Pass all data country
i.putExtra("country", name);
// Pass all data flag
i.putExtra("flag", flag);
// Pass a single position
i.putExtra("position", position);
// Open SingleItemView.java Activity
startActivity(i);
}});
return rootView;
}
public Cursor getAllRows() {
String where = null;
Cursor c = database.query(true, TABLE_NAME, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
My listViewAdapter.java class that should load the data on the screen:
package kf.kaunozoo;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
String[] country;
int[] flag;
LayoutInflater inflater;
public ListViewAdapter(Context context, String[] country, int[] flag) {
this.context = context;
this.country = country;
this.flag = flag;
}
public int getCount() {
return country.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView txtcountry;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Locate the TextViews in listview_item.xml
txtcountry = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
imgflag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set to the TextViews
txtcountry.setText(country[position]);
// Capture position and set to the ImageView
imgflag.setImageResource(flag[position]);
return itemView;
}
}
What am I doing wrong? All answers are appreciated
I have had this problem once in one of my apps, however, what I did was, I saved unique ids for each drawable in database as I had limited images. While displaying I wrote a small function where I used switch statement to check for each id from database and then loaded images accordingly in ImageView.
However, when you have lots of images, try to use below function, where you can provide image names dynamically from database.
// image from res/drawable
int resID = getResources().getIdentifier("your_image_name",
"drawable", getPackageName());
Also, you may try the solution given at this blog.