NullPointException in ListView when getting button - java

I am having a weird problem and can't seem to find whats causing it. Every view component in my ArrayAdapter is being located in the getView method except my button which is causes a NullPointerException.
Adapter:
public class ItemAdapter extends ArrayAdapter<Item>{
private Context context;
private int resource;
private List<Item> list;
public ItemAdapter(Context context, int resource, List<Item> list)
{
super(context, resource, list);
this.context = context;
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(resource, parent,false);
TextView name = (TextView) convertView.findViewById(R.id.itemName);
ImageView itemImg = (ImageView) convertView.findViewById(R.id.itemImg);
Button addToCart = (Button) convertView.findViewById(R.id.button1);
final Item item = list.get(position);
name.setText(item.getName());
UrlImageViewHelper.setUrlDrawable(itemImg, item.getPicture());
addToCart.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view)
{
Toast.makeText(context, "Clicked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Fragment with listview
#InjectView(R.id.itemList) private ListView listView;
#Inject private ItemDao dao;
private ArrayAdapter<Item> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_shop, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
dao.open();
List<Item> items = dao.findAll();
dao.close();
adapter = new ItemAdapter(getActivity(),R.layout.list_product_item, items);
listView.setAdapter(adapter);
}
list_product_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp" >
<ImageView
android:id="#+id/itemImg"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginRight="5dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/itemStoreName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Now the call to convertView.findViewById(R.id.button1) returns a null instance. What is the cause of this and how can I fix it.

do you have right the name of the layout?
adapter = new GroceryItemAdapter(getActivity(), R.layout.list_textview, items);
vs.
list_product_item
(I am assuming this is the file name for R.layout.list_product_item)

Instead of getting the layout inflater using the from method try initializing the inflater in the constructor..
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
in the getView
convertView = mInflater.inflate(your layout, null);

Related

Android : How to get a reference of a button defined in resource XML and not in Activity XML

Basically I am trying to code a onClickListener for a button in MainActivity.java .
This Button is defined in a resource file : main_resource.xml inside a ListView and not in activity_main.xml.
I am getting the error :
Trying to define a onClick Listener on null item.
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
});
Here is my main_resource.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/ridedetails"
android:layout_marginLeft="2dip">
</TextView>
<EditText
android:layout_height="wrap_content"
android:hint="Quote Price"
android:layout_width="wrap_content"
android:id="#+id/PriceQuotation"
android:layout_below="#+id/ridedetails"
android:layout_marginLeft="2dip">
</EditText>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/PriceQuotation"
android:layout_marginStart="61dp"
android:layout_toEndOf="#+id/PriceQuotation"
android:text="Button" />
</RelativeLayout>
Here is my activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
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:id="#+id/myrefresh"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/activity_home_drawer" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PreviousRide"
>
<ListView
android:id="#+id/incomingrides"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="30dp"
android:layout_marginTop="80dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</android.support.v4.widget.SwipeRefreshLayout>
Here I am not using any Custom Adapter Class : I am injecting the data into my list view using the following ArrayAdapter code written in onRefresh() of Swipe Refresh Widget ::
final ArrayAdapter<String > adapter=new ArrayAdapter<String>(getApplicationContext(),
R.layout.home_resource, R.id.ridedetails, allNames);
l1.setAdapter(adapter);
// L1 is the listView Reference
You have to create custom class for adapter
Here is sample code for adapter.
public class MyAdapter extends ArrayAdapter<String> {
private int resourceId;
private List<String> sites = null;
private Context context;
public MyAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.context = context;
this.resourceId = resource;
this.sites = objects;
}
#Override
public String getItem(int position) {
return sites.get(position);
}
#Override
public int getCount() {
return sites.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String name = getItem(position);
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(resourceId, null);
}
TextView mTextView = (TextView) view.findViewById(R.id.ridedetails);
mTextview.setText(name);
Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
set adapter in listview like below code.
l1.setAdapter(new MyAdapter(getApplicationContext(), R.layout.home_resource, allNames));
you should put your onClickListener in Adapter Not in Main Activity
Your Adapter
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Button btn = (Button ) v.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
})
}

Custom GridView Adapter not displaying

I'm creating a list of "channels" on an app that users can select. I want them in a grid view, (kind of like clickable tiles). There are supposed to be two separate Grids on this Fragment - default channels (channelListSupplied) and ones that the user will have to request subscriptions to (channelListEarned).
I used a custom adapter that I got from another answer here on SO, but I can't get it to work because it's in a Fragment instead of in the Activity, and I'm sure there's some reference I'm not passing correctly.
Below is a list of the relevant pieces of Java and XML...
FragmentChannels.java: (fragment to MainActivity.java)
public class FragmentChannels extends Fragment implements FragmentManager.OnBackStackChangedListener {
ViewGroup container;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
final JSONObject channelList = data.getJSONObject("channels");
final JSONArray channelListSupplied = channelList.getJSONArray("supplied");
final JSONArray channelListEarned = channelList.getJSONArray("earned");
GridView channelViewSupplied = (GridView) view.findViewById(R.id.channel_grid_supplied);
GridView channelViewEarned = (GridView) view.findViewById(R.id.channel_grid_earned);
if (Session.getSessionVar("canHasSpecial").equals("1")) {
FragmentChannels.this.createGridView(channelViewEarned, channelListEarned, FragmentChannels.this.container);
}
FragmentChannels.this.createGridView(channelViewSupplied, channelListSupplied, FragmentChannels.this.container);
...
return view;
}
public void createGridView(final GridView gridView, JSONArray list, final ViewGroup container) throws JSONException {
final String[] gridList = new String[list.length()];
final Activity activity = getActivity();
for (int i = 0; i < list.length(); i++) {
JSONObject channelData = (JSONObject) list.get(i);
gridList[i] = channelData.getString("source_name");
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
gridView.setAdapter(new GridViewAdapter(activity, gridList, container));
}
});
}
public boolean createChannelMenu(Menu menu) {
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_channels, menu);
super.onCreateOptionsMenu(menu, inflater);
return true;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final Activity activity = getActivity();
}
#Override
public void onBackStackChanged() {
}
}
GridViewAdapter.java:
public class GridViewAdapter extends BaseAdapter {
private Context context;
private final String[] textViewValues;
private ViewGroup container;
public GridViewAdapter(Context context, String[] textViewValues, ViewGroup container) {
this.context = context;
this.textViewValues = textViewValues;
this.container = container;
}
#Override
public int getCount() {
return this.textViewValues.length;
}
#Override
public Object getItem(int position) {
return textViewValues[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("CDFF", position+": "+this.textViewValues[position]);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = inflater.inflate(R.layout.grid_item_layout, this.container);
TextView titleView = (TextView) gridView.findViewById(R.id.grid_item_title);
titleView.setText(textViewValues[position]);
}
else {
gridView = convertView;
}
return gridView;
}
}
fragment_channels.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="FragmentChannels"
android:id="#+id/fragment_channel_container"
tools:context="xx.xxx.xxxx.FragmentChannels"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:text="My Channels"
android:background="#color/peach"
android:textSize="20sp"
android:textColor="#color/midnightBlue"
android:gravity="center"
android:textAppearance="#style/TextAppearance.FontPath"
/>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/channel_grid_earned"
android:layout_margin="5dp"
android:columnWidth="180dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/channel_grid_supplied"
android:layout_margin="5dp"
android:columnWidth="180dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</FrameLayout>
grid_item_layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#color/white"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="150dp"
android:layout_height="100dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/grid_item_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:gravity="center"
android:maxLines="2"
android:ellipsize="marquee"
android:textSize="12sp" />
</RelativeLayout>
As of now, nothing displays on the Fragment except the "My Channels" TextView.
I greatly appreciate any help!
Fixed.
I changed the line:
gridView = inflater.inflate(R.layout.grid_item_layout, this.container);
To:
gridView = inflater.inflate(R.layout.grid_item_layout, null);
in the GridViewAdapter.java class.

setOnItemClickListener is not working for ArrayAdapter<ImageView>

When i try to click on items in the list it doesnt go through the onItemClick method.
GridViewAdapter.java
public class GridViewAdapter extends ArrayAdapter<ImageItem>{
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList<ImageItem>();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView gridView;
private GridViewAdapter customGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(customGridAdapter);
Log.d("yyoyoyoyo", "jhgvkbkhbjkhbj");
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, position + "#Selected",
Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<ImageItem>();
// retrieve String drawable array
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
row_grid.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="vertical"
android:padding="5dp"
android:clickable="true"
android:background="#drawable/grid_color_selector"
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
>
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</ImageView>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="12sp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</TextView>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:clickable="false"
android:descendantFocusability="blocksDescendants"
tools:context=".MainActivity" >
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:drawSelectorOnTop="true"
android:stretchMode="columnWidth"
android:descendantFocusability="blocksDescendants"
>
</GridView>
</RelativeLayout>
I have tried most of the solutions regarding this topic on StackOverFlow none of them worked for me. This app lists all the images but when you click onItemClick isnt fired. Probably there is something wrong with my code.
Thank you!!
Remove android:clickable="true" in row_grid.xml. and add android:clickable="true" in activity_main.xml
Also remove the
android:focusable="false"
android:focusableInTouchMode="false"
As row_grid.xml is clickable, it blocks the grid's onclick listener from responding.

Android Custom ListView Adapter doesn't populate

Long time stack user, first time poster. I have followed several Custom ListView Adapter tutorials and have not been able to get this one to work (I have successfully created these adapters before). I have spent way too many hours trying to get this to work!!! Can someone please have a look and hopefully find the silly mistake that I made?
This is in MainActivity.java onCreate() to call the list
//Declaration for the list
private ArrayList<Consumption> meals = new ArrayList<Consumption>();
private RAdapter rAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal);
//This is the first of two listviews on the activity
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
//This is the listview I am having problems with
ListView listView2 = (ListView) findViewById(R.id.resultList);
rAdapter = new RAdapter(this,meals);
listView2.setAdapter(rAdapter);
}
I have triple checked that meals has data, it does.
This is the RAdapter.java (The Custom Adapter) code:
public class RAdapter extends ArrayAdapter<Consumption>{
static class holder{
TextView rName;
EditText quan;
ImageButton delete;
}
private ArrayList<Consumption> meals;
private final Context context;
public RAdapter(Context context) {
super(context, R.layout.result_row);
this.context = context;
}
public RAdapter(Context context, ArrayList<Consumption> meals) {
super(context, R.layout.result_row);
this.context = context;
this.meals = meals;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
holder h = null;
if (v == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
v = inflater.inflate(R.layout.result_row, parent, false);
h = new holder();
h.rName = (TextView) v.findViewById(R.id.resultName);
h.quan = (EditText) v.findViewById(R.id.resultGrams);
h.delete = (ImageButton) v.findViewById(R.id.resultDelete);
v.setTag(h);
}else{
h = (holder) v.getTag();
}
Consumption i = meals.get(position);
h.rName.setText(i.getShortName());
h.quan.setText(i.getQuantity());
return v;
}
}
Here is result_row.xml (The specific row to populate):
<?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="wrap_content" >
<ImageButton
android:id="#+id/resultDelete"
android:layout_marginLeft="10dp"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_notification_clear_all"
android:contentDescription="#string/meal_remove" />
<TextView
android:id="#+id/resultName"
android:layout_marginLeft="10dp"
android:layout_width="150dp"
android:layout_height="40sp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/resultDelete" />
<EditText
android:id="#+id/resultQuantity"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="50dp"
android:layout_height="40sp"
android:inputType="numberDecimal"
android:layout_toRightOf="#+id/resultName"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/resultGrams"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/resultQuantity"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/grams" />
</RelativeLayout>
Here is activity_meal.xml (which has the listview "resultList" in it):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/semislantedbacktransparent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MealActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/translateButton"
android:layout_width="100dp"
android:layout_height="65dp"
android:background="#drawable/addtorecipe"
android:contentDescription="#string/dummy_button"
android:text="#string/button_add_recipe" />
</LinearLayout>
<SearchView
android:id="#+id/searchView1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/search"
android:focusable="true"
android:iconifiedByDefault="false"
android:onClick="enterTomInput"
android:queryHint="Search for food items"
android:showAsAction="always"
android:textColor="#000000" >
</SearchView>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignLeft="#+id/searchView1"
android:layout_below="#+id/searchView1"
android:cacheColorHint="#color/black_overlay" >
</ListView>
<ListView
android:id="#+id/resultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_below="#+id/listView1" />
<ImageButton
android:id="#+id/completeButton"
android:layout_width="100dp"
android:layout_height="65dp"
android:layout_alignRight="#+id/resultList"
android:layout_alignTop="#+id/linearLayout1"
android:background="#drawable/completemeal"
android:contentDescription="#string/dummy_button" />
</RelativeLayout>
I can post a logcat, but there is no error message to report. I have tried putting System prints everywhere, but cannot figure the problem out.
Any help would be much appreciated!!
Just change following code and fill your arraylist with data.
public RAdapter(Context context, ArrayList<Consumption> meals) {
super(context, R.layout.result_row);
this.context = context;
this.meals = meals;
}
to
public RAdapter(Context context, ArrayList<Consumption> meals) {
super(context, R.layout.result_row,meals);
this.context = context;
this.meals = meals;
}
in your adapter class.
change your adapter like this
public class RAdapter extends ArrayAdapter<Consumption> {
private Activity activity;
private ArrayList<Consumption> meals;
private LayoutInflater inflater = null;
public RAdapter (Activity act, int resource, ArrayList<Consumption> arrayList) {
super(act, resource, arrayList);
this.activity = act;
this.meals= arrayList;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.result_row, parent, false);
}
//remaining code
return view;
}
}
and call this adapter
rAdapter = new RAdapter(MainActivity.this,R.layout.result_row,meals);
listView2.setAdapter(rAdapter);

Android ListView based in custom BaseAdapter is not shown in my code

I've working on ListView with a custom BaseAdapter which I've watched on the Slidenerd tutorial series here:(It's not important to watch to understand my question)
http://www.youtube.com/watch?v=_l9e2t4fcfM&list=PLonJJ3BVjZW6hYgvtkaWvwAVvOFB7fkLa&index=91
After running the code on the virtual device there is no error but not ListView too.
Is it possible to tell me what's the problem of my code?
public class List extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new EhsanAdapter(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
}
class SingleRow{
String title;
String description;
int image;
public SingleRow(String title,String description,int image) {
this.title = title;
this.description=description;
this.image=image;
}
}
class EhsanAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
Context context;
public EhsanAdapter(Context c) {
list = new ArrayList<SingleRow>();
context = c;
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
String[] descriptions = res.getStringArray(R.array.descriptions);
int[] images = {R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5};
for(int i=0;i<10;i++){
list.add(new SingleRow(titles[i], descriptions[i], images[i]));
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView description = (TextView) row.findViewById(R.id.txtDescription);
ImageView image = (ImageView) row.findViewById(R.id.imgPic);
SingleRow temp = list.get(i);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;
}
}
The layout of activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".List" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
The layout of single row:
<?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="match_parent" >
<ImageView
android:layout_margin="10dp"
android:id="#+id/imgPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/image1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Title"
android:id="#+id/txtTitle"
android:layout_alignTop="#+id/imgPic"
android:layout_toRightOf="#+id/imgPic"
android:layout_alignParentRight="true">
</TextView>
<TextView
android:id="#+id/txtDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imgPic"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#+id/imgPic"
android:layout_marginTop="20dp"
android:text="Description"
android:ems="10">
</TextView>
</RelativeLayout>
Remove the line LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); from getView() method and instead add it in the constructor of EhsanAdapter class.
I see different issues:
The layout of single row contains a relative layout which the android:layout_height="match_parent" should be android:layout_height="wrap_content"
Then inside the Adapter you are neither recycling the views nor using the ViewHolder pattern:
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
About ViewHolder pattern implementation optimisation in ListView
http://www.jmanzano.es/blog/?p=166
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){ //The row view is not created, let's do it:
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView description = (TextView) row.findViewById(R.id.txtDescription);
ImageView image = (ImageView) row.findViewById(R.id.imgPic);
// Here we add the title, description and image inside the ViewHolder
....
}else{
//With the View holder pattern we get the views inside the row view to fill it later
....
}
// Now we get the SingleRow and we fill it using the ViewHolder pattern
SingleRow temp = list.get(i);
....
return row;
}
You only have 5 images and you wrote i<10 you should've wrote i<5 the amount of "titles" and "descriptions" and "images" must be the same.
for(int i=0;i<5;i++){
list.add(new SingleRow(titles[i], descriptions[i], images[i]));
}

Categories

Resources