This may be a bit of a silly question, but I am having a bit of a hard time understanding how to reference a listview/adapter that I created. I started by creating a custom listview that will allow me to display list items that have both pictures and text in them. I found a lot of great tutorials online, so this part wasn't too bad. I then added two buttons at the bottom of the listview that I would like to use to manipulate data within the listview. Now I can figure out how to access the list when I am in the onItemClickListener for the list, because you can simply call parent.getItemAtPosition(position) in order to access it. I am not quite sure how to access this list within the onClick method for the button, since the parent/position are not passed as parameters. So I suppose my first question is...
How to properly access the listview/arrayadapter I created from within my button onClick method.
The other question that I have been struggling with is how to search for an item (row) in my listview by searching for the value of a specific element withing that row. For instance, in my code below, the rows I have created have five images, two text fields, and a boolean value. So how would I go about searching through my list to find the row that has the "address" of 555555, which corresponds to the Harley Davidson list entry.
I have included my code below. Thank you very much for the help.
HelmetList.java
public class HelmetList
{
public HelmetList (String name, String address, String img_hel, String img_rec, String img_bat,
String img_dsk, String img_str, Boolean selected)
{
super();
this.name = name;
this.address = address;
this.img_hel = img_hel;
this.img_rec = img_rec;
this.img_bat = img_bat;
this.img_dsk = img_dsk;
this.img_str = img_str;
this.selected = selected;
}
private String name;
private String address;
private String img_hel;
private String img_rec;
private String img_bat;
private String img_dsk;
private String img_str;
private Boolean selected;
public String getName ()
{
return name;
}
public void setName (String s_name)
{
this.name = s_name;
}
public String getAddress ()
{
return address;
}
public void setAddress (String s_address)
{
this.address = s_address;
}
public String getImgHel ()
{
return img_hel;
}
public void setImgHel (String s_img_hel)
{
this.img_hel = s_img_hel;
}
public String getImgRec ()
{
return img_rec;
}
public void setImgRec (String s_img_rec)
{
this.img_rec = s_img_rec;
}
public String getImgBat ()
{
return img_bat;
}
public void setImgBat (String s_img_bat)
{
this.img_bat = s_img_bat;
}
public String getImgDsk ()
{
return img_dsk;
}
public void setImgDsk (String s_img_dsk)
{
this.img_dsk = s_img_dsk;
}
public String getImgStr ()
{
return img_str;
}
public void setImgStr (String s_img_str)
{
this.img_str = s_img_str;
}
public Boolean getSelected ()
{
return selected;
}
public void setSelected (Boolean s_selected)
{
this.selected = s_selected;
}
}
HelmetListAdapter.java
public class HelmetListAdapter extends ArrayAdapter<HelmetList>
{
private int resource;
private LayoutInflater inflater;
private Context context;
public HelmetListAdapter (Context p_context, int p_resource, List<HelmetList> p_objects)
{
super (p_context, p_resource, p_objects);
resource = p_resource;
inflater = LayoutInflater.from (p_context);
context = p_context;
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
HelmetList Helmet = getItem (position);
TextView hname = (TextView) convertView.findViewById(R.id.h_name);
hname.setText(Helmet.getName ());
TextView haddress = (TextView) convertView.findViewById(R.id.h_address);
haddress.setText(Helmet.getAddress ());
ImageView himage = (ImageView) convertView.findViewById(R.id.h_image);
String uri = "drawable/" + Helmet.getImgHel();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
himage.setImageDrawable(image);
ImageView hrec = (ImageView) convertView.findViewById(R.id.h_rec);
uri = "drawable/" + Helmet.getImgRec();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hrec.setImageDrawable(image);
ImageView hlbat = (ImageView) convertView.findViewById(R.id.h_lb);
uri = "drawable/" + Helmet.getImgBat();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hlbat.setImageDrawable(image);
ImageView hldsk = (ImageView) convertView.findViewById(R.id.h_ld);
uri = "drawable/" + Helmet.getImgDsk();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hldsk.setImageDrawable(image);
ImageView hstr = (ImageView) convertView.findViewById(R.id.h_str);
uri = "drawable/" + Helmet.getImgStr();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hstr.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
public class MainActivity extends Activity
{
private ListView lvhelmets;
private HelmetListAdapter adhelmets;
private Context ctx;
List<Integer> selected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
List<HelmetList> helmetlist = new ArrayList<HelmetList>();
helmetlist.add(new HelmetList("Bell", "11111", "helmetpic0", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Shoei", "33333", "helmetpic1", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Harley Davidson", "55555", "helmetpic2", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Joe Rocket", "77777", "helmetpic3", "rec",
"bat", "mm", "str", Boolean.FALSE));
lvhelmets = (ListView) findViewById(R.id.Helmet_list);
lvhelmets.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
adhelmets = new HelmetListAdapter(ctx, R.layout.row_format, helmetlist);
lvhelmets.setAdapter (adhelmets);
Button price = (Button) findViewById(R.id.bPrice);
Button safety = (Button) findViewById(R.id.bSafety);
price.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(MainActivity.this, "price", Toast.LENGTH_SHORT).show();
}
});
safety.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(MainActivity.this, "safety", Toast.LENGTH_SHORT).show();
}
});
lvhelmets.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
HelmetList helmet = (HelmetList) parent.getItemAtPosition(position);
if (!helmet.getSelected())
{
view.setBackgroundColor(Color.LTGRAY);
helmet.setSelected(Boolean.TRUE);
}
else
{
view.setBackgroundColor(Color.TRANSPARENT);
helmet.setSelected(Boolean.FALSE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_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/Helmet_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp"
android:choiceMode="multipleChoice"
android:layout_weight="1">
</ListView>
<LinearLayout
android:id="#+id/btnHolderLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/bPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Price"
android:clickable="true" />
<Button
android:id="#+id/bSafety"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Safety"
android:clickable="true" />
</LinearLayout>
</LinearLayout>
row_format.xml
<?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="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/h_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_marginLeft="5dip"/>
</LinearLayout>
<TextView
android:id="#+id/h_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#040404"
android:typeface="sans"
android:textSize="20dip"
android:layout_marginTop="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/h_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/h_name"
android:textColor="#343434"
android:textSize="12dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<ImageView
android:id="#+id/h_rec"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_lb"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="45dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_ld"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="85dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_str"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
In the onClick method, try:
lvhelmets.setAdapter(new HelmetListAdapter(ctx, rowf_format.xml, helmetList));
That will call your adapter which will populate the listview.
If the List of Integers is meant to hold the indexes of selected items, then in your ListViews onItemClicked listener, add the position to your List of Integers when one is selected.
Make your List of HelmetLists a field in your Activity. That way, when you press either of the two buttons, you have both the index (es) of the HelmetList you need, as well as the list you can retrieve each object from. Wasn't sure in your scenario if you were allowing multi-selection.
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!
Code
public class UsageSettings2 extends Fragment {
MainData mDatabaseHelper;
RecyclerView mRecyclerView;
UserDataHelper mHelper;
private List<UsageHelper> usage = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private UsageAdapter mAdapter;
SQLiteDatabase db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.settings_usage2, container, false);
final MainData myDBHlpr = new MainData(getActivity());
db = myDBHlpr.getWritableDatabase();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.usagelist);
//Add the data first
linearLayoutManager = new LinearLayoutManager(getActivity());
//and then create a object and pass the lis
mAdapter = new UsageAdapter(usage);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
Cursor csr = myDBHlpr.getAllQuestions2(getActivity());
while (csr.moveToNext()) {
String name = csr.getString(csr.getColumnIndex("Name"));
int sent = csr.getInt(csr.getColumnIndex("MessagesSent"));
int recieved = csr.getInt(csr.getColumnIndex("MessagesRecieved"));
int total = csr.getInt(csr.getColumnIndex("Messages"));
String time = csr.getString(csr.getColumnIndex("TimeSpent"));
new UsageHelper(name,sent,recieved,total,time);
int profile_counts = myDBHlpr.getProfilesCount2();
Log.d("FFF", String.valueOf(profile_counts));
}
return rootView;
}
}
Adapter
public class UsageAdapter extends RecyclerView.Adapter<UsageAdapter.UsageViewHolder>{
private List<UsageHelper> mUsageHelper;
public UsageAdapter(List<UsageHelper> UsageAdapter) {
this.mUsageHelper = UsageAdapter;
}
public class UsageViewHolder extends RecyclerView.ViewHolder{
public TextView mName;
public TextView mSent;
public TextView mRecieved;
public TextView mTotal;
public TextView mTime;
public UsageViewHolder(View view) {
super(view);
mName = (TextView)view.findViewById(R.id.name);
mSent = (TextView)view.findViewById(R.id.sent);
mRecieved = (TextView)view.findViewById(R.id.recieved);
mTotal = (TextView)view.findViewById(R.id.total);
mTime = (TextView)view.findViewById(R.id.time);
}
}
#Override
public UsageAdapter.UsageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_usage,parent,false);
return new UsageAdapter.UsageViewHolder(V);
}
#Override
public void onBindViewHolder(final UsageViewHolder holder, int position) {
final UsageHelper usageHelper = mUsageHelper.get(position);
holder.mName.setText(usageHelper.getName());
holder.mSent.setText(usageHelper.getSent());
holder.mRecieved.setText(usageHelper.getRecieved());
holder.mTotal.setText(usageHelper.getTotal());
holder.mTime.setText(usageHelper.getTime());
}
#Override
public int getItemCount() {
return mUsageHelper.size();
}
Modal
public class UsageHelper {
private String Name;
private int Sent;
private int Recieved;
private int Total;
private String Time;
public UsageHelper() {
}
public UsageHelper(String Name, int Sent ,int Recieved, int Total, String Time) {
this.Name = Name;
this.Sent = Sent;
this.Recieved = Recieved;
this.Total = Total;
this.Time = Time;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public int getSent() {
return Sent;
}
public void setSent(int sent) {
this.Sent = sent;
}
public int getRecieved() {
return Recieved;
}
public void setRecieved(int recieved) {
this.Recieved = recieved;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
this.Time = time;
}
public int getTotal() {
return Total;
}
public void setTotal(int total) {
this.Total = total;
}
}
The problem is that its not showing anything... the fragment is blank when i open it although the data is present... Any idea why its now showing any data? Im not getting any error just that the data isnt showing..........................................................................
Got an error after making changes according to answers
Custom
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/usage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black">
<RelativeLayout
android:weightSum="1"
android:id="#+id/linear"
android:padding="1dp"
android:background="#color/white"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15dp"
android:layout_toLeftOf="#+id/mid"
android:text="Name"
android:layout_alignParentStart="true"
android:id="#+id/name"
android:paddingVertical="10dp"
android:background="#color/black"
android:gravity="center_horizontal"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sent"
android:layout_toRightOf="#id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Sent"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/recieved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/sent"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Recieved"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/recieved"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Total"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/recieved"
android:background="#color/black"
android:gravity="center_horizontal"
android:paddingVertical="10dp"
android:text="Time \nSpent"
android:textColor="#color/white"
android:textSize="15dp" />
</RelativeLayout>
The usage list is always empty because you are not adding the new "UsageHelper" you are creating from your Cursor into the list.
What you need to do is the following:
Cursor csr = myDBHlpr.getAllQuestions2(getActivity());
while (csr.moveToNext()) {
...
UsageHelper newListItem = new UsageHelper(name,sent,recieved,total,time);
usage.add(newListItem);
...
}
mAdapter.notifyDataSetChanged();
When you finish adding elements to the list, you want to notify your adapter that the list has new items, so you have to call to mAdapter.notifyDataSetChanged(); and the new elements will be displayed
add mAdapter.notifyDataSetChanged(); in while condition or after adding your data in model class.
In the while loop of onCreateView(), add each row from the db to the list:
usage.add(new UsageHelper(name,sent,recieved,total,time));
instead of just:
new UsageHelper(name,sent,recieved,total,time)
which does nothing.
And after the loop finishes:
mAdapter.notifyDataSetChanged();
so the RecyclerView loads all the added rows to the list.
Edit
Replace
holder.mSent.setText(usageHelper.getSent());
with
holder.mSent.setText("" + usageHelper.getSent());
because usageHelper.getSent() is int and it is treated as a resource id.
I am trying to make a to-do list using an EditText and a ListView. How can I change the text font, color and size? I have seen a couple answers using array adapters, but don't know how to apply them to dynamically created ListView items.
Here is what I have so far:
ActivityMain.xml
<RelativeLayout
android:id="#+id/AgendaRL"
android:orientation="vertical"
android:background="#3E2723"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/agenda"
android:layout_width="370sp"
android:layout_height="wrap_content"
android:text="#string/agenda"
android:textSize="40sp"
android:textColor="#b7950b"
android:layout_marginTop="12sp"
android:layout_marginLeft="12sp"
android:layout_marginStart="12sp"
android:layout_marginBottom="0sp" />
<View
android:background="#b7950b"
android:layout_below="#+id/agenda"
android:layout_width="28sp"
android:layout_height="36sp"/>
<EditText
android:id="#+id/aTask"
android:layout_below="#+id/agenda"
android:background="#drawable/ribbon"
android:inputType="text"
android:text="#string/Add_Task"
android:textColor="#3E2723"
android:maxLength="22"
android:maxLines="1"
android:layout_width="330sp"
android:layout_height="36sp"
android:textSize="28sp"
android:layout_marginLeft="28sp"
android:layout_marginStart="28sp"/>
<Button
android:id="#+id/Done"
style="?android:attr/borderlessButtonStyle"
android:layout_marginLeft="250sp"
android:layout_marginStart="250sp"
android:background="#b7950b"
android:text="#string/Done"
android:textColor="#3E2723"
android:textSize="18sp"
android:layout_below="#+id/agenda"
android:layout_width="48sp"
android:layout_height="36sp"
android:onClick="DoneClick"/>
<ListView
android:id="#+id/LVAgenda"
android:layout_below="#+id/aTask"
android:divider="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
MainActivity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView LVAgenda = (ListView) findViewById(R.id.LVAgenda);
arrayListAgenda = new ArrayList<String>();
arrayAdapterAgenda = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListAgenda);
LVAgenda.setAdapter(arrayAdapterAgenda);
}
public void DoneClick(View v){
EditText aTask = (EditText)findViewById(R.id.aTask);
String agenda = aTask.getText().toString().trim();
if(agenda.isEmpty()){
return;
}
arrayAdapterAgenda.add(agenda);
aTask.setText("Add task");
}
As commonsware said you can use getView() of ArrayAdapter to do this.
I have implemented Facebook friend selector with ListAdapter. I will share the code. May be it helps. Please try.
First make a XML file in layout that defines the layout of each item of your 'to do list'.
In my case it is a facebook profile image and a checked textbox. (There is also a spacer for alignment)
Facebook.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="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingLeft="10dp"/>
<CheckedTextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:textColor="#android:color/black"
android:textStyle="bold" />
</LinearLayout>
<View
android:id="#+id/spacer"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/white"/>
</LinearLayout>
Now prepare your data array. In my case it is custom class array where each element contains a facebook name, profilepic, and a boolean.
public class Item{
public final String text;
public final Drawable icon;
public boolean isChecked;
public Item(String text, Drawable icon, boolean ischeck) {
this.text = text;
this.icon = icon;
this.isChecked = ischeck;
}
#Override
public String toString() {
return text;
}
}
I call the below code by passing friendsArray from another activity.
final Item[] items = new Item[friendsArray.length];
try {
int a = 1;
for (int i = 0; i < friendsArray.length; i++) {
tsk = new DownloadImageTask();
Bitmap bmp = (Bitmap) tsk.execute(new RaceActivity.FriendInfo[]{friendsArray[i]}).get();
Resources res = getActivity().getResources();
drawable = new BitmapDrawable(res, bmp);
items[i] = new Item(friendsArray[i].name, drawable,false);
}
}
catch(Exception ex)
{
}
Now your data array is prepared. You can pass this to ListAdapter(items in my case).
Its nice to understand the working of a List adapter. I created a scrollable List. What this logic does is it reuses the Views while scrolling.
ListAdapter adapter = new ArrayAdapter<Item>(
getActivity(),
android.R.layout.select_dialog_item,
android.R.id.text1,
items){
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
FaceBookHolder fb = new FaceBookHolder();
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.facebook,null);
fb.Name = (CheckedTextView) v.findViewById(R.id.name);
fb.img = (ImageView) v.findViewById(R.id.img);
fb.spacer = (View) v.findViewById(R.id.spacer);
fb.Name.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CheckedTextView cv = (CheckedTextView)v;
if(cv.isChecked())
cv.setChecked(false);
else
cv.setChecked(true);
for(int i =0;i< items.length; i++)
{
if(items[i].text == cv.getText())
{
items[i].isChecked = cv.isChecked();
}
}
}
});
v.setTag(fb);
}
else
fb = (FaceBookHolder) v.getTag();
Item itm = items[position];
fb.Name.setText(itm.text);
fb.img.setImageDrawable(itm.icon);
fb.Name.setChecked(itm.isChecked);
return v;
}
};
you get the view in getView(), so you can modify it however you want.(change color , font etc)
Hope it helps! cheers!
I have a listview with multiple row layouts (radio group, edit text, text view), with multiple choice mode. I want to retrieve it's selected data (user-selected or typed data) on a submit button.
This is the code from my main file:
public class GraduatingSurvey extends Fragment {
private static final String LOGTAG = "log" ;
public String stdcode = "024-15-16079";
Button submit;
RadioGroup radioGroup;
RadioButton radioButton;
EditText comment;
ArrayList<GraduatingSurveyModel> graduatingModelList;
ListView listView;
View view;
public GraduatingSurvey() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_graduating_survey, container, false);
submit = (Button) view.findViewById(R.id.btn_graduate_submit);
listView = (ListView) view.findViewById(R.id.graduate_list);
graduatingModelList = new ArrayList<GraduatingSurveyModel>();
//handle submit form Event.
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int child=listView.getAdapter().getCount();
Log.i("radio", "child: " + child);
SparseBooleanArray checked = listView.getCheckedItemPositions(); //Is returning empty
Log.i("radio", "sparseArray: " + checked);
for(int i=0;i<child;i++) {
int type = listView.getAdapter().getItemViewType(i);
Log.i("radio", "type: " + type);
if(type == 2){
// Want to retrieve data here
}
if(type == 0)
{
}
if(type == 1){
}
}
}
});
NetAsync(view);
return view;
}
This is the adapter:
public class GraduatingSurveyAdapter extends ArrayAdapter<GraduatingSurveyModel> {
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2;
int type;
ArrayList<GraduatingSurveyModel> ArrayListSurvey;
int Resource;
Context context;
LayoutInflater vi;
public GraduatingSurveyAdapter(Context context, int resource, ArrayList<GraduatingSurveyModel> objects) {
super(context, resource, objects);
ArrayListSurvey = objects;
Resource = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (position == 14){
type = TYPE_ITEM1;
} else if (position == 23 || position == 24 || position == 25){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type;
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
//first Item or row is being created hence ConvertView is NULL
if(convertView == null){
if (type == TYPE_ITEM2) {
convertView = vi.inflate(R.layout.graduates_survey_comment,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
holder.tv_comment = (TextView) convertView.findViewById(R.id.graduate_comment);
}
else if (type == TYPE_ITEM1) {
convertView = vi.inflate(R.layout.graduates_survey_subheader,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
}
else {
//infalte layout of normaltype
//Inflating items only once
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
holder.tv_comment = (TextView) convertView.findViewById(R.id.graduate_comment);
holder.rg = (RadioGroup) convertView.findViewById(R.id.graduate_radioGroup);
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
/* RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
Log.i("radio", "onCheckedChanged: " + radioButton + " " + checkedId);
notifyDataSetChanged();*/
Integer pos = (Integer) group.getTag();
GraduatingSurveyModel element = ArrayListSurvey.get(pos);
switch (checkedId) {
case R.id.graduate_sAgree:
element.current = GraduatingSurveyModel.ANSWER_ONE_SELECTED;
break;
case R.id.graduate_agree:
element.current = GraduatingSurveyModel.ANSWER_TWO_SELECTED;
break;
case R.id.graduate_uncertain:
element.current = GraduatingSurveyModel.ANSWER_THREE_SELECTED;
break;
case R.id.graduate_disagree:
element.current = GraduatingSurveyModel.ANSWER_FOUR_SELECTED;
break;
case R.id.graduate_sDisagree:
element.current = GraduatingSurveyModel.ANSWER_FIVE_SELECTED;
break;
default:
element.current = GraduatingSurveyModel.NONE; // Something was
}
}
});
}
convertView.setTag(holder);
}else{
//reuse code. (Inflate items only once then reuse them.)
holder = (ViewHolder) convertView.getTag();
}
// get info from ArrayList(that came through JSON), and set it in the View.
if (type == TYPE_ITEM1) {
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
}
else if (type == TYPE_ITEM2) {
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
}
else{
holder.rg.setTag(new Integer(position));
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
if(ArrayListSurvey.get(position).current != GraduatingSurveyModel.NONE){
RadioButton r = (RadioButton) holder.rg.getChildAt(ArrayListSurvey.get(position).current);
r.setChecked(true);
}else{
holder.rg.clearCheck();
}
}
return convertView;
}
static class ViewHolder{
private TextView tv_question;
private TextView tv_comment;
private LinearLayout lv_choices;
private RadioGroup rg;
}
}
This is my model:
public class GraduatingSurveyModel {
public String question;
public String comment;
public String choices;
public String subHeading;
public int current = NONE; // hold the answer picked by the user, initial is NONE(see below)
public static final int NONE = 1000; // No answer selected
public static final int ANSWER_ONE_SELECTED = 0; // first answer selected
public static final int ANSWER_TWO_SELECTED = 1; // second answer selected
public static final int ANSWER_THREE_SELECTED = 2; // third answer selected
public static final int ANSWER_FOUR_SELECTED = 3; // forth answer selected
public static final int ANSWER_FIVE_SELECTED = 4; // forth answer selected
public GraduatingSurveyModel() {
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getChoices() {
return choices;
}
public void setChoices(String choices) {
this.choices = choices;
}
public String getSubHeading() {
return subHeading;
}
public void setSubHeading(String subHeading) {
this.subHeading = subHeading;
}
}
And this is the XML layout of the main fragment:
<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:padding="16dp"
android:background="#color/dialog_background"
android:orientation="vertical"
tools:context="iulms.iunc.edu.pk.iqraiulms.GraduatingSurvey"
android:id="#+id/main_layout">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/graduate_list"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btn_graduate_submit"
/>
<Button
android:id="#+id/btn_graduate_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
These are the layouts for the different types of rows in listview
Row type 1:
<?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/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="13dp" />
<!-- <EditText
android:id="#+id/graduate_comment"
style="#style/GraduateTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/textbox"
android:ems="10"
android:hint="Comment"
android:inputType="textMultiLine"
android:lines="3" />-->
<LinearLayout
android:id="#+id/graduate_choices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/graduate_radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/graduate_sAgree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Strongly Agree" />
<RadioButton
android:id="#+id/graduate_agree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Agree" />
<RadioButton
android:id="#+id/graduate_uncertain"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Uncertain"
/>
<RadioButton
android:id="#+id/graduate_disagree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Disagree" />
<RadioButton
android:id="#+id/graduate_sDisagree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Strongly Disagree" />
</RadioGroup>
</LinearLayout>
</LinearLayout>
Row type 2
<?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/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="13dp" />
<EditText
android:id="#+id/graduate_comment"
style="#style/GraduateTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/textbox"
android:ems="10"
android:hint="Comment"
android:inputType="textMultiLine"
android:lines="3" />
</LinearLayout>
Row type 3:
<?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/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="15dp"
android:textColor="#color/primary_dark"/>
</LinearLayout>
How can I retrieve the data submitted in the main fragment?
Thanks
For this You can create a custom class with row values like,
Arraylist<CustomClass> mnewList = new ArrayList();
Class CustomClass
{
private String edValues,
private int rowId,
}
etc.
Then Implement on change listener for radio button in that add/remove current selected items to that custom list.
Im not sure how to return values from my listview which includes checkboxes. Im fairly new to Android and ArrayAdapters in general so please bear with me.
Here is my list adapter, having two text views and a checkbox
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:checked="false"
android:layout_alignBottom="#+id/NumberView"
android:layout_alignParentTop="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/NameView"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingRight="20dp"
android:textSize="28sp"
android:textIsSelectable="true"
android:layout_marginTop="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/NumberView"
android:layout_below="#+id/NameView"
android:paddingRight="20dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="5dp" />
</RelativeLayout>
A button on activity_mail calls this:
public void grabthecontacts(View view) {
setContentView(R.layout.selectcontacts);
populateListView(view);
}
Now im not sure what do to after this next function, this is what creates and populates the list, but how do I get the results?
Here is my populatelistview function, which pulls all the persons contacts and then puts it into an adapter
public void populateListView(View view) {
try {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(new Person(name, phoneNumber));
}
phones.close();
}
catch (Exception e){
e.printStackTrace();
}
ArrayAdapter<Person> adapter = new myListAdapter();
ListView listview2 = (ListView) findViewById(R.id.contactlistview);
listview2.setAdapter(adapter);
}
public class myListAdapter extends ArrayAdapter<Person> {
public myListAdapter() {
super(MainActivity.this, R.layout.da_item, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.da_item, parent, false);
}
// Find person wot work with
Person currentperson = list.get(position);
// Fill the view
TextView nameboxview = (TextView)itemView.findViewById(R.id.NameView);
nameboxview.setText(currentperson.getName());
TextView numberboxview = (TextView)itemView.findViewById(R.id.NumberView);
numberboxview.setText(currentperson.getPhone());
return itemView;
}
}
Make your own Person class which will have a boolean instance variable which will tell if the particular item has been selected or not.
/**
* Created by Pankaj Nimgade on 19-12-2015.
*/
public class Person {
private boolean isChecked;
private String phoneNumber;
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Make a ArrayList of this class type and populate your ListView.
make little change in your Adapter... add following code which will keep track of what items were selected.
CheckBox checkBox = (CheckBox)itemView.findViewById(R.id.checkBox);
if (checkBox.isChecked()) {
person.setChecked(true);
}
after your listview is populated
ArrayList<Person> searchList = searchList(list);
following is the code to look for the items which was checked.
private ArrayList<Person> searchList(ArrayList<Person> list) {
ArrayList<Person> tempList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).isChecked()) {
tempList.add(list.get(i));
}
}
return list;
}