Passing String array to another Activity with Custom View - java

I'm having an issue passing an array into a listview
I can pass an image to the second activty but when I
try to pass an array to the listview I get a lang.NullPointerException error
and the app crashes.
any helpful input would be great Thanks
here is the code
Main Activity
package com.example.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView;
// Defined the text values to show in ListView
String[] values = new String[]{"Barack Obama","Donald Trump","Bill Clinton",
"Hillary Clinton","Joe Biden"};
// Defined the image ids to show in ListView
Integer[] images = {
R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,
R.drawable.image5
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the custom view
CustomView adapter = new CustomView(MainActivity.this, values, images);
// Get ListView object from xml
listView = (ListView) findViewById(R.id.container);
//set adapter
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(position == 0){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[]{"Barack Obama","The White House","1-234-567-8900",
"Barack.Obama#whitehouse.com","note"};
Integer image = images[0];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 1){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[] {"Donald Trump","Trump Tower","1-234-567-8901",
"Donald.Trump#whitehouse.com","note"};
Integer image = images[1];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 2){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details = new String[] {"Bill Clinton","New York","1-234-567-8902",
"Bill.Clinton#whitehouse.com","note"};
Integer image = images[2];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 3){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details = new String[] {"Hillary Clinton","New Jersey","1-234-567-8903",
"Hillary.Clinton#whitehouse.com","note"};
Integer image = images[3];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 4){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[] {"Joe Biden","OHIO","1-234-567-8903",
"Joe.Biden#whitehouse.com","note"};
Integer image = images[4];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
}
});
}
}
Second Activity I want to pass the array to
package com.example.androidlistview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends Activity {
ListView list;
String []web={"Name:","Address:","Phone Number:","Email:","Note:"};
int image;
String[] details;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// create the custom view
CustomList Adapter= new CustomList(Details.this, web, details);//, details should go here
// Get ListView object from xml
list=(ListView)findViewById(R.id.list);
//set adapter
list.setAdapter(Adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
image= bundle.getInt("image");
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(image);
}
}
}
and the custom view i'm using for the Second Activity details
package com.example.androidlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String>{
private final Activity mContext;
private final String[] web;
private final String[] details;
public CustomList(Activity mContext,String[] web, String[] details){ //, String[] details should go here
super(mContext, R.layout.list_single, web);
this.mContext=mContext;
this.web=web;
this.details=details;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = mContext.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText(web[position]);
TextView txtTitle1 = (TextView)rowView.findViewById(R.id.txt1);
txtTitle1.setText(details[position]);
return rowView;
}
}

This is what i did to fix this
Main Activity
package com.example.androidcontacts;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ListActivity {
ListView mylist;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri allContacts = Uri.parse("content://"+"com.example.androidcontacts.Books" + "/Contact");
Cursor c;
CursorLoader cursorLoader = new CursorLoader(
this,allContacts,null,null,null,null);
c = cursorLoader.loadInBackground();
String[] columns = new String[] {Contact._ID,Contact.TITLE,Contact.AUTHOR,Contact.YEAR,Contact.IMAGE};
int[] views = new int[] {R.id.contactID,R.id.contactName,R.id.contactAuthor,R.id.contactYear,R.id.Image};
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(this, R.layout.activity_main,
c, columns, views,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
//Intent i=new Intent(MainActivity.this,Details.class);
//startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_search){
Intent intent = new Intent(this, Search.class);
startActivity(intent);
finish();
return true;
}
if(id == R.id.action_add){
Intent intent = new Intent(this, Add.class);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Second activity Details
package com.example.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends Activity {
//Variables for Bundle
int image;
String name;
String address;
String phone;
String email;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Button SMS = (Button) findViewById(R.id.button1);
SMS.setOnClickListener(new OnClickListener() {
//when button1 is clicked open messenger
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phone, null)));
}
});
Button Email = (Button) findViewById(R.id.button2);
Email.setOnClickListener(new OnClickListener() {
//when button2 is clicked open email
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
startActivity(Intent.createChooser(emailIntent, "Choose Email Client"));
}
});
Button Phone = (Button) findViewById(R.id.button3);
Phone.setOnClickListener(new OnClickListener() {
//when button3 is clicked start call
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null)));
}
});
// get details passed from MainActivity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
image= bundle.getInt("image");
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(image);
name = bundle.getString("name");
TextView nameView = (TextView) findViewById(R.id.name1);
nameView.setText(name);
address = bundle.getString("address");
TextView addressView = (TextView) findViewById(R.id.address1);
addressView.setText(address);
phone = bundle.getString("phone");
TextView phoneView = (TextView) findViewById(R.id.phone1);
phoneView.setText(phone);
email = bundle.getString("email");
TextView emailView = (TextView) findViewById(R.id.email1);
emailView.setText(email);
note = bundle.getString("note");
TextView noteView = (TextView) findViewById(R.id.note1);
noteView.setText(note);
}
}
}
My Custom View
package com.example.androidlistview;
import android.app.Activity;
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 CustomView extends ArrayAdapter<String>{
private final Activity context;
private final String[] values;
private final Integer[] images;
//Constructor
public CustomView(Activity context,String[] values, Integer[] images) {
super(context, R.layout.single_row, values);
this.context = context;
this.values = values;
this.images = images;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText(values[position]);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
imageView.setImageResource(images[position]);
return rowView;
}
}

Related

My Base Adapter, List<Song> songlist has a size of 0, instead of 14. It's preventing me from using my imgCoverArt onClick

I have been trying to create a ListView with the PlaylistsAdapter. But whenever I try to click on imgCoverArt, the app crashes, stating that the songlist has a size of 0. I have tried changing the types of the variables and just changing the codes overall. But I just couldn't fix it and I don't know the issue.
Thanks in advance.
This was the error I got:
2020-08-10 03:52:56.720 3091-3091/sg.edu.tp.musicstream E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.musicstream, PID: 3091
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at sg.edu.tp.musicstream.PlaylistsAdapter$1.onClick(PlaylistsAdapter.java:88)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I have tried to include the relevant classes and please let me know if you need anything else.
package sg.edu.tp.musicstream;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import sg.edu.tp.musicstream.util.AppUtil;
public class PlaylistsAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
public PlaylistsAdapter(Context context, List<Song> songlist, Song[] songs)
{
mContext = context;
inflater = LayoutInflater.from(mContext);
this.songs = songs;
this.songlist = songlist;
this.arrayList = new ArrayList<>();
this.arrayList.addAll(songlist);
}
public class ViewHolder
{
ImageButton imgCoverArt;
TextView txtSongTitle;
TextView txtArtist;
ImageButton btnAddToPlaylist;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.playlist_listview, null);
holder.imgCoverArt = convertView.findViewById(R.id.imgCoverArt);
holder.txtSongTitle = convertView.findViewById(R.id.txtSongTitle);
holder.txtArtist = convertView.findViewById(R.id.txtArtist);
holder.btnAddToPlaylist = convertView.findViewById(R.id.btnAddToPlaylist);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgCoverArt.setImageResource(songlist.get(position).getCoverArt());
holder.imgCoverArt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
{
if (songlist.get(position).getId().equals(songs[index].getId())) {
Song song = songs[index];
sendDataToActivity(songs, song);
AppUtil.popMessage(mContext, ""+ songlist.size());
}
}
}
});
holder.txtSongTitle.setText(songlist.get(position).getTitle());
holder.txtArtist.setText(songlist.get(position).getArtist());
if (position >= 10) {
holder.btnAddToPlaylist.setContentDescription("S10" + position);
} else {
holder.btnAddToPlaylist.setContentDescription("S100" + position);
}
return convertView;
}
public void sendDataToActivity(Song[] songs, Song song)
{
// 1. Create a new Intent and specify the source and destination screen/activity.
Intent intent = new Intent(mContext, PlaySongActivity.class);
songlist = HomeFragment.arrayList;
songlist = new ArrayList<>();
// 2. Store the song information into the Intent object to be sent over to the destination screen.
intent.putExtra("id", song.getId());
intent.putExtra("title", song.getTitle());
intent.putExtra("artist", song.getArtist());
intent.putExtra("fileLink", song.getFileLink());
intent.putExtra("coverArt", song.getCoverArt());
intent.putExtra("songs", songs);
intent.putExtra("songlist", (Serializable) songlist);
// 3. Launch the destination screen/activity
mContext.startActivity(intent);
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
songlist.clear();
if (charText.length()==0){
songlist.addAll(arrayList);
}
else {
for (Song song : arrayList){
if (song.getTitle().toLowerCase(Locale.getDefault())
.contains(charText) || song.getArtist().toLowerCase(Locale.getDefault())
.contains(charText)){
songlist.add(song);
}
}
}
notifyDataSetChanged();
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import sg.edu.tp.musicstream.ui.main.SectionsPagerAdapter;
import sg.edu.tp.musicstream.util.AppUtil;
public class HomeActivity extends AppCompatActivity {
private SectionsPagerAdapter sectionsPagerAdapter;
private SongCollection songCollection = new SongCollection();
static Song[] playlistSongs = new Song[14];
static ArrayList<Song> playlist = new ArrayList<>();
private Fragment homeFragment;
private Fragment playlistsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
homeFragment = new HomeFragment();
playlistsFragment = new PlaylistsFragment();
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(homeFragment, "Recommended Songs");
sectionsPagerAdapter.addFragment(playlistsFragment, "Playlist");
viewPager.setAdapter(sectionsPagerAdapter);
}
public void addToPlaylist (View view) {
String songId = view.getContentDescription().toString();
Song song = songCollection.searchById(SongCollection.recommendedSongs, songId);
playlist.add(song);
AppUtil.popMessage(this, "Added " + song.getTitle() + " to playlist!");
playlistSongs[playlist.size()] = song;
sectionsPagerAdapter.removeFragment(playlistsFragment, "Playlist");
sectionsPagerAdapter.addFragment(new PlaylistsFragment(), "Playlist");
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
public void removeAll(View view) {
playlist.clear();
PlaylistsFragment.songAdapter.notifyDataSetChanged();
}
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
private PlaylistsAdapter playlistsAdapter;
private ListView listView;
static ArrayList<Song> arrayList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container,false);
for (int index =0; index<SongCollection.recommendedSongs.length; index++) {
arrayList.add(SongCollection.recommendedSongs[index]);
}
listView = view.findViewById(R.id.listView);
playlistsAdapter = new PlaylistsAdapter(getActivity(), arrayList, SongCollection.recommendedSongs);
listView.setAdapter(playlistsAdapter);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView)myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)){
playlistsAdapter.filter("");
listView.clearTextFilter();
}
else {
playlistsAdapter.filter(s);
}
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.settings){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
if (id==R.id.logOut){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
package sg.edu.tp.musicstream;
import java.util.List;
import java.util.Random;
public class SongCollection
{
static Song[] recommendedSongs = new Song[14];
private Song[] playlist1 = new Song[5];
private Song[] playlist2 = new Song[5];
public SongCollection()
{
//Recommended Songs
Song photograph = new Song("S1000", "Photograph", "Ed Sheeran","097c7b735ceb410943cbd507a6e1dfda272fd8a8?cid=null",4.32, R.drawable.photograph);
Song theWayYouLookTonight = new Song("S1001", "The Way You Look Tonight", "Michael Buble","a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",4.39,R.drawable.michael_buble_collection);
Song billieJean = new Song("S1002", "Billie Jean", "Michael Jackson","f504e6b8e037771318656394f532dede4f9bcaea?cid=2afe87a64b0042dabf51f37318616965",4.39,R.drawable.billie_jean);
Song spark = new Song("S1003", "Spark", "TAEYEON","e857ae54599f2cca1703b598cef871664f36e72e?cid=2afe87a64b0042dabf51f37318616965", 3.63, R.drawable.spark);
Song darkside = new Song("S1004", "Darkside", "Alan Walker","2acc534ac733f8868c98e13e4f71917fae2e3ce3?cid=2afe87a64b0042dabf51f37318616965", 3.53, R.drawable.darkside);
Song diamondHeart = new Song("S1005", "Diamond Heart", "Alan Walker","d75c2b8e870acb087872bd49eeb5d6efb37cfc9d?cid=2afe87a64b0042dabf51f37318616965", 4.01, R.drawable.diamond_heart);
Song ocean= new Song("S1006", "Ocean (feat. Khalid)", "Martin Garrix","5ce5ed5600e96f1604aff6b05c0dc35319023a1c?cid=2afe87a64b0042dabf51f37318616965", 3.61, R.drawable.ocean);
Song numb = new Song("S1007", "Numb", "Linkin Park","e6ccf7717f8a167bfea4afc1bf7da1a0cd707fbb?cid=2afe87a64b0042dabf51f37318616965", 3.09, R.drawable.numb);
Song sadForever = new Song("S1008", "Sad Forever", "Lauv","1250fb3bea03aee6da908ea67420ddd954ad812a?cid=2afe87a64b0042dabf51f37318616965", 3.39, R.drawable.sad_forever);
Song kyokiranbu = new Song("S1009", "Kyokiranbu", "GARNiDELiA","ec373ab20f18e1a4a7b19b3abaac3ce605690abd?cid=2afe87a64b0042dabf51f37318616965", 4.32, R.drawable.kyokiranbu);
Song gokurakuJoudo= new Song("S1010", "Gokuraku Joudo", "GARNiDELiA","8924599ac778ebfbac7ddc2e5cc87961f82f736c?cid=2afe87a64b0042dabf51f37318616965", 3.65, R.drawable.gokuraku_joudo);
Song connect = new Song("S1011", "Connect", "ClariS","6692db454109aa077ed25e65df82a06d34017da6?cid=2afe87a64b0042dabf51f37318616965", 4.5, R.drawable.connect);
Song wannabe = new Song("S1012", "WANNABE", "ITZY", "2bae7f42bbae3cd75228d6400e37515b79467928?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.wannabe);
Song icy = new Song("S1013", "ICY", "ITZY", "118a0dea24f229f51ffff23a9d334cf5714dbaf6?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.icy);
recommendedSongs[0] = photograph;
recommendedSongs[1] = theWayYouLookTonight;
recommendedSongs[2] = billieJean;
recommendedSongs[3] = spark;
recommendedSongs[4] = darkside;
recommendedSongs[5] = diamondHeart;
recommendedSongs[6] = ocean;
recommendedSongs[7] = numb;
recommendedSongs[8] = sadForever;
recommendedSongs[9] = kyokiranbu;
recommendedSongs[10] = gokurakuJoudo;
recommendedSongs[11] = connect;
recommendedSongs[12] = wannabe;
recommendedSongs[13] = icy;
}
In your adapter, you have three different ways of storing the songs:
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
This is a problem. Pick one type, and use it everywhere.
The adapter is building its logic around the getCount() method:
#Override
public int getCount() {
return songlist.size();
}
Which uses songlist. But your onClick() method uses songs:
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
// ...
}
If you change this to use songlist instead, probably the issue will go away.

How do I access/alter views within a listview item from a different item in the same listview?

I have a small app that uses a ListView, each item having a play button, an open/close button, and an ImageView whose visibilty is set to View.GONE. When I press the open/close button, it should set the ImageView in that one list item to View.VISIBLE, change the open/close button, and close any other list items that are displaying the ImageView as VISIBLE and change their open/close button to reflect closed. This is my onClick in my custom ArrayAdapter.
boolean open = false;
imgOpen_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!open){
openClose.setImageResource(R.drawable.open_arrow);
mainImage.setVisibility(View.VISIBLE);
open = true;
}else{
openClose.setImageResource(R.drawable.close_arrow);
mainImage.setVisibility(View.VISIBLE);
open = false;
}
});
How do I access a View in one list item from another list item?
Entire Custom ArrayAdapter.
package net.androidbootcamp.mypersonalplaylist;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
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 MyListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] songs;
private final Integer[] imgID;
MediaPlayer mpKickStart, mpGirlsGirls, mpHomeSweetHome;
public MyListAdapter(Activity context, String[] songs, Integer[] imgID){
super(context, R.layout.list_view_custom, songs);
this.context=context;
this.songs=songs;
this.imgID=imgID;
}
public View getView(final int position, View view, ViewGroup parent){
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_view_custom, null, true);
TextView txtSongName = rowView.findViewById(R.id.txtSongName);
final ImageView imgCoverArt = rowView.findViewById(R.id.imgCoverArt);
final ImageView imgPlayButton = rowView.findViewById(R.id.imgPlayButton);
final ImageView imgOpen_Close = rowView.findViewById(R.id.imgOpen_Close);
txtSongName.setText(songs[position]);
imgCoverArt.setImageResource(imgID[position]);
mpKickStart = new MediaPlayer();
mpKickStart = MediaPlayer.create(context, R.raw.kickstartmyheart);
mpGirlsGirls = new MediaPlayer();
mpGirlsGirls = MediaPlayer.create(context, R.raw.girlsgirlsgirls);
mpHomeSweetHome = new MediaPlayer();
mpHomeSweetHome = MediaPlayer.create(context, R.raw.homesweethome);
imgPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position){
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
});
imgOpen_Close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("POSITION", "Position Clicked: " + position);
}
});
return rowView;
}
}
MainActivity
package net.androidbootcamp.mypersonalplaylist;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView list;
String[] songs = {"Name 1", "Name 2", "Name 3"};
Integer[] imgID = {R.drawable.kickstart_my_heart, R.drawable.girls_girls_girls, R.drawable.home_sweet_home};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyListAdapter adapter = new MyListAdapter(this, songs, imgID);
list = findViewById(R.id.listView);
list.setAdapter(adapter);
}
}

Open Activity and populate based off ListView selection

I'm trying to pass data from a custom listview to a new activity and populate its TextViews. It does work but it always takes the first position that was added and passes it through. How do I get it to pass the data clicked on?
MainActivity
package uk.co.jaunt_app.jaunt;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
import static uk.co.jaunt_app.jaunt.R.id.Posts;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton addmap;
private Button settingbtn;
private TextView mNameTextView;
private TextView mEmailTextView;
ListView mPosts;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ArrayAdapter<String> adapter;
private FirebaseAuth auth;
private ArrayList<feed> feedPop = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.jauntlogodark);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase(Config.FIREBASE_URL);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uid = currentFirebaseUser.getUid();
Firebase usersRef = ref.child("Users").child(uid).child("name");
Firebase emailRef = ref.child("Users").child(uid).child("email");
Firebase postRef = ref.child("Users").child(uid).child("Maps");
postRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (final DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
final String mapName = person.getMapName();
final String mapid = person.getMapID();
final String mapStartLat = person.getStartLat();
final String mapStartLong = person.getStartLong();
final String mapEndLat = person.getEndLat();
final String mapEndLong = person.getEndLong();
adapter.notifyDataSetChanged();
feedPop.add(
new feed(mapName, mapStartLat, mapStartLong, mapEndLat, mapEndLong));
final ArrayAdapter<feed> adapter = new feedArrayAdapter(MainActivity.this, 0, feedPop);
ListView listView = (ListView) findViewById(R.id.customListView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this, ViewUserMapActivity.class);
intent.putExtra("mapName", mapName.toString());
intent.putExtra("mapStartLat", mapStartLat.toString());
intent.putExtra("mapStartLong", mapStartLong.toString());
intent.putExtra("mapEndLat", mapEndLat.toString());
intent.putExtra("mapEndLong", mapEndLong.toString());
startActivity(intent);
}
});
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(),
"Cancelled", Toast.LENGTH_LONG)
.show();
}
});
//create property elements
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mPosts = (ListView) findViewById(Posts);
mPosts.setAdapter(adapter);
List<Nav> navList= new ArrayList<Nav>();
navList.add(new Nav("Profile"));
navList.add(new Nav("Feed"));
navList.add(new Nav("Maps"));
navList.add(new Nav("Most Popular"));
navList.add(new Nav("Settings"));
navList.add(new Nav("Report a Bug"));
ArrayAdapter<Nav> navadapter = new ArrayAdapter<Nav>(this,android.R.layout.simple_list_item_1, navList);
final ListView lv= (ListView) findViewById(R.id.left_drawer);
lv.setAdapter(navadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition = position;
switch(itemPosition) {
case 0:
Intent menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 1:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 2:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 3:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 4:
menuItem = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(menuItem);
break;
case 5:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
}
}
});
mNameTextView = (TextView) findViewById(R.id.NameTextView);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue(String.class);
mNameTextView.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mEmailTextView = (TextView) findViewById(R.id.EmailTextView);
emailRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
mEmailTextView.setText(email);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
addmap = (FloatingActionButton) findViewById(R.id.add_map);
addmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Answers.getInstance().logCustom(new CustomEvent("Added Map"));
Intent intent = new Intent(MainActivity.this, MapStartActivity.class);
startActivity(intent);
}
});
settingbtn = (Button) findViewById(R.id.settingbtn);
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu_drawer, menu);
return true;
}
}
//custom ArrayAdapter
class feedArrayAdapter extends ArrayAdapter<feed>{
private Context context;
private List<feed> feedPop;
//constructor, call on creation
public feedArrayAdapter(Context context, int resource, ArrayList<feed> objects) {
super(context, resource, objects);
this.context = context;
this.feedPop = objects;
}
//called when rendering the list
public View getView(int position, View convertView, ViewGroup parent) {
//get the property we are displaying
feed feed = feedPop.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.feed_listview, null);
TextView others = (TextView) view.findViewById(R.id.others);
TextView mapname = (TextView) view.findViewById(R.id.address);
//set address and description
String completeOthers = feed.getFeedStartLat() + ", " + feed.getFeedStartLong() + ", " + feed.getFeedEndLat() + ", " + feed.getFeedEndLong();
others.setText(completeOthers);
//set address and description
String completeAddress = feed.getFeedName();
mapname.setText(completeAddress);
return view;
}
}
Get value from ArrayList based on position then pass to activity
intent.putExtra("mapName", feedPop.get(position).getmapName().toString());

Getting error on start activity

Getting error on My array Adapter class .The error is on Startavtivity line i dont know why it is its working on other pahes but it shows error on this page .So could you please help me out
ERROR" The Constructor Intent(MyArrayAdapter,Class<Add_new_employee >undefined)
package com.example.employeemanager;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyArrayAdapter extends ArrayAdapter<Student> {
Context context;
int layoutResourceId;
ArrayList<Student> students = new ArrayList<Student>();
public MyArrayAdapter(Context context, int layoutResourceId,ArrayList<Student> studs)
{
super(context, layoutResourceId, studs);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.students = studs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View item = convertView;
StudentWrapper StudentWrapper = null;
if (item == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
item = inflater.inflate(layoutResourceId, parent, false);
StudentWrapper = new StudentWrapper();
StudentWrapper.name = (TextView) item.findViewById(R.id.textName);
StudentWrapper.age = (TextView) item.findViewById(R.id.textAge);
StudentWrapper.address = (TextView) item.findViewById(R.id.textAddr);
StudentWrapper.edit = (Button) item.findViewById(R.id.btnEdit);
StudentWrapper.delete = (Button) item.findViewById(R.id.btnDelete);
StudentWrapper.checkBox = (CheckBox) item.findViewById(R.id.checkBox1);
item.setTag(StudentWrapper);
}
else
{
StudentWrapper = (StudentWrapper) item.getTag();
}
Student student = students.get(position);
StudentWrapper.name.setText(student.getName());
StudentWrapper.age.setText(student.getAge());
StudentWrapper.address.setText(student.getAddress());
StudentWrapper.edit.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent
(MyArrayAdapter.this,Add_new_employee.class) );
}
});
StudentWrapper.delete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
StudentWrapper.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
Toast.makeText(context, "Checkox", Toast.LENGTH_LONG).show();
}
});
return item;
}
protected void startActivity(Intent intent) {
// TODO Auto-generated method stub
}
static class StudentWrapper
{
TextView name;
TextView age;
TextView address;
Button edit;
Button delete;
CheckBox checkBox;
}
}
Inseted of this
startActivity(new Intent
(MyArrayAdapter.this,Add_new_employee.class) );
use this
context.startActivity(new Intent
(context,Add_new_employee.class) );
Note: Make sure you had declared Add_new_employee in android manifest.xml
Try
startActivity(new Intent
(getBaseContext(),Add_new_employee.class) );

ArrayAdapter delete an item with a button

I am having a bit of a problem, i created an arrayadapter that works just fine, but when i click in the delete button, it deletes the item but the listview doesn´t change. I now i am missing a bit of code, but I don´t know what it is?
ListarSocio.java
package com.example.polideportivo1;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class ListarSocio extends Activity {
ListView listview;
ArrayAdapterSocio socioArrayAdapter;
ArrayList<Socios>socio = VariablesGlobales.getInstance().getSocios();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_socio_main);
socioArrayAdapter = new ArrayAdapterSocio(ListarSocio.this, R.layout.list_socio, socio);
listview = (ListView)findViewById(R.id.ListaMainSocio);
listview.setItemsCanFocus(false);
listview.setAdapter(socioArrayAdapter);
}
}
ArrayAdapterSocio.java
package com.example.polideportivo1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.datatype.Duration;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ArrayAdapterSocio extends ArrayAdapter<Socios>{
Context context;
int layoutResourceId;
ArrayList<Socios>socio = VariablesGlobales.getInstance().getSocios();
public ArrayAdapterSocio(Context context, int layoutResourceId, ArrayList<Socios> soc) {
super(context, layoutResourceId, soc);
this.context= context;
this.layoutResourceId = layoutResourceId;
this.socio = soc;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View item = convertView;
CapturadorSocio CapturadorSocio = null;
if (item == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
item = inflater.inflate(layoutResourceId, parent, false);
CapturadorSocio = new CapturadorSocio();
CapturadorSocio.nombre = (TextView) item.findViewById(R.id.textNombre);
CapturadorSocio.apellido = (TextView) item.findViewById(R.id.textApellido);
CapturadorSocio.documento = (TextView) item.findViewById(R.id.textCI);
CapturadorSocio.sexo = (TextView) item.findViewById(R.id.textSexo);
CapturadorSocio.estadoCivil = (TextView) item.findViewById(R.id.textEstadoCivil);
CapturadorSocio.nacionalidad = (TextView) item.findViewById(R.id.textNacionalidad);
CapturadorSocio.fechaNacimiento = (TextView) item.findViewById(R.id.textNacimiento);
CapturadorSocio.domicilio = (TextView) item.findViewById(R.id.textDomicilio);
CapturadorSocio.localidad = (TextView) item.findViewById(R.id.textLocalidad);
CapturadorSocio.telfijo = (TextView) item.findViewById(R.id.textTelFijo);
CapturadorSocio.telcelular = (TextView) item.findViewById(R.id.textTelCel);
CapturadorSocio.correo = (TextView) item.findViewById(R.id.textCorreo);
CapturadorSocio.edit = (Button) item.findViewById(R.id.btnEdit);
//CapturadorSocio.delete = (Button) item.findViewById(R.id.btnDelete);
item.setTag(CapturadorSocio);
} else {
CapturadorSocio = (CapturadorSocio) item.getTag();
}
Socios socios = socio.get(position);
CapturadorSocio.nombre.setText(socios.obtenerNombre());
CapturadorSocio.apellido.setText(socios.obtenerApellido());
CapturadorSocio.documento.setText(socios.obtenerCI());
CapturadorSocio.sexo.setText(socios.obtenerSexo());
CapturadorSocio.estadoCivil.setText(socios.obtenerEstadoCivil());
CapturadorSocio.nacionalidad.setText(socios.obtenerNacionalidad());
CapturadorSocio.fechaNacimiento.setText(socios.obtenerFechaNacimiento());
CapturadorSocio.domicilio.setText(socios.obtenerDomicilio());
CapturadorSocio.localidad.setText(socios.obtenerLocalidad());
CapturadorSocio.telfijo.setText(socios.obtenerTelefonoFijo());
CapturadorSocio.telcelular.setText(socios.obtenerCelular());
CapturadorSocio.correo.setText(socios.obtenerCorreo());
CapturadorSocio.delete.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
Socios borrarSocio = socio.get(position);
VariablesGlobales.getInstance().getSocios().remove(borrarSocio);
}});
return item;
}
static class CapturadorSocio {
TextView nombre;
TextView apellido;
TextView documento;
TextView sexo;
TextView estadoCivil;
TextView nacionalidad;
TextView fechaNacimiento;
TextView domicilio ;
TextView localidad;
TextView telfijo;
TextView telcelular;
TextView correo;
Button edit;
Button delete;
}
}
When you delete an item you should remove it from your socio list and then call notifyDataSetChanged() on your adapter instance.
Hope that helps

Categories