| Icon(image) | Title(text) | cross(image) |
| | Description(text)| |
| | | coupon(image) |
Its a list view.
Here i want to get id of different items when clicked separately in list view like cross, coupon, icon is clicked then i will get their id...
I'm a newbie...Please help me out....
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/list_item_iv_icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="#string/app_name"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<ImageView
android:id="#+id/list_item_iv_icon_cross"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:contentDescription="#string/app_name"
android:src="#drawable/cross_selector" />
<TextView
android:id="#+id/list_item_tv_title"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_toRightOf="#+id/list_item_iv_icon"
android:gravity="left"
android:textColor="#CC0033"
android:textIsSelectable="false"
android:textSize="20sp" />
<TextView
android:id="#+id/list_item_tv_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/list_item_tv_title"
android:layout_toRightOf="#+id/list_item_iv_icon"
android:gravity="left"
android:textColor="#3399FF"
android:textIsSelectable="false"
android:textSize="14sp" />
<ImageView
android:id="#+id/list_item_iv_type"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignBottom="#id/list_item_iv_icon"
android:layout_alignParentRight="true"
android:contentDescription="#string/app_name" />
</RelativeLayout>
I know how to get id of the clicked list. i want to know is how to get item id of a clicked item in list.
Here is the answer for NewBies like Me...
<ImageView
android:id="#+id/list_item_iv_icon_cross"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:contentDescription="#string/app_name"
android:src="#drawable/cross_selector"
android:onClick="onCrossClick" />
i used onClick on item and to get position in which it has been clicked i used
final int position = listView.getPositionForView((View) v.getParent());
full code :-
public void onCrossClick(View v) {
final int position = listView.getPositionForView((View) v.getParent());
Toast.makeText(this, "click on button " + position, Toast.LENGTH_LONG)
.show();
}
The following is the code to set a listener for the list view which would capture the list item selection event.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
// To get the item from the list use the position value
Object yourObject = yourAdapter.getItem(position);
}
})
Check below Sample code :
public class ListViewAdapter_test extends BaseAdapter {
private LayoutInflater mInflater;
public ListViewAdapter_test(Context con) {
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(con);
}
public int getCount() {
// TODO Auto-generated method stub
return a_product_id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
// return product_id1.size();
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
// return product_id1.get(position).hashCode();
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
final ListContent holder;
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.scan_row1, null);
holder = new ListContent();
holder.name = (TextView) v.findViewById(R.id.sc_textname);
holder.name1 = (TextView) v.findViewById(R.id.sc_review);
holder.ratings = (RatingBar) v.findViewById(R.id.sc_ratingBar1);
holder.total_rate = (Button) v.findViewById(R.id.button1);
holder.img_p = (ImageView) v.findViewById(R.id.image_prod);
// holder.total_rate.setOnClickListener(mOnTitleClickListener1);
v.setTag(holder);
} else {
holder = (ListContent) v.getTag();
}
holder.total_rate.setOnClickListener(mOnTitleClickListener3);
holder.img_p.setOnClickListener(mOnTitleClickListener_image);
return v;
}
}
static class ListContent {
ImageView img_p;
TextView name1;
TextView name;
RatingBar ratings;
Button total_rate;
}
public OnClickListener mOnTitleClickListener3 = new OnClickListener() {
public void onClick(View v) {
final int position = list_v
.getPositionForView((View) v.getParent());
Log.d("you are click on Ratings","you are click on Ratings");
}
};
public OnClickListener mOnTitleClickListener_image = new OnClickListener() {
public void onClick(View v) {
final int position = list_v
.getPositionForView((View) v.getParent());
Log.d("you are click on image view","you are click on image view");
}
};
Related
I am still learning android. Here I need help to toggle between Play and Pause source in ImageButton in the ListView.
There should be only one song in Play state at a time. So if clicked other should stop.
SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {
public SongAdapter(#NonNull Context context, int resource, #NonNull List<Song> objects) {
super(context, resource, objects);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View playlistItemView = convertView;
if (playlistItemView == null) {
playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);
}
Song currentSong = getItem(position);
// get list item elements
ImageView albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
TextView songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
TextView songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
TextView songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
final ImageButton songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);
// set data to the list item
assert currentSong != null;
albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
songTitle.setText(currentSong.getSongTitle());
songAlbumTitle.setText(currentSong.getSongAlbumTitle());
songArtist.setText(currentSong.getSongSingers());
// set song button action
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
Toast.makeText(getContext(), "Button clicked for item " + position, Toast.LENGTH_LONG).show();
}
});
return playlistItemView;
}
}
Song.java
public class Song {
private String songAlbumTitle;
private String songTitle;
private String songSingers;
private int songAlbumCoverId;
public Song(String albumTitle, String title, String singers, int albumCoverId) {
songAlbumTitle = albumTitle;
songTitle = title;
songSingers = singers;
songAlbumCoverId = albumCoverId;
}
public String getSongAlbumTitle() {
return songAlbumTitle;
}
public String getSongTitle() {
return songTitle;
}
public String getSongSingers() {
return songSingers;
}
public int getSongAlbumCoverId() {
return songAlbumCoverId;
}
}
Activity.java
public class DreamVoyage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dream_voyage);
// get view ids
ImageView albumCoverImage = findViewById(R.id.album_cover);
// get intent extras
Bundle bundle = getIntent().getExtras();
// check if bundle in not null and containing value
if (bundle != null) {
String albumTitle = bundle.getString("album_one_title");
String albumBand = bundle.getString("album_one_band");
int albumCover = bundle.getInt("album_one_cover");
albumCoverImage.setImageResource(albumCover);
TextView albumTitleText = findViewById(R.id.album_title);
TextView albumBandText = findViewById(R.id.album_band);
albumTitleText.setText(albumTitle);
albumBandText.setText(albumBand);
ArrayList<Song> songs = new ArrayList<Song>();
songs.add(new Song(albumTitle, "I do it for you", "Bryn Adams", albumCover));
songs.add(new Song(albumTitle, "Here I am", "Bryn Adams", albumCover));
SongAdapter songAdapter = new SongAdapter(this, 0, songs);
ListView listView = findViewById(R.id.playlist_view);
listView.setAdapter(songAdapter);
}
}
}
playlist_item.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#drawable/border_bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/playlist_album_thumbnail"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="#drawable/album_three"
android:scaleType="centerCrop"
android:contentDescription="#string/album_thumbnail_desc"/>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/playlist_song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mon voyage de rĂªve"
android:layout_marginLeft="8dp"
android:textColor="#000000"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="#+id/playlist_song_album_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dream Voyage"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toStartOf="#id/playlist_song_title"/>
<TextView
android:id="#+id/playlist_song_credit_separator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_album_title"/>
<TextView
android:id="#+id/playlist_song_artist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - John Doen, Jane Doe"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_credit_separator"/>
</android.support.constraint.ConstraintLayout>
<ImageButton
android:id="#+id/playlist_play_button"
android:layout_width="24dp"
android:layout_height="24dp"
android:padding="0dp"
android:layout_gravity="center_vertical"
android:background="#00FFFFFF"
android:src="#drawable/ic_play_arrow_black_24dp"
android:scaleType="centerCrop"/>
</LinearLayout>
Use a variable to store current playing items index
SongAdapter {
int playingIndex = -1 //-1 means no song is playing
.
.
.
}
Set play/pause drawable based on playingIndex and set the playingIndex in the songPlayButton.setOnClickListener
public View getView(final int position, ...) {
if(playingIndex == position)
songPlayButton.setImageResource(R.drawable.ic_play_black_24dp);
else
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == playIndex)
playIndex = -1;
else
playIndex = position;
notifyDataSetChanged();
}
});
}
It should get the job done. But it forces a redraw of all rows. In RecyclerView there is the notifyItemChanged method which can force redraw on single item.
You may try using the method here to update single row https://stackoverflow.com/a/3727813/4907678
My suggestion is migrating to RecyclerView and using notifyItemChanged.
cheers!
This is my code:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
View vie = (View)parent.getParent();
TextView tv = (TextView) vie.findViewById(R.id.tv_id);
String genus = (String) tv.getText();
Toast.makeText(getBaseContext(), genus+"--"+id, Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
Every time it is returning the same value for every item. Here are my list items:
<?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" >
<TextView
android:id="#+id/tv_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textStyle="bold" />
<ImageView
android:id="#+id/iv_flag"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_below="#id/tv_country"
android:layout_centerVertical="true"
android:padding="5dp"
/>
<TextView
android:id="#+id/tv_country_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iv_flag"
android:layout_below="#id/tv_country" />
<TextView
android:id="#+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_country_details"
/>
</RelativeLayout>
Here is my view file.
<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" >
<ListView
android:id="#+id/lv_countries"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".NearbyGymList" />
<Button android:id="#+id/btnNoResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lv_countries"
android:text="No More Results"/>
</RelativeLayout>
How can fix this problem?
Remove this line:
View vie = (View)parent.getParent();
And change to use view from parameter, because it is the view of item which is clicked:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//Remove this line: View vie = (View)parent.getParent();
//Use view because it is the view of item which is clicked.
TextView tv1 = (TextView) view.findViewById(R.id.tv_id);
//Add this
TextView tv2 = (TextView) view.findViewById(R.id.tv_country_details);
String genus = (String) tv1.getText().toString();
String genus2 = (String) tv2.getText().toString();
Toast.makeText(getBaseContext(),genus+"--"+id+" "+genus2 , Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
You're not adding a reference to your others TextViews. Do it this way:
Remove this line
View vie = (View)parent.getParent();
so your code will become:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView tv1 = (TextView) view.findViewById(R.id.tv_id);
TextView tv2 = (TextView) view.findViewById(R.id.tv_country_details);
String genus = (String) tv1.getText().toString();
String genus2 = (String) tv2.getText().toString();
Toast.makeText(getBaseContext(),genus+"--"+id+" "+genus2 , Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
To access the element in the dataset at position you can use
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Object object = parent.getItemAtPosition(position);
and cast it to the correct type.
In Adapter Class
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.yourlayout, parent, false);
TextView textView = (TextView) row.findViewById(R.id.textView);
textView .setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Do whatever you want
});
I have a custom list adapter that populates a listview.
I am trying to get each item in the listview to be clickable. When clicked, I want the app to load another activity and populate it with the proper data. The data comes from a java list of listing.java.
I can't seem to get it to respond to clicks, here is what I've tried so far:
//this is in the onCreate method
final ListView listview = (ListView) findViewById(R.id.listview);
listingsAdapter = new ListingsAdapter(this, mylistings);
listview.setAdapter(listingsAdapter);
here is my first attempt (this was just to get toast working, but it didn't work)
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG).show();
};
});
I have also tried this:
listview.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(HomeScreenActivity.this, DetailedViewActivity.class);
startActivity(i);
};
});
Help would be appreciated. Let me know if I should post my adapter as well!
Here is the adaptor:
public class ListingsAdapter extends BaseAdapter{
List<Listing> listings;
Context context;
LayoutInflater inflater;
public ListingsAdapter(Context context, List<Listing> listings){
this.context = context;
this.listings = listings;
inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public boolean isEnabled(int position)
{
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View _localView = convertView;
if (_localView == null){
_localView = inflater.inflate(R.layout.main_cell, parent, false);
}
TextView text1 = (TextView) _localView.findViewById(R.id.firstline);
TextView text2 = (TextView) _localView.findViewById(R.id.secondLine);;
Listing listing = listings.get(position);
text1.setText(listing.getTitle());
text2.setText(listing.getAddress());
return _localView;
}
#Override
public int getCount(){
// TODO Auto-generated method stub
return listings.size();
}
#Override
public Object getItem(int arg0){
return listings.get(arg0);
}
#Override
public long getItemId(int arg0){
// TODO Auto-generated method stub
return arg0;
}
}
this is the main_cell.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
<TextView
android:id="#+id/firstline"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp"/>
</RelativeLayout>
Right, so I am recovering from a severe hangover and I just remembered that I promised to elaborate on the link I posted - disregard the link!
You should add the following piece of code to your ListingsAdapter:
#Override
public boolean isEnabled(int position)
{
return true;
}
And you should edit the RelativeLayout in your main_cell.xml from
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43"
android:longClickable="true">
to
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43">
This works, I have tested it.
try to initialize local instance of View:
#Override
public View getView(int position, View convertView, ViewGroup parent){
View _localView = convertView;
if (_localView == null){
_localView = inflater.inflate(R.layout.main_cell, parent, false);
}
TextView text1 = (TextView) _localView.findViewById(R.id.firstline);
TextView text2 = (TextView) _localView.findViewById(R.id.secondLine);;
Listing listing = listings.get(position);
text1.setText(listing.getTitle());
text2.setText(listing.getAddress());
return _localView;
}
UPD:
Also modify other necessary methods in your adapter class, because you need to get id of an item clicked for using it in onItemClick method:
#Override
public Object getItem(int arg0){
// TODO Auto-generated method stub
listings.get(arg0);
}
#Override
public long getItemId(int arg0){
// TODO Auto-generated method stub
return arg0;
}
as an example. Hope this will help you.
I am getting a NullPointer Exception in custom ListView Adapter android application.
This is my custom class with a few variables and getter.
public class ViewClass {
String ItemName, Category, Amount, TotalAmount;
//get,set methods here
}
This is my Main Activity class.
public class ViewList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<ViewClass> details = new ArrayList<ViewClass>();
ViewClass[] v = new ViewClass[5];
for (int i = 0; i < 5; i++) {
v[i] = new ViewClass();
v[i].setItemName("Item Name");
v[i].setAmount("Rs 1111");
v[i].setCategory("cateGory");
v[i].setTotalAmount("aaaa");
details.add(v[i]);
}
ListView msgList = (ListView) findViewById(R.id.MessageList);
msgList.setAdapter(new CustomListAdapter(details, this));
// msgList.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> a, View v, int position,
// long id) {
//
// String s = (String) ((TextView) v.findViewById(R.id.From))
// .getText();
// Toast.makeText(ViewList.this, s, Toast.LENGTH_SHORT).show();
// }
// });
}
}
This is the XML file for ListItem Layout, the name is list_item_trans
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBGColor1"
android:layout_width="10dp"
android:layout_height="fill_parent"
android:background="#android:color/background_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
<TextView
android:id="#+id/tvItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvAmount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBGColor2"
android:layout_width="10dp"
android:layout_height="fill_parent"
android:background="#android:color/background_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
<TextView
android:id="#+id/tvCat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp" />
<TextView
android:id="#+id/tvTotalAmount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:textSize="12sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/space" />
</LinearLayout>
This is as the name suggests, the CustomListAdapter
public class CustomListAdapter extends BaseAdapter{
private ArrayList<ViewClass> _data;
Context _c;
CustomListAdapter(ArrayList<ViewClass> data, Context c) {
_data = data;
_c = c;
}
public int getCount() {
// TODO Auto-generated method stub
return _data.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return _data.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) _c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item_message, null);
}
TextView tvItemName = (TextView) v.findViewById(R.id.tvItem);
TextView tvCategory = (TextView) v.findViewById(R.id.tvCat);
TextView tvAmount = (TextView) v.findViewById(R.id.tvAmount);
TextView tvTotalAmount = (TextView) v.findViewById(R.id.tvTotalAmount);
ViewClass msg = _data.get(position);
tvItemName.setText(msg.ItemName);
tvCategory.setText("Subject: " + msg.Category);
tvAmount.setText(msg.Amount);
tvTotalAmount.setText(msg.TotalAmount);
return v;
}
}
I am getting the error on in the getView method of the CustomListAdapter
tvItemName.setText(msg.ItemName);
This is the XML file for ListItem Layout, the name is list_item_trans
So The xml layout name is list_item_trans.xml
v = vi.inflate(R.layout.list_item_message, null);
You are inflating list_item_message.xml but your layout name is list_item_trans.xml
Maybee the error is here ?
List item layout is list_item_trans, but you are inflating list_item_message.
Change this line:
v = vi.inflate(R.layout.list_item_message, null);
Into this:
v = vi.inflate(R.layout.list_item_trans, null);
NullPointer Exception in custom ListView Adapter is caused
because you are inflating list_item_message.xml instead of list_item_trans.xml and initializing textviews from list_item_trans.xml
so just change
v = vi.inflate(R.layout.list_item_message, null);
To this
v = vi.inflate(R.layout.list_item_trans, null);
Good afternoon everybody :)
I have a listview for adding goals (not important :p). the listview's child has some textviews and edittextboxes, where the user can fill in its information.
I have a Textwatcher which checks whether the text in one of the listview's childs has changed, so the data can be written to the class in the array off the listview + a global array (for passing data between activety's, but this is also not important).
Now my problem is, when I add an Item to the list, the text of all the previous existing items in edittext 'discription' changes to the text of newly added Item. For example when i have 1 Item in the listview that says 'test' and I add a new one to the list that says 'this is a new test' >> Both change to 'this is a new test'. I debugged the program a lot and noticed that in the end (after adding the new item), the program will go trough the textwatcher with 's' = 'this is a new test' and position = '0'. This probably causes the text of the first one to change.. But I don't understand why this is happening.
Can somebody help me?
this is my listview:
class listViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<Goals> list;
public listViewAdapter(final Context context, ArrayList<Goals> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void synchronise(){
geldclass.setGoals_list(this.list);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.goal_item, parent,
false);
}
Goals goal = (Goals) getItem(position);
final EditText txtdiscription = (EditText) convertView.findViewById(R.id.editDiscription);
txtdiscription.setText(goal.getDiscription());
txtdiscription.addTextChangedListener(new textWatcher(txtdiscription, position));
final EditText txtgoal = (EditText) convertView
.findViewById(R.id.editGoal);
txtgoal.addTextChangedListener(new textWatcher(txtgoal, position));
final EditText txtfrom = (EditText) convertView
.findViewById(R.id.editFrom);
txtfrom.addTextChangedListener(new textWatcher(txtfrom, position));
final EditText txtto = (EditText) convertView
.findViewById(R.id.editto);
txtto.addTextChangedListener(new textWatcher(txtto, position));
final CheckBox check_date = (CheckBox) convertView
.findViewById(R.id.check_enable_date);
check_date
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
});
return convertView;
}
private class textWatcher implements TextWatcher {
private View view;
private int position;
private textWatcher(View view, int position) {
this.view = view;
this.position = position;
}
#Override
public void afterTextChanged(Editable s) {
switch (view.getId()) {
case R.id.editDiscription:
list.get(position).setDiscription(s.toString());
synchronise();
break;
case R.id.editGoal:
list.get(position).setGoalvalue(Integer.parseInt(s.toString()));
synchronise();
break;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
}
this is my goal child item in xml:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textDiscription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/name"
android:textSize="15dp"
android:width="80dp" />
<EditText
android:id="#+id/editDiscription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions"
android:width="120dp" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textGoal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/goal"
android:textSize="15dp" />
<EditText
android:id="#+id/editGoal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions"
android:width="200dp" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/check_enable_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/from"
android:textSize="15dp" />
<EditText
android:id="#+id/editFrom"
android:enabled="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textfrom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/to"
android:textSize="15dp" />
<EditText
android:id="#+id/editto"
android:enabled="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10" >
</EditText>
</TableRow>
</TableLayout>
And here is where I add the Items (don't pay attention to 'geldclass'.. Its a global class where the global array is stored):
public void onClick(View v) {
Goals goal = new Goals("this is a new test");
geldclass.addGoals(goal);
goal_adapter = new listViewAdapter(GoalManager.this, geldclass.getGoals_list());
goal_list.setAdapter(goal_adapter);
}
public void onClick(View v) {
Goals goal = new Goals("this is a new test");
geldclass.addGoals(goal);
goal_adapter = new listViewAdapter(GoalManager.this, geldclass.getGoals_list());
goal_list.setAdapter(goal_adapter);
}
should be changed to
public void onClick(View v) {
Goals goal = new Goals("this is a new test");
geldclass.addGoals(goal);
goal_adapter.setNotifyDatasetChanges();
}
calling the setNotifyDatasetChanges() make the Adapter to refresh the listView with the new changed data in its list, i'm assuming that the geldclass.getGoals_list() is the same list that you initialized the Adapter before.