Android Customer Array Adapter does not display data - android

Hi StackOverflow community! I need your help understanding the following behavior:
I tried to implement a ListView for which each view follows the below layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLWLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100">
<TextView
android:id="#+id/noteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="66.6" />
<LinearLayout
android:id="#+id/linearVLWLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="33.3"
android:orientation="vertical">
<TextView
android:id="#+id/textcolor"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/reminder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textcolor" />
<TextView
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/reminder" />
<TextView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/location" />
</LinearLayout>
Now, when I'm assigning elements to the list, I'm using the below adapter:
public class MyAdapter extends ArrayAdapter<Note> {
private Context mContext;
private int mResource;
public MyAdapter(#NonNull Context context, int resource, ArrayList<Note> objects) {
super(context, resource);
mContext =context;
mResource=resource;
}
public View getView(int position, View convertView, ViewGroup parent){
String text = getItem(position).getText();
String color = getItem(position).getColor();
String location = getItem(position).getLocation();
String reminder = getItem(position).getReminder();
String image = getItem(position).getImage();
Note note = new Note(text,color,location,reminder,image);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource,parent,false);
TextView nttxt = (TextView) convertView.findViewById(R.id.noteText);
TextView ntcolor = (TextView) convertView.findViewById(R.id.textcolor);
TextView ntrem = (TextView) convertView.findViewById(R.id.reminder);
TextView ntlocat = (TextView) convertView.findViewById(R.id.location);
TextView ntimg = (TextView) convertView.findViewById(R.id.image);
nttxt.setText(text);
ntcolor.setText(color);
ntrem.setText(reminder);
ntlocat.setText(location);
ntimg.setText(image);
Log.i("Convert",convertView.toString());
Log.i("Text",nttxt.toString());
return convertView;
}
}
The final result should be a list of notes together with user preferences and location/reminder.
Please see below the list assignation made on OnCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_explorer);
FloatingActionButton myFab = this.findViewById(R.id.fabAddNote);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intentNoteEditor = new Intent(getApplicationContext(), NoteEditor.class);
startActivity(intentNoteEditor);
}
});
ListView notesList = (ListView) findViewById(R.id.listviewNotes);
Note note1 = new Note("Note1","Col1","Reminder1","Location1","Image1");
Note note2 = new Note("Note2","Col2","Reminder2","Location2","Image2");
Note note3 = new Note("Note3","Col3","Reminder3","Location3","Image3");
Note note4 = new Note("Note4","Col4","Reminder4","Location4","Image4");
ArrayList<Note> notesArray = new ArrayList<>();
notesArray.add(note1);
notesArray.add(note2);
notesArray.add(note3);
notesArray.add(note4);
Log.i("Notes",note1.getText().toString());
MyAdapter adapter = new MyAdapter(this,R.layout.list_item,notesArray);
notesList.setAdapter(adapter);
Log.i("Adapter",adapter.getContext().toString());
}
What am I doing wrong?
Any suggestions will be highly appreciated.
Thank you in advance!

You didn't store the list you feed your adapter to a local field.
Here you are passing ArrayList<Note> objects through the adapter constructor, but didn't save it locally to some store.
So, First modify your Adapter to have a filed of ArrayList<Note>
and initialize it in the constructor.
Second, override the adapter getCount() to return the size of your
list.
Third: modify your getView(), to get the Note object of the current
position in the list
public class MyAdapter extends ArrayAdapter<Note> {
private Context mContext;
private int mResource;
private ArrayList<Note> mNotes;
public MyAdapter(#NonNull Context context, int resource, ArrayList<Note> objects) {
super(context, resource);
mContext = context;
mResource = resource;
mNotes = objects;
}
#Override
public int getCount() {
return mNotes.size();
}
public View getView(int position, View convertView, ViewGroup parent){
String text = mNotes.get(position).getText();
String color = mNotes.get(position).getColor();
String location = mNotes.get(position).getLocation();
String reminder = mNotes.get(position).getReminder();
String image = mNotes.get(position).getImage();
// .... continue the rest of code.
Hope this address your issue.

Related

ListView will only display the initial items

I'm attempting to use a custom ArrayAdapter for a listView in which I have in one of my activities. The quantity of data I am using is quite large, so to rule out that being the issue I hardcoded an ArrayList<ArrayList<String>> to simply pass 8 items to display on my listView, however the same issue has occured where only the initial 4 are being displayed with no ability to scroll to further items.
I am also aware that there are currently no images being displayed on the listView, I intend to link this up after resolving this issue.
This is the main activity which will display the listView in question:
ProductSelectionActivity.java
public class ProductSelectionActivity extends AppCompatActivity {
ListView productListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_selection);
ArrayList<ArrayList<String>> productsList = new ArrayList<ArrayList<String>>();
ArrayList<String> prodIds = new ArrayList<String>();
ArrayList<String> prodNames = new ArrayList<String>();
ArrayList<String> prodCosts = new ArrayList<String>();
ArrayList<String> prodMainImages = new ArrayList<String>();
prodIds.add("id1");
prodIds.add("id2");
prodIds.add("id3");
prodIds.add("id4");
prodIds.add("id5");
prodIds.add("id6");
prodIds.add("id7");
prodIds.add("id8");
prodNames.add("name1");
prodNames.add("name2");
prodNames.add("name3");
prodNames.add("name4");
prodNames.add("name5");
prodNames.add("name6");
prodNames.add("name7");
prodNames.add("name8");
prodCosts.add("cost1");
prodCosts.add("cost2");
prodCosts.add("cost3");
prodCosts.add("cost4");
prodCosts.add("cost5");
prodCosts.add("cost6");
prodCosts.add("cost7");
prodCosts.add("cost8");
prodMainImages.add("image1");
prodMainImages.add("image2");
prodMainImages.add("image3");
prodMainImages.add("image4");
prodMainImages.add("image5");
prodMainImages.add("image6");
prodMainImages.add("image7");
prodMainImages.add("image8");
productsList.add(prodIds);
productsList.add(prodNames);
productsList.add(prodCosts);
productsList.add(prodMainImages);
// Create the listView arrayAdapter
ProductListAdapter arrayAdapter =
new ProductListAdapter(this, R.layout.product_list_items, productsList);
// Set the adapter
productListView = (ListView) findViewById(R.id.products_list);
productListView.setAdapter(arrayAdapter);
}}
The following is the class for the adapter:
ProductListAdapter.java
public class ProductListAdapter extends ArrayAdapter<ArrayList<String>> {
// Initialise list of products
ArrayList<ArrayList<String>> products;
public ProductListAdapter(Context context, int resource, ArrayList<ArrayList<String>> objects) {
super(context, resource, objects);
products = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.product_list_items, parent, false);
}
// Get product listing info with reference to position that has been passed as param
ArrayList<String> prodIds = products.get(0);
String prodId = prodIds.get(position);
ArrayList<String> prodNames = products.get(1);
String prodName = prodNames.get(position);
ArrayList<String> prodCosts = products.get(2);
String prodCost = prodCosts.get(position);
ArrayList<String> prodMainImages = products.get(3);
String prodMainImage = prodMainImages.get(position);
// Getting id for textview and imageview
TextView textViewName = (TextView) convertView.findViewById(R.id.prod_name_text);
TextView textViewCost = (TextView) convertView.findViewById(R.id.prod_cost_text);
// Setting values to ids
textViewName.setText(prodName);
textViewCost.setText("£"+prodCost);
return convertView;
}}
The layout for the ProductSelectionActivity:
activity_product_selection.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProductSelectionActivity">
<ListView
android:id="#+id/products_list"
android:layout_width="396dp"
android:layout_height="508dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.961" />
</android.support.constraint.ConstraintLayout>
The layout for the adapter:
product_list_items.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:orientation="horizontal"
android:weightSum="100" >
<ImageView
android:id="#+id/prod_main_image"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_weight="60"
app:srcCompat="#color/background_holo_light" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="40"
android:orientation="vertical" >
<TextView
android:id="#+id/prod_name_text"
android:layout_width="278dp"
android:layout_height="60dp"
android:text="#string/prod_name_text" />
<TextView
android:id="#+id/prod_cost_text"
android:layout_width="278dp"
android:layout_height="60dp"
android:text="#string/prod_cost_text" />
</LinearLayout>
</LinearLayout>
I believe the issue lies within the layout files, through process of elimination of other factors that I thought may have been the issue; such as ensuring all data was being passed correctly (I was able to identify this through the Logcat).
If there is anything else that I could clarify then please let me know.
The ListView will display the items that you are passing in the adapter. So you are passing an ArrayList of 4 elements. This is why the ListView only shows 4 items. If you add more elements to the productsList ArrayList then the number of items you can show will increase.
Another thing, just to improve on what you are doing. Instead of creating separate ArrayLists for each product detail separately, just create a model for your Product and load it with data. Then pass a ArrayList to your custom adapter with any number of Product items you want.
class Product {
String productId;
String productName;
String productCost;
String productImage;
Product(String id, String name, String cost, String image) {
productId = id;
productName = name;
productCost = cost;
productImage = image;
}
}
Now in your ProductSelectionActivity just use it like this.
ArrayList<Product> productList = new ArrayList();
productList.add(new Product("id1", "name1", "cost1", "image1");
//Do this for all other products
ProductListAdapter arrayAdapter = new ProductListAdapter(this, R.layout.product_list_items, productList);
// Set the adapter
productListView = (ListView) findViewById(R.id.products_list);
productListView.setAdapter(arrayAdapter);
The final step is to update your adapter to handle an ArrayList of Products
public class ProductListAdapter extends ArrayAdapter<Product> {
// Initialise list of products
ArrayList<Product> products;
public ProductListAdapter(Context context, int resource, ArrayList<Product> objects) {
super(context, resource, objects);
products = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.product_list_items, parent, false);
}
//Get the product item for this position
Product product = products.get(0);
TextView textViewName = (TextView) convertView.findViewById(R.id.prod_name_text);
TextView textViewCost = (TextView) convertView.findViewById(R.id.prod_cost_text);
// Setting values to ids
textViewName.setText(product.productName);
textViewCost.setText("£" + product.productCost);
return convertView;
}
}
Another improvement would be to use a ViewHolder instead of using a simple view.
You can create a Wrapper(POJO) class to hold your product information and use it for your list adapter. It would be a better way to handle by you list rather than using ArrayList<ArrayList<String>>.
First create a model(Pojo) class to hold product information.
class Product {
String prodId;
String prodName;
String prodCost;
String prodMainImage;
public Product(String prodIds, String prodNames, String prodCostsl, String prodMainImages) {
this.prodId = prodIds;
this.prodName = prodNames;
this.prodCost = prodCostsl;
this.prodMainImage = prodMainImages;
}
}
ProductSelectionActivity.java
public class ProductSelectionActivity extends AppCompatActivity {
ListView productListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_selection);
ArrayList<Product> productsList = new ArrayList<>();
productsList.add(new Product("id1", "name1", "cost1", "image1"));
productsList.add(new Product("id2", "name2", "cost2", "image2"));
productsList.add(new Product("id3", "name3", "cost3", "image3"));
productsList.add(new Product("id4", "name4", "cost4", "image4"));
ProductListAdapter arrayAdapter =
new ProductListAdapter(this, R.layout.product_list_items, productsList);
// Set the adapter
productListView = (ListView) findViewById(R.id.products_list);
productListView.setAdapter(arrayAdapter);
}}
ProductListAdapter.java
public class ProductListAdapter extends ArrayAdapter<Product> {
// Initialise list of products
ArrayList<Product> products;
public ProductListAdapter(Context context, int resource, ArrayList<Product> objects) {
super(context, resource, objects);
products = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.product_list_items, parent, false);
}
Product product = products.get(position);
// Getting id for textview and imageview
TextView textViewName = convertView.findViewById(R.id.prod_name_text);
TextView textViewCost = convertView.findViewById(R.id.prod_cost_text);
// Setting values to ids
textViewName.setText(product.prodName);
textViewCost.setText("£"+product.prodCost);
return convertView;
}
}
That's it. It should work properly. Although nowadays, RecyclerView is being used more for its performance and management. This code can be replaced with RecyclerView as well. Let me know if you want to convert it to RecyclerView. I can help you with that.
Man, first of all use RecyclerView and don't worry about size of data. Secondly make a class which will contains your data:
class Data {
int id;
String name;
String imageUrl;
public Data(int id, String name, String imageUrl) {
this.id = id;
this.name = name;
this.imageUrl = imageUrl;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getImageUrl() {
return imageUrl;
}
}
Please, research information about how to use RecyclerView and why RecyclerView is better that ListView.
Set wrap_content to the height of root layout in product_list_items layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:orientation="horizontal"
android:weightSum="100" >
<ImageView
android:id="#+id/prod_main_image"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_weight="60"
app:srcCompat="#color/background_holo_light" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="40"
android:orientation="vertical" >
<TextView
android:id="#+id/prod_name_text"
android:layout_width="278dp"
android:layout_height="60dp"
android:text="#string/prod_name_text" />
<TextView
android:id="#+id/prod_cost_text"
android:layout_width="278dp"
android:layout_height="60dp"
android:text="#string/prod_cost_text" />
</LinearLayout>

Update custom listview from a button

I have a custom row item xml and a Activity xml which has a button, a textbox and a listview. Can anybody give me a very simple example on how this is done? I know i will need a adapter (what it extends i dont know) and update it from the button
I have tried getting the list view updated from the button with the editview text but cant get the adapter code to be hit. I am looking at base adapters now but cant help but feel this shouldn't be complicated and need so many override methods.
Activity class
public class InvitePlayers_Activity extends Activity {
ListViewAdapter emailAdapter = null;
ImageView imgView_mail;
ImageView imgView_confirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //remove title bar
setContentView(R.layout.activity_inviteplayers);
//Generate list View from ArrayList
displayListView();
}
private void displayListView() {
//assign controls
final ListView listView = (ListView) findViewById(R.id.listView_invitePlayers);
imgView_mail = (ImageView)findViewById(R.id.imgView_mail);
//Test data
ArrayList<String> inviteNew = new ArrayList<String>();
final ArrayList<ArrayList<String>> inviteList = new ArrayList<ArrayList<String>>();
emailAdapter = new ListViewAdapter(this,inviteList);
listView.setAdapter(emailAdapter);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
//Edit listeners
imgView_mail.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
//variables
final String enteredMail = "testListViewEntry";
final ArrayList<ArrayList<String>> inviteList = new ArrayList<ArrayList<String>>();
ArrayList<String> invite = new ArrayList<String>();
invite.add(0, enteredMail);//add first email
invite.add(1,"icon_invitestatussent.png"); //add first status icon
inviteList.add(invite);
emailAdapter.notifyDataSetChanged();
listView.setAdapter(emailAdapter);
}
});
}
}
Adapter class
public class ListViewAdapter extends BaseAdapter {
private Activity context;
ArrayList<ArrayList<String>> inviteDetails = new ArrayList<ArrayList<String>>();
public ListViewAdapter(Activity context, ArrayList<ArrayList<String>> inviteDetails ) {
this.inviteDetails = inviteDetails;
this.context = context;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public View getView(int position, View view, ViewGroup parent){
//Inflater
LayoutInflater inflater = context.getLayoutInflater();
//get row view
if (view == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.list_item_email, null);
}
//assign controls
final TextView textView_playerEmail = (TextView) view.findViewById(R.id.textView_playerEmail);
ImageView imgView_inviteStatus = (ImageView) view.findViewById(R.id.imgView_inviteStatus);
//Assign control values that are dynamic
textView_playerEmail.setText(inviteDetails.get(position).get(0));
imgView_inviteStatus.setImageResource(R.drawable.icon_invitestatussent);
return view;
}
public ArrayList<ArrayList<String>> addInvite(ArrayList<String> inviteDetails, ArrayList<ArrayList<String>> currentInvites)
{
currentInvites.add(inviteDetails);
return currentInvites;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
Custom row xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:id="#+id/textView_playerEmail"
android:textColor="#color/white"
android:text="item1">
</TextView>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView_inviteStatus" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgView_remove"
android:src="#drawable/btn_cancel" />
Activity layout
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:gravity="left|center">
<ImageView
android:layout_width="45dp"
android:layout_height="34dp"
android:id="#+id/imgView_mail"
android:src="#drawable/btn_mail"
android:layout_weight="0.22"
android:padding="3dp" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView_invitePlayers"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/btn_confirm"
android:src="#drawable/btn_confirm"
android:clickable="false"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:padding="2dp"
android:layout_weight="1" />
</LinearLayout>
From reading the description of the question I think you need to set custom adapter to show the elements in you listview. This is how you set the custom adapter for the listview:
public class Notes_list extends BaseAdapter
{
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public Notes_list(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname)
{
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
return id.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int pos, View child, ViewGroup arg2) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.custom_row, null);
mHolder = new Holder();
// mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
child.setTag(mHolder);
} else
{
mHolder = (Holder) child.getTag();
}
// mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
return child;
}
public class Holder
{
// TextView txt_id;
TextView txt_fName;
TextView txt_lName;
}
}
now in your main activity where you have to call the list enter code like this:
private ListView userList;
private ArrayList<Employee> itemsList = new ArrayList<modelName>();
userList = (ListView) findViewById(R.id.List);
UserList disadpt = new UserList(MainActivity.this, itemsList);
userList.setAdapter(disadpt);
Hope it helps...

Android custom ListView layout problems

Hi guys, I tried to learn how to use custom ListView by this page
It works fine but I have problems with another options.
Cannot set margin to listItems
Cannot set backgro
Cannot set OnItemClickListener
1# Margin
First of all I'm trying to set margin between list items but nothing works. I try to set margin on RelativeLayout in rowlayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
2# Background
I want to set background on whole screen under listView. I think I put black color on every View in every xml I found but nothing affect the background. I can change background of single list items, that's all.
android:background="#000000"
3#OnItemClickListener
My last problem is that I'm not able to set onItemClickListener. I have no idea how to set it if I don't have simply ListView but RelativeLayout with TextView etc.
I guess I have to use
setOnClickListener(new OnClickListener()
and after that
public void onClick(View arg0) {
but I have no idea on which View I have to use this method.
Files
MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.rowlayout, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.rowlayout, parent, false);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView counterView = (TextView) rowView.findViewById(R.id.item_counter);
// 4. Set the text for textView
imgView.setImageResource(modelsArrayList.get(position).getIcon());
titleView.setText(modelsArrayList.get(position).getTitle());
counterView.setText(modelsArrayList.get(position).getCounter());
}
else{
//rowView = inflater.inflate(R.layout.group_header, parent, false);
// TextView titleView = (TextView) rowView.findViewById(R.id.header);
// titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Model.java
package com.example.sunny.katan;
/**
* Created by Sunny on 15.09.14.
*/
public class Model{
private int icon;
private String title;
private String counter;
private boolean isGroupHeader = false;
public Model(String title) {
this(-1,title,null);
isGroupHeader = true;
}
public Model(int icon, String title, String counter) {
super();
this.icon = icon;
this.title = title;
this.counter = counter;
}
public String getCounter() {
return counter;
}
public String getTitle() {
return title;
}
public int getIcon() {
return icon;
}
public boolean isGroupHeader() {
return false;
}
public void setGroupHeader(boolean isGroupHeader) {
this.isGroupHeader = isGroupHeader;
}
//gettters & setters...
}
main.java
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// if extending Activity
//setContentView(R.layout.activity_main);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
// if extending Activity 2. Get ListView from activity_main.xml
//ListView listView = (ListView) findViewById(R.id.listview);
// 3. setListAdapter
//listView.setAdapter(adapter); if extending Activity
setListAdapter(adapter);
}
private ArrayList<Model> generateData(){
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model(R.raw.barbell,"Cviky","37"));
models.add(new Model(R.raw.stretching,"Protahování","94"));
models.add(new Model(R.raw.work,"Generování workoutu","293"));
return models;
}
rowlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<!-- icon -->
<ImageView
android:id="#+id/item_icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:src="#raw/barbell"
/>
<!-- title -->
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/item_icon"
android:layout_marginTop="30dp"
android:layout_alignBaseline="#+id/item_counter"
android:textSize="20dp"
/>
<!-- counter -->
<TextView
android:id="#+id/item_counter"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:background="#drawable/rectangle"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="false"
>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".katan_lobby"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/menu"
android:layout_gravity="center_horizontal"
android:background="#238CD4"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prvniItemSeznamu"
android:background="#238CD4"
style="#style/listView"
/>
</LinearLayout>
</ScrollView>
Looks like you are half way there in your activity.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
MyAdapter adapter = new MyAdapter(this, generateData());
ListView listView = (ListView) findViewById(R.id.menu);
listView.setAdapter(adapter); if extending Activity
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//You now have the position but you will need to get your model list and use .get(position) and cast it to Model to get access to it.
}
});
}
//First define your list view item xml… something like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
android:layout_marginTop="10dp"
android:padding="10dp" >
<TextView
android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/custom_blue"
android:text="TextView" />
<TextView
android:id="#+id/item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="#color/custom_grey"
android:text="TextView" />
</LinearLayout>
//Then you define your list list adapter.
public class MyListAdapter extends ArrayAdapter<MyModel> {
private Context context;
private ArrayList<MyModel> myModel;
public MyListAdapter(Context context, ArrayList<MyModel> myModelList) {
super(context, R.id.icon, myModelList);
this.context = context;
this.myModelList = myModelList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = null;
View rowView = convertView;
TextView myItemName = (TextView)rowView.findViewById(R.id.item1);
TextView myItemTitle = (TextView)rowView.findViewById(R.id.item2);
//use your models getters/setters
myItemName.setText(myModelList.get(position).getItemTitle());
myItemTitle.setText(myModelList.get(position).getItemName());
return rowView
}
}
//Now use both the list adapter and list item in your ListFragment or ListActivity.
ArrayList<MyModel> myModelList = new ArrayList<MyModel>();
MyListAdapter myApt = new MyListAdapter(this, myModelList);
setListAdapter(myApt);
//For clicking on the items:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// ListView Clicked item value
String itemValue = l.getItemAtPosition(position).toString();
doSomethingWihtMyItemMethod(position);
}
/* You can customize your list item anyway you like, just be aware of screen real estate when doing so.Hope this helps. */

Utilising my created list view. Android

I am trying to use list views and I have managed to create one and it works perfectly. However it creates itself in a new screen. I'd like to know how I can use an already created list view in the main menu (defined by main.xml).
My Java Code:
public class Option2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent startNewActivityOpen = new Intent(Option2Activity.this, ListViewActivity.class);
startActivityForResult(startNewActivityOpen, 0);
}
}
public class ListViewActivity extends ListActivity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ListView lv = (ListView)findViewById(R.id.listview_main);
// Currently unused...
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.list_titles);
TypedArray icons = res.obtainTypedArray(R.array.list_icons);
setListAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
//I tried using lv.setAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
//but it didn't work. 'setListAdapter' is creating a new listview in another screen
}
}
public class Adapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public Adapter(Context ctx, int viewResourceId, String[] strings, TypedArray icons)
{
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount()
{
return mStrings.length;
}
#Override
public String getItem(int position)
{
return mStrings[position];
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(mViewResourceId, null);
Button ib = (Button)convertView.findViewById(R.id.list_button);
ib.setText(mStrings[position]);
ib.setCompoundDrawables((mIcons.getDrawable(position)), null, null, null);
//this doesn't work either, it is supposed to set an image in the button
//if anyone knows how to help me I'd appreciate but it isn't the main issue
TextView tv = (TextView)convertView.findViewById(R.id.list_text);
tv.setText(mStrings[position]);
return convertView;
}
}
THE XML
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:maxHeight="50dp"
android:maxWidth="50dp"
android:src="#drawable/newsimage" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:maxHeight="50dp"
android:maxWidth="50dp"
android:src="#drawable/newsimage" />
<TextView
android:id="#+id/textView1"
android:layout_marginTop="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="Option 2 Menu"
android:textSize="25dp" />
</RelativeLayout>
<ListView
android:id="#+id/listview_main"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/newspaper"
android:scaleType="fitXY"
/>
</LinearLayout>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/list_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24dp"
android:padding="6dp"
/>
<Button
android:id="#+id/list_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I think this is all the relevant code. Thank you in advance. I also would like to include that a piece of this code was referenced from other developers which I searched in forums.
FIXED
public class Option2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView)findViewById(R.id.listview_main);
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.list_titles);
TypedArray icons = res.obtainTypedArray(R.array.list_icons);
lv.setAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
}
}
Not exactly like the latest user's reply. But it worked. There is no need for the ListViewActivity.
Thank you forum.
Remove ListViewActivity activity just use the activity I given below,
public class Option2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView)findViewById(R.id.listview_main);
// Currently unused...
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.list_titles);
TypedArray icons = res.obtainTypedArray(R.array.list_icons);
lv.setListAdapter(new Adapter(ctx, R.layout.list_item, options, icons));
}
public class Adapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public Adapter(Context ctx, int viewResourceId, String[] strings, TypedArray icons)
{
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount()
{
return mStrings.length;
}
#Override
public String getItem(int position)
{
return mStrings[position];
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(mViewResourceId, null);
Button ib = (Button)convertView.findViewById(R.id.list_button);
ib.setText(mStrings[position]);
ib.setCompoundDrawables((mIcons.getDrawable(position)), null, null, null);
//this doesn't work either, it is supposed to set an image in the button
//if anyone knows how to help me I'd appreciate but it isn't the main issue
TextView tv = (TextView)convertView.findViewById(R.id.list_text);
tv.setText(mStrings[position]);
return convertView;
}
}
Try this,

Custom list displayed is empty

I have a donorview class which extends linearlayout which is as follows:
public class donorview extends LinearLayout {
private TextView donortext;
private String donorstr;
private ImageButton call;
private ImageButton msg;
private String donornumber;
private Context context1;
private View convertView;
public donorview(Context context, String donorname1, String donornum) {
super(context);
context1 = context;
// TODO Auto-generated constructor stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listformat, null);
convertView.setClickable(true);
donortext = (TextView) findViewById(R.id.donornametext);
call = (ImageButton) findViewById(R.id.call);
msg = (ImageButton) findViewById(R.id.msg);
System.out.println("donorname:"+donorname1);
System.out.println("donornum:"+donornum);
donortext.setText(donorname1);
System.out.println("after setting text");
donorstr = donorname1;
donornumber = donornum;
}
void onClickCall(){
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + donornumber));
convertView.getContext().startActivity(callIntent);
}
public void setdonorname(String donorname12) {
donortext.setText(donorname12);
}
public String getdonorname() {
return this.donorstr;
}
}
I get a NullPoinerException as
java.lang.NullPonintereException
at com.wglxy.example.dash1.donorview.<init>(donorview.java:35)
while setting the text of the textview donortext. My XML layout of the listformat is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/linerlayout1"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/donornametext" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_weight="1" android:text="a"/>
<ImageButton android:layout_width="wrap_content" android:id="#+id/call"
android:layout_height="wrap_content" android:contentDescription="#string/description_about"
android:src="#drawable/call" android:onClick="onClickCall"
android:background="#ffffff" />
<ImageButton android:layout_width="wrap_content" android:id="#+id/msg"
android:layout_height="wrap_content" android:contentDescription="#string/description_about"
android:src="#drawable/msg" android:onClick="onClickMsg"
android:background="#ffffff" />
</LinearLayout>
I dont understand what I am doing wrong. The list that is being displayed is empty. When i am printing the donorname and donornum it is being printed but the custom list displayed is empty.I have been trying to figure it out from a long time. Could anyone please help me with this?
My adapter code is as follows
public class donorAdapter extends BaseAdapter {
private Activity activity;
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> nums = new ArrayList<String>();
private Context context;
private String strnum;
private String strname;
private static LayoutInflater inflater = null;
public donorAdapter(Context context, Activity a, ArrayList<String> names,
ArrayList<String> nums) {
this.context = context;
activity = a;
this.names = names;
this.nums = nums;
inflater = LayoutInflater.from(activity);
}
public int getCount() {
return names.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
donorview fv;
if (convertView == null) {
System.out.println("inside getview:"+names.get(position).toString());
strname=names.get(position).toString();
strnum=nums.get(position).toString();
System.out.println("inside getview:"+nums.get(position).toString());
fv = new donorview(context, strname,strnum);
convertView = fv;
}
else {
((donorview) convertView).setdonorname(names.get(position)
.toString());
}
convertView.setClickable(true);
convertView.setFocusable(true);
return convertView;
}
}
-Thanks in advance
You should use
donortext = (TextView)convertView.findViewById(R.id.donornametext);
and also replace your code by
convertView = inflater.inflate(R.layout.listformat, this);
Replace
findViewById
with
convertView.findViewById()
you use findViewById, when you have already set the content for the activity, in your case you did not , so you have to specify which view it has to look to get the id. You have to do the same for the rest of your views.

Categories

Resources