ListView is null in Fragment - android

I want to create a ListView in a Fragment for chats just like WhatsApp but the adapter is showing null. Below is my code :
ChatsFragment.java
package com.houssup.userchat;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
public class ChatsFragment extends Fragment {
ListView list;
CustomChatAdapter adapter;
public ChatsFragment chatsFragment = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.customrow_chat, container, false);
ListView lv= ( ListView )view.findViewById( R.id.list ); // List defined in XML ( See Below )
/**************** Create Custom Adapter *********/
setListData();
adapter=new CustomChatAdapter( getContext(), CustomListViewValuesArr);
lv.setAdapter(adapter);
return view;
}
public void setListData()
{
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setName("Swapnil"+i);
sched.setDesignation("Interior Designer"+i);
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add( sched );
}
}
}
CustomChatAdapter.java
package com.houssup.userchat;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by hp on 01-06-2016.
*/
public class CustomChatAdapter extends BaseAdapter{
private Context context;
private ArrayList data;
private static LayoutInflater inflater=null;
ListModel tempValues=null;
int i=0;
/************* CustomChatAdapter Constructor *****************/
public CustomChatAdapter(Context context, ArrayList d) {
/********** Take passed values **********/
this.context=context;
data=d;
/*********** Layout inflator to call external xml layout () ***********/
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView name;
public TextView designation;
public CircleImageView image;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.customrow_chat, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.name = (TextView) vi.findViewById(R.id.name);
holder.designation=(TextView)vi.findViewById(R.id.designation);
holder.image= (CircleImageView) vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.name.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = ( ListModel ) data.get( position );
/************ Set Model values in Holder elements ***********/
holder.name.setText( tempValues.getName() );
holder.designation.setText( tempValues.getDesignation() );
holder.image.setImageResource(R.drawable.circuladp);
/******** Set Item Click Listner for LayoutInflater for each row *******/
/* vi.setOnClickListener(new OnItemClickListener( position ));*/
}
return vi;
}
/* #Override
public void onClick(View v) {
Log.v("CustomChatAdapter", "=====Row button clicked=====");
}*/
/********* Called when Item click in ListView ************/
/* private class OnItemClickListener implements View.OnClickListener {
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
*//*#Override
public void onClick(View arg0) {
CustomListViewAndroidExample sct = (CustomListViewAndroidExample)activity;
*//**//**** Call onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****//**//*
sct.onItemClick(mPosition);
}*/
}
fragment_chats.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"
tools:context="com.houssup.userchat.ChatsFragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</FrameLayout>
customrow_chat.xml
<?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="wrap_content"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/circuladp"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_below="#id/title"
android:text="Yashvant Rai Bacchhan"
android:layout_marginLeft="50dp"
android:textSize="18dp"
android:textColor="#000000"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/designation"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="6dp"
android:layout_marginLeft="55dp"
android:textSize="14dp"
android:layout_height="wrap_content"
android:text="Designer"/>
</LinearLayout>
</LinearLayout>
This fragment is in a TabActivity.I don't know why it is showing null. Any help will be appreciated !!

The code shows that you inflating the fragment view for the layout 'R.layout.customrow_chat' but the layout name is 'fragment_chats.xml'. Typo?

See you code. you convertView is always null.
change it:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.customrow_chat, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.designation=(TextView)convertView.findViewById(R.id.designation);
holder.image= (CircleImageView) convertView.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
if(data.size()<=0)
{
holder.name.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = ( ListModel ) data.get( position );
/************ Set Model values in Holder elements ***********/
holder.name.setText( tempValues.getName() );
holder.designation.setText( tempValues.getDesignation() );
holder.image.setImageResource(R.drawable.circuladp);
/******** Set Item Click Listner for LayoutInflater for each row *******/
/* vi.setOnClickListener(new OnItemClickListener( position ));*/
}
return convertView;
}

Related

Imageview getting automatically changed on scroll listview

I am new to android and facing one very comman problem of listview i googled alot but did'nt found anything usefull for my case.Hope you people show me the right direction.Whenever I am changing my image from "plus" to "tick" on click my last item image also got automatically changed on scroll.
My list_comapare_product XMl :-
<?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:background="#color/white_color"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/white_color"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/img_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/crane" />
<com.mss.skyjack.custom.views.SkyjackCustomTextview
android:id="#+id/tv_product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="test"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/img_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/plus" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/black_color" />
</LinearLayout>
Here is my Adapter :-
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ComapreProductSelectionAdapter extends BaseAdapter {
Activity activity;
List<SelectorTest> listSelector;
private LayoutInflater mLayoutInflater;
public ComapreProductSelectionAdapter(Activity activity,
List<SelectorTest> listSelector) {
this.activity = activity;
this.listSelector = listSelector;
mLayoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listSelector.size();
}
#Override
public SelectorTest getItem(int position) {
return listSelector.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int i = position;
final SelectorTest listItem = listSelector.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.list_comapare_product, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvProductName = (TextView) convertView
.findViewById(R.id.tv_product_name);
viewHolder.imgProduct = (ImageView) convertView
.findViewById(R.id.img_product);
viewHolder.imgadd = (ImageView) convertView
.findViewById(R.id.img_plus);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imgadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.imgadd.getDrawable().getConstantState() == activity
.getResources().getDrawable(R.drawable.plus)
.getConstantState()) {
viewHolder.imgadd.setImageResource(R.drawable.tick);
} else {
viewHolder.imgadd.setImageResource(R.drawable.plus);
}
}
});
return convertView;
}
static class ViewHolder {
TextView tvProductName;
ImageView imgProduct, imgadd;
View viewRightLine;
}
}
Thanks.
You need to keep track of which items have been "ticked". I copied your adapter and made necessary changes. You can just copy-paste the code and it should work.
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ComapreProductSelectionAdapter extends BaseAdapter {
Activity activity;
List<SelectorTest> listSelector;
private LayoutInflater mLayoutInflater;
private ArrayList<Integer> tickedItems = new ArrayList<Integer>();
public ComapreProductSelectionAdapter(Activity activity,
List<SelectorTest> listSelector) {
this.activity = activity;
this.listSelector = listSelector;
mLayoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listSelector.size();
}
#Override
public SelectorTest getItem(int position) {
return listSelector.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int i = position;
final SelectorTest listItem = listSelector.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.list_comapare_product, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvProductName = (TextView) convertView
.findViewById(R.id.tv_product_name);
viewHolder.imgProduct = (ImageView) convertView
.findViewById(R.id.img_product);
viewHolder.imgadd = (ImageView) convertView
.findViewById(R.id.img_plus);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imgadd.setTag(position);
viewHolder.imgadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(tickedItems.contains((Integer)v.getTag()) {
//Already ticked, set to plus
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.plus));
tickedItems.remove((Integer)v.getTag());
} else {
tickedItems.add((Integer)v.getTag());
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.tick));
}
}
});
if(tickedItems.contains(position))
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.tick));
else
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.plus));
return convertView;
}
static class ViewHolder {
TextView tvProductName;
ImageView imgProduct, imgadd;
View viewRightLine;
}
}
As an extra, don't use ImageView.setImageResource() as it is inefficient.
Quote from Android docs about ImageView.setImageReource()
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.

'cannot be cast to' error in custom adapter

i have a application with slidemenu that have some fragments in it
two custom adapter i used that both of them are same code and just one of them have a image more than another
customadapter file is:
package ir.monocode.az;
import ir.monocode.az.R;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
public class CustomAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Context activity;
private ArrayList data;
private static LayoutInflater inflater=null;
public Resources res;
CatsModel tempValues=null;
int i=0;
Context context;
Typeface face;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Context context, ArrayList d,Resources resLocal) {
/********** Take passed values **********/
activity = context;
data=d;
res = resLocal;
/*********** Layout inflator to call external xml layout () **********************/
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
public View getView(int position, View convertView, ViewGroup parent) {
View vii=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vii = inflater.inflate(R.layout.catitems, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vii.findViewById(R.id.ctextView1);
holder.image=(ImageView)vii.findViewById(R.id.cimageView2);
Typeface typeface = Typeface.createFromAsset(holder.text.getContext().getAssets(),
"fonts/B YEKAN.TTF");
holder.text.setTypeface(typeface);
/************ Set holder with LayoutInflater ************/
vii.setTag(holder);
}
else
holder=(ViewHolder)vii.getTag();
if(data.size()<=0)
{
holder.text.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = (CatsModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValues.getCatName());
int resID = activity.getResources().getIdentifier("icon"+tempValues.getImage() , "drawable", activity.getPackageName());
holder.image.setImageResource(resID);
/******** Set Item Click Listener for LayoutInflater for each row ***********/
vii.setOnClickListener(new OnItemClickListener(position));
}
return vii;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.customonItemClick(mPosition);
}
}
}
articleadapter is:
package ir.monocode.az;
import ir.monocode.azmoonEstekhdami.R;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
public class ArticleAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Context activity;
private ArrayList data;
private static LayoutInflater inflater=null;
public Resources res;
ArticlesModel tempValues=null;
int i=0;
Context context;
Typeface face;
/************* CustomAdapter Constructor *****************/
public ArticleAdapter(Context context, ArrayList d,Resources resLocal) {
/********** Take passed values **********/
activity = context;
data=d;
res = resLocal;
/*********** Layout inflator to call external xml layout () **********************/
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflater.inflate(R.layout.articleitems, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.atextView1);
Typeface typeface = Typeface.createFromAsset(holder.text.getContext().getAssets(),
"fonts/B YEKAN.TTF");
holder.text.setTypeface(typeface);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.text.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = (ArticlesModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValues.getArticleName());
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.articleItemClick(mPosition);
}
}
}
and of course i have two xml layout for my items style:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cLinearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="right"
android:orientation="vertical"
android:paddingBottom="10dp" >
<LinearLayout
android:id="#+id/cLinearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="right" >
<TextView
android:id="#+id/ctextView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#215e76"
android:textSize="20sp" />
<ImageView
android:id="#+id/cimageView2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:maxHeight="20dp"
android:maxWidth="20dp"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<ImageView
android:id="#+id/cimageView1"
android:layout_width="10dp"
android:layout_height="match_parent"
android:background="#ffc20e" />
</LinearLayout>
</LinearLayout>
and another is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/aLinearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="right"
android:orientation="vertical"
android:paddingBottom="10dp" >
<LinearLayout
android:id="#+id/aLinearLayout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="right" >
<TextView
android:id="#+id/atextView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#215e76"
android:textSize="20sp" />
<ImageView
android:id="#+id/aimageView1"
android:layout_width="10dp"
android:layout_height="match_parent"
android:background="#ffc20e" />
</LinearLayout>
</LinearLayout>
now when i run program
fragment that fill with customadapter work very good
but fragment that filled by articlesadapter have below error
java.lang.ClassCastException: ir.monocode.az.ArticlesModel cannot be cast to ir.monocode.az.CatsModel
how i must solve my problem?
can you help me please?
thank you
You can solve with polymorphism. Replace the failing declaration (the one your cast error comes from) with the Interface BaseAdapter
Something like this (your relevant code wasn't posted, so this is just a guess)
CatsModel it = retrieveMyCustomAdapter();
becomes
BaseAdapter it = retrieveMyCustomAdapter();
A more formal approach would be to declare an abstract class extending BaseAdapter, and make both CatsModel and ArticlesModel inherit from this new class.

Get different multiple image views in a list view

I have been trying to implement a list view which has five image views in a single row of a list view. I found that it can be done with layout inflater but since I am new to android I could not exactly get how to make the best use of it. I want to get a view of this sort:
L,S,D,A,E are images and it should change accordingly for different users in the list view according to the data provided dynamically. Can anybody please help me with the code snippet for this, or just give me an idea on how to implement it?
Okay so your list view should inflate a layout of this type:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:id="#+id/layoutContainer" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv1" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv2" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv3" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv4" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv5" />
</LinearLayout>
Save it to row.xml located in your layout folder.
Next implement this in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter myAdapter = new CustomAdapter(getApplicationContext());
ListView mainListView = (ListView) findViewById(R.id.lv);
mainListView.setAdapter(myAdapter);
}
Finally, you need to create the CustomAdapter.java class, like this:
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class CustomAdapter extends BaseAdapter {
private Bitmap[][] data;
private int count;
private Context context;
public CustomAdapter(Context context) {
this.context = context;
data = new Bitmap[100][];
count = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public Bitmap[] getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View adapterView = convertView;
if (adapterView == null) {
adapterView = inflater.inflate(R.layout.row, null);
}
ImageView imageView = (ImageView) adapterView.findViewById(R.id.iv1);
imageView.setImageBitmap(data[position][0]);
//Repeat the last two steps for all five images, changing the last index accordingly
return adapterView;
}
public void addBitmapArray (Bitmap[] newValue) {
data[++count] = newValue;
}
}
In row of the list add a linear layout LinearLayout1 then do something like fallowing in your adapter add dynamically images to the list item..
public View getView(final int position, View convertView, ViewGroup parent)
{
// System.out.println(" inside KeyvalueAdapter..");
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.new_row, null);
holder = new ViewHolder();
holder.tv_title = (TextView) convertView.findViewById(R.id.titleTextView);
ImageView imageView = new ImageView(context);
imageView.setImageResource(resId);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearLayout.addView(imageView);
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
holder.tv_title.setText(notifList.get(position));
return convertView;
}
If you want to load different image you have to extend your listview adapter:
example if i understand correctly your question.
Check out this thread:
Android custom Row Item for ListView
You have to write your own xml with 5 imageviews

Android ListView row color

I'm trying to change the row color of my listView in customAdapter. There's an array of integer that include 0 and 1, I'm trying to read from the array and change the color of rows like this:
0 = white
1 = yellow
but it shows a yellow color in all rows.
This is my CustomAdapter:
package com.example.test;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<RowItem> {
ArrayList<Integer> test;
Context context;
public CustomAdapter(Context context, int resourceId, List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
SqliteHelper checkFav = new SqliteHelper(context);
checkFav.open();
test = checkFav.getFavForList();
checkFav.close();
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_layout, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.pTxt);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
int color0 = Color.YELLOW;
int colorDefault = Color.WHITE;
switch (test.get(position)){
case 0:
convertView.setBackgroundColor(colorDefault);
break;
case 1:
convertView.setBackgroundColor(color0);
}
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
And this is my row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:src="#drawable/active_icon" />
<TextView
android:id="#+id/pTxt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="20sp"
android:gravity="right"/>
</LinearLayout>
Thanks in advance.
getView() is called for each row in a list so you should not loop over all items in test but only handle the one denoted by position and you should do that after (not in) the if (convertView == null) block.
Edit:
getView() should do the following things:
Check if convertView isn't null (if it is, create a new View as you did)
Check if convertView is of the right type (this only matters if more than one kind of View is used in the list which is not the case here). If the type is wrong, create a new View.
Now we have a valid View for the list row.
Retrieve the data which affects how to display this row. In your case this would be the result of test.get(position). The position is the number of the requested row (starting with 0 at the top of the ListView).
Adjust the View according to your data (you did this in the for-loop but you should do it only once for the requested entry at position).
Return the View
In more complex situations you may have to do the third step before the second but not here.
Fast solution (not very nice code, but works):
#Override
public int getItem(int position){
return test.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int color0 = ....
int color1 = ....
int colorDefault = ...
switch (test.get(position)) {
case 0:
convretview.setBackgroundColor(color0);
break;
case 1:
convretview.setBackgroundColor(color1);
break;
default:
convretview.setBackgroundColor(colorDefault);
}
...
}

Custom Font in Android ListView for RSS Reader

I want to show News(Bengali language) from Rss feeds in Android ListView. When run the app nothing shows in screen. I'm sharing my codes. I will glad, if you guys tell me,if i doing anything wrong here
MainActivity.java
package com.andodev.android.reader;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.andodev.android.reader.data.RssItem;
import com.andodev.android.reader.listeners.ListListener;
import com.andodev.android.reader.util.RssReader;
public class NewsActivity extends Activity {
/**
* This method creates main application view
*/
List<RssItem> listItems = new ArrayList<RssItem>();
CustomAdapter adapt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
setContentView(R.layout.main);
try {
// Create RSS reader
RssReader rssReader = new RssReader("http://www.amaderbarisal.com/feed/");
// Get a ListView from main view
ListView itcItems = (ListView) findViewById(R.id.list);
adapt = new CustomAdapter(this, listItems);
itcItems.setAdapter(adapt);
// Set list view item click listener
itcItems.setOnItemClickListener(new ListListener(rssReader.getItems(), this));
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
}
}
CustomAdapter
/**
*
*/
package com.andodev.android.reader;
import java.util.List;
import com.andodev.android.reader.data.RssItem;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<RssItem> {
List<RssItem> listItems;
Context context;
public CustomAdapter(Context context,List<RssItem> listItems) {
super(context,R.layout.custom);
// TODO Auto-generated constructor stub
this.context = context;
this.listItems = listItems;
}
public RssItem getItem(int position){
return listItems.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
RssHolder holder = new RssHolder();
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.custom, null);
TextView tv = (TextView)v.findViewById(R.id.name);
Typeface myTYpe = Typeface.createFromAsset(context.getAssets(), "solaiman-lipi.ttf");
tv.setTypeface(myTYpe);
holder.RssTitle = tv;
v.setTag(holder);
}
else{
holder = (RssHolder) v.getTag();
RssItem p = listItems.get(position);
holder.RssTitle.setText(p.getTitle());
}
return v;
}
private static class RssHolder{
public TextView RssTitle;
}
}
custom.xml
<?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="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:textStyle="bold"
/>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"/>
</LinearLayout>
You are not setting the text in TextView in case convertView is null.
Instead of:
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.custom, null);
TextView tv = (TextView)v.findViewById(R.id.name);
Typeface myTYpe = Typeface.createFromAsset(context.getAssets(), "solaiman-lipi.ttf");
tv.setTypeface(myTYpe);
holder.RssTitle = tv;
v.setTag(holder);
}
else{
holder = (RssHolder) v.getTag();
RssItem p = listItems.get(position);
holder.RssTitle.setText(p.getTitle());
}
Use
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.custom, null);
holder = new ViewHolder();
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "solaiman-lipi.ttf")
holder.rssTitle = (TextView) convertView.findViewById(R.id.name);
holder.rssTitle.setTypeface(typeface);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.rssTitle.setText(listItems.get(position).getTitle());
return convertView;

Categories

Resources