Update ListView in fragment - java

I have a context menu in fragment A which contains DialogFragment. With the help of DialogFragment I've created a playlist which saves in MediaStore.Playlists. In fragment B I'm showing a ListView with playlists.
How to update Listview in fragment B when I am add new playlist?
P.S Im trying to usenotifydatasetchanged()` on my adapter, but it does not work.
This is PlaylistFragment where I can not update:
private ListView lvPlaylists;
private int[] images = new int[] { R.drawable.icon_playlist };
private ArrayList<HashMap<String, String>> listPlaylists = new ArrayList<HashMap<String, String>>();;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.playlists, null);
listPlaylists = getAllPlaylists(getActivity());
lvPlaylists = (ListView) v.findViewById(R.id.lvPlaylists);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i = 0; i < listPlaylists.size(); i++) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("elementPlaylist",
listPlaylists.get(i).get("playlistName"));
datum.put("imagesPlaylist", Integer.toString(images[0]));
data.add(datum);
}
SimpleAdapter sAdapter = new SimpleAdapter(getActivity(), data,
R.layout.list_playlist_element, new String[] {
"elementPlaylist", "imagesPlaylist" }, new int[] {
R.id.tvName, R.id.ivIcon });
lvPlaylists.setAdapter(sAdapter);
lvPlaylists.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
String playlistId = listPlaylists.get(pos).get("playlistId");
Intent playlistSongs = new Intent(getActivity(),
PlaylistSongs.class);
playlistSongs.putExtra("playlistId", playlistId);
startActivity(playlistSongs);
}
});
return v;
}
public ArrayList<HashMap<String, String>> getAllPlaylists(Context context) {
String[] projection = { MediaStore.Audio.Playlists._ID, // 0
MediaStore.Audio.Playlists.NAME // 1
};
Cursor playListSDCardCursor = myquery(context,
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection,
null, null, MediaStore.Audio.Playlists.NAME, 0);
if (playListSDCardCursor.moveToFirst()) {
for (int i = 0; i < playListSDCardCursor.getCount(); i++) {
HashMap<String, String> playlist = new HashMap<String, String>();
playlist.put(
"playlistName",
playListSDCardCursor.getString(playListSDCardCursor
.getColumnIndex(MediaStore.Audio.Playlists.NAME)));
playlist.put(
"playlistId",
playListSDCardCursor.getString(playListSDCardCursor
.getColumnIndex(MediaStore.Audio.Playlists._ID)));
listPlaylists.add(playlist);
playListSDCardCursor.moveToNext();
}
}
playListSDCardCursor.close();
return listPlaylists;
}
public static Cursor myquery(Context context, Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder,
int limit) {
try {
ContentResolver resolver = context.getContentResolver();
if (resolver == null) {
return null;
}
if (limit > 0) {
uri = uri.buildUpon().appendQueryParameter("limit", "" + limit)
.build();
}
return resolver.query(uri, projection, selection, selectionArgs,
sortOrder);
} catch (UnsupportedOperationException ex) {
return null;
}
}
This is DialogFragment where i create new playlist:
public class MyDialogFragment extends DialogFragment {
Context mContext;
public MyDialogFragment() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Введите имя плейлиста:");
final EditText input = new EditText(getActivity());
input.setId(0);
builder.setView(input);
builder.setPositiveButton("Ок", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
Log.d("", "User name: " + value);
if (value != null) {
ContentValues cv = new ContentValues();
cv.put(MediaStore.Audio.Playlists.NAME, value);
Uri uri = getActivity().getContentResolver().insert(
MediaStore.Audio.Playlists
.getContentUri("external"), cv);
}
return;
}
});
builder.setNegativeButton("Отмена",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
This is TrackFragment where i call context menu and show FragmentDialog:
public class TrackFragment extends Fragment {
private ListView lvTracks;
private static ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private int songIndex;
private Utilities utils;
private ArrayList<HashMap<String, String>> listPlaylists = new ArrayList<HashMap<String, String>>();;
private int countPlaylist = 0;
private int itemPosition;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.track, null);
utils = new Utilities();
songsList = getAllSongs(getActivity());
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i = 0; i < songsList.size(); i++) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("songTitle", songsList.get(i).get("songTitle"));
datum.put("songArtist", songsList.get(i).get("songArtist"));
datum.put("songDuration", songsList.get(i).get("songDuration"));
datum.put("songAlbum", songsList.get(i).get("songAlbum"));
data.add(datum);
}
lvTracks = (ListView) v.findViewById(R.id.lvTracks);
lvTracks.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
songIndex = position;
writeData();
Intent mainIntent = new Intent(getActivity().getBaseContext(),
PlayerActivity.class);
mainIntent.putExtra("songIndex", position);
Bundle b = new Bundle();
b.putInt("songIndex", position);
b.putInt("mediaIndex",
Integer.parseInt(songsList.get(position).get("songId")));
mainIntent.putExtras(b);
int albumId = Integer.parseInt(songsList.get(position).get(
"songAlbum"));
Bitmap cover = utils.getAlbumart(albumId, getActivity()
.getApplicationContext());
if (cover == null) {
cover = BitmapFactory.decodeResource(getResources(),
R.drawable.nocover);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
cover.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
mainIntent.putExtra("albumArt", byteArray);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
});
registerForContextMenu(lvTracks);
SimpleAdapter sAdapter = new SimpleAdapter(getActivity(), data,
R.layout.list_track_element, new String[] { "songTitle",
"songArtist", "songDuration" },
new int[] { R.id.tvSongName, R.id.tvSongArtist,
R.id.tvSongDuration });
lvTracks.setAdapter(sAdapter);
return v;
}
public void onCreateContextMenu(android.view.ContextMenu menu, View v,
android.view.ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
countPlaylist++;
if (countPlaylist > 1) {
listPlaylists.clear();
listPlaylists = getAllPlaylists(getActivity()
.getApplicationContext());
} else {
listPlaylists = getAllPlaylists(getActivity()
.getApplicationContext());
}
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.setHeaderTitle("Добавить в плейлист");
menu.add(0, 0, 0, "Новый плейлист");
for (int i = 0; i < listPlaylists.size(); i++)
menu.add(0, i + 1, 0, listPlaylists.get(i).get("playlistName"));
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
itemPosition = info.position;
if (item.getItemId() == 0) {
createPlaylist(item.getItemId());
}
else {
Log.d("Playlist id",
Integer.parseInt(listPlaylists.get(item.getItemId()).get(
"playlistId"))
+ "");
addToPlaylist(Integer.valueOf(listPlaylists.get(
item.getItemId() - 1).get("playlistId")));
}
return true;
}
private void createPlaylist(int itemId) {
new MyDialogFragment().show(getFragmentManager(), "MyDialog");
}
private void addToPlaylist(int playlistId) {
ContentResolver resolver = getActivity().getContentResolver();
String[] cols = new String[] { "count(*)" };
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external",
playlistId);
Cursor cur = resolver.query(uri, cols, null, null, null);
cur.moveToFirst();
final int base = cur.getInt(0);
cur.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER,
Integer.valueOf(base + 1));
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID,
Integer.valueOf(songsList.get(itemPosition).get("songId")));
Log.d("mediaIndex", songsList.get(itemPosition).get("songId") + "");
resolver.insert(uri, values);
}
public ArrayList<HashMap<String, String>> getAllPlaylists(Context context) {
String[] projection = { MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME };
Cursor playListSDCardCursor = myquery(context,
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection,
null, null, MediaStore.Audio.Playlists.NAME, 0);
if (playListSDCardCursor.moveToFirst()) {
for (int i = 0; i < playListSDCardCursor.getCount(); i++) {
HashMap<String, String> playlist = new HashMap<String, String>();
playlist.put(
"playlistName",
playListSDCardCursor.getString(playListSDCardCursor
.getColumnIndex(MediaStore.Audio.Playlists.NAME)));
playlist.put(
"playlistId",
playListSDCardCursor.getString(playListSDCardCursor
.getColumnIndex(MediaStore.Audio.Playlists._ID)));
listPlaylists.add(playlist);
playListSDCardCursor.moveToNext();
}
}
playListSDCardCursor.close();
return listPlaylists;
}
}
I have partially solved problem adding playlist manually:
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("elementPlaylist", value);
datum.put("imagesPlaylist", Integer.toString(images[0]));
PlaylistFragment.data.add(datum);
And playlist added in listview,but on click it throw :
java.lang.IndexOutOfBoundsException: Invalid index 18, size is 18

Use CursorLoader for populating your list fragment
http://developer.android.com/reference/android/content/CursorLoader.html
It will set notification uri to your Cursor sp it will update automtically
Make your fragment implement LoaderCallbacks
class PlaylistFragment extends Fragment implements LoaderCallbacks<Cursor>{
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
sAdapter.swapCursor(null);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(getActivity(), MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, null, null, null)
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor result) {
sAdapter.swapCursor(result);
}
#Override
public void onStart(){
getLoaderManager().restartLoader(0, null, this);
}
}
Thats all, loader will automatically requry Playlist changes

Related

RecyclerView not updating after creating or deleting playlists in Fragments

I am trying to update my recyclerView by notifyDataSetChanged(). But it's not working. I have to close my specific fragment and open it to see the changes.
This is MyFragment where I call recyclerView
BottomSheetFragment.java
// showing Playlist Names
recyclerPlayListViewName =
bottomView.findViewById(R.id.recycler_play_list_view_name);
playlists = new ArrayList<Playlist>();
PlayListMethodHolder.getplaylistList(getContext(), playlists);
playlistAdapter = new PlaylistAdapter(bottomView.getContext(), playlists,
"bottomsheet");
recyclerPlayListViewName.setHasFixedSize(true);
recyclerPlayListViewName.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerPlayListViewName.setAdapter(playlistAdapter);
playlistAdapter.notifyDataSetChanged();
This is AdapterClass where I call to delete the playlist method.
PlaylistAdapter.java
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
long plistID = playlists.get(position).getId();
switch (item.getItemId()) {
case R.id.pPlay:
break;
case R.id.pRename:
String dpType = "playlistRename";
PlayListPopDialog popDialog = new PlayListPopDialog(mContext,
dpType, plistID, playlists);
popDialog.show();
break;
case R.id.pDelete:
PlayListMethodHolder.deletePlaylist(mContext, plistID);
break;
And This is another DialogView where I call Create PlayList
PlayListPopDialog.java
findViewById(R.id.btn_playlist_save).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtCreateNamePlaylist = findViewById(R.id.edt_create_name_playlist);
String playlistName = edtCreateNamePlaylist.getText().toString().trim();
if (!(playlistName.isEmpty())) {
boolean state = PlayListMethodHolder
.doPlaylistExists(getContext(), playlistName);
if (!state) {
PlayListMethodHolder.createPlaylist(getContext(), playlistName);
dismiss();
} else {
Toast.makeText(getContext(), "This name is already exists.",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Empty name", Toast.LENGTH_SHORT).show();
}
}
});
Finally, this is a class for holding all methods of creating or deleting PlayLists
PlayListMethodHolder.java
public class PlayListMethodHolder {
public static void createPlaylist(Context context, String playlistName) {
String[] projectionName = new String [] {
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME,
MediaStore.Audio.Playlists.DATA,
};
ContentValues nameValues = new ContentValues();
nameValues.put(MediaStore.Audio.Playlists.NAME, playlistName);
nameValues.put(MediaStore.Audio.Playlists.DATE_ADDED,
System.currentTimeMillis());
nameValues.put(MediaStore.Audio.Playlists.DATE_MODIFIED,
System.currentTimeMillis());
Uri uri = context.getApplicationContext().getContentResolver()
.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, nameValues);
if (uri != null) {
context.getApplicationContext().getContentResolver()
.query(uri, projectionName, null, null, null);
context.getApplicationContext().getContentResolver().notifyChange(uri, null);
}
}
// Delete single playlist from list
public static void deletePlaylist (#NonNull final Context context, long playlistId){
String playlistid = String.valueOf(playlistId);
ContentResolver resolver = context.getContentResolver();
String where = MediaStore.Audio.Playlists._ID + "=?";
String[] whereVal = {playlistid};
resolver.delete(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, where,
whereVal);
return ;
}
// get Playlist names
public static void getplaylistList(Context context, ArrayList<Playlist> plist) {
Cursor playlistCursor = context.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
null,
null,
null,
null);
if (playlistCursor != null && playlistCursor.moveToFirst()) {
//get columns
int idColumn = playlistCursor.getColumnIndex
(MediaStore.Audio.Playlists._ID);
int titleColumn = playlistCursor.getColumnIndex
(MediaStore.Audio.Playlists.NAME);
do {
long thisId = playlistCursor.getLong(idColumn);
String thisTitle = playlistCursor.getString(titleColumn);
plist.add(new Playlist(thisId, thisTitle));
} while (playlistCursor.moveToNext());
}
}
Tap to see PlayList Design View

Android: how to play audio file?

I've create a custom ListView with title and artist TextView, and with play and stop Button. The problem is that when I press play or stop Button, audio file doesn't start. How is it possible?
I've uploaded my custom Adapter and my AudioToSendActivity class:
AudioAdapter.java
public class AudioAdapter extends ArrayAdapter<String> {
private Context mContext;
private List<String> audioList;
public AudioAdapter(#NonNull Context context, ArrayList<String> list) {
super(context, 0 , list);
mContext = context;
audioList = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.audio_row, parent, false);
String audio = audioList.get(position);
String[] items = audio.split("\n");
String title = "", artist = "";
if (items.length > 1) {
title = items[0];
}
if (items.length > 2) {
artist = items[1];
}
ImageView imageAudio = (ImageView) listItem.findViewById(R.id.audio_image);
TextView titleView = (TextView) listItem.findViewById(R.id.audio_title);
titleView.setText(title);
TextView artistView = (TextView) listItem.findViewById(R.id.audio_artist);
artistView.setText(artist);
return listItem;
}
}
AudioToSendActivity.java
public class AudioToSendActivity extends AppCompatActivity {
private ArrayList<String> arrayList;
private ListView listView;
private ArrayAdapter<String> adapter;
private static final int PERMISSION_REQUEST = 1;
private Button sendButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_to_send);
listView = findViewById(R.id.audio_list_view);
sendButton = findViewById(R.id.send_audio);
if(ContextCompat.checkSelfPermission(AudioToSendActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(AudioToSendActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(AudioToSendActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
else {
ActivityCompat.requestPermissions(AudioToSendActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
}
else {
upload();
}
}
private void upload() {
listView = findViewById(R.id.audio_list_view);
arrayList = new ArrayList<>();
getAudio();
adapter = new AudioAdapter(this, arrayList); //AudioAdapter<String>(this, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// open music player to play desired song
}
});
}
public void getAudio() {
ContentResolver contentResolver = getContentResolver();
Uri audioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor audioCursor = contentResolver.query(audioUri, null, null, null, null);
if(audioCursor != null && audioCursor.moveToFirst()) {
int audioTitle = audioCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int audioArtist = audioCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
do {
String currentTitle = audioCursor.getString(audioTitle);
String currentDate = audioCursor.getString(audioArtist);
arrayList.add(currentTitle + "\n" + currentDate);
}
while (audioCursor.moveToNext());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case PERMISSION_REQUEST: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(ContextCompat.checkSelfPermission(AudioToSendActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
upload();
}
}
else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
}
}
Thanks in advance to everyone.
try this. Get the uri of your file and set it like this:
//for example
public void getAudio() {
ContentResolver contentResolver = getContentResolver();
Uri audioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor audioCursor = contentResolver.query(audioUri, null, null, null, null);
if(audioCursor != null && audioCursor.moveToFirst()) {
int audioTitle = audioCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int audioArtist = audioCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
//get the song path here and ...
int audiodata = audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
String currentTitle = audioCursor.getString(audioTitle);
String currentDate = audioCursor.getString(audioArtist);
//And here
String currentPath = audioCursor.getString(audioPath);
//And add it to your list however you like
arrayList.add(currentTitle + "\n" + currentDate + "\n" + currentPath);
}
while (audioCursor.moveToNext());
}
}
And then retrieve the path and make a uri from it and the rest:
Uri myAudioUri = Uri.parse("file:///" + currentPath);
//or
Uri myAudioUri = Uri.parse(currentPath);
//didn't have time to check the lines above
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(this, myAudioUri);
mp.prepare();
mp.start();

Invoke a activity method inside a fragment method

I am kind of new using on this. Maybe I am doing something really stupid.
My question is: There is a way of getting a method of activity inside of a fragment method?
public class MyMusic extends Fragment {
private static final int MY_PERMISSION_REQUEST = 1;
SongScreen songScreen = new SongScreen();
static ArrayList<Song> songList = new ArrayList<Song>();;
ListView songView;
String songTitle, songArtist, durationSong, songAlbum;
Song currentSong;
int position;
public MyMusic()
{}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_music, container, false);
//List View
songView = (ListView) view.findViewById(R.id.my_music);
songList = new ArrayList<Song>();
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.READ_EXTERNAL_STORAGE)){
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST);
}else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST);
}
} else {
accessfiles();
}
return view;
}
public void accessfiles(){
// songList = new ArrayList<Song>();
Cursor song = getMusic();
SongAdapter songAdt = new SongAdapter(this.getContext(), songList);
songView.setAdapter(songAdt);
//When you click on the item pass to a new fragment with all the info
songView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String songTitle = ((TextView) view.findViewById(R.id.titleSong)).getText().toString();
String songArtist = ((TextView) view.findViewById(R.id.artistSong)).getText().toString();
String durationSong = ((TextView) view.findViewById(R.id.songDuration)).getText().toString();
Song currentSong = songList.get(position);
String songAlbum = currentSong.getAlbum();
passingToScreen(songTitle,songArtist,durationSong,songAlbum);
//Path have the path of the song
String path = currentSong.getPathSong();
((MainActivity)getActivity()).playerStart(path ,currentSong);
}});
}
private void passingToScreen(String songTitle, String songArtist, String durationSong, String songAlbum) {
Bundle bundle = new Bundle();
bundle.putString("songTitle", songTitle);
bundle.putString("songArtist", songArtist);
bundle.putString("durationSong", durationSong);
bundle.putString("songAlbum", songAlbum);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
songScreen.setArguments(bundle);
fragmentTransaction.replace(R.id.layoutCM,
songScreen,
songScreen.getTag()).commit();
}
public Cursor getMusic(){
Context context = getContextOfApplication();
ContentResolver contentResolver = context.getContentResolver();
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songcursor = contentResolver.query(songUri, null, null, null, null);
if (songcursor != null && songcursor.moveToFirst()){
int songId = songcursor.getColumnIndex(MediaStore.Audio.Media._ID);
int songTitle = songcursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int songArtist = songcursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int songAlbum = songcursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int songDuration = songcursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
int pathSong = songcursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do{
Long currentId = songcursor.getLong(songId);
String currentTitle = songcursor.getString(songTitle);
String currentArtist = songcursor.getString(songArtist);
String currentAlbum = songcursor.getString(songAlbum);
Long currentDuration = songcursor.getLong(songDuration);
String currentPath = songcursor.getString(pathSong);
songList.add(new Song(currentId, currentTitle, currentArtist, currentDuration, currentAlbum, currentPath ));
}
while (songcursor.moveToNext());
}
return songcursor;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case MY_PERMISSION_REQUEST: {
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
accessfiles();
}
}
}
}
}
public void getNext(Song currentSong) {
if (songList.contains(currentSong))
{
int position1 = songList.indexOf(currentSong);
if(position1 > songList.size())
{
String nextSong = songList.get(0).getPathSong();
Song next = songList.get(0);
((MainActivity)getActivity()).playerStart(nextSong, next);
}else{
String nextSong = songList.get(position1+1).getPathSong();
Song next = songList.get(position1 + 1);
((MainActivity)getActivity()).playerStart(nextSong, next);
}
}
}
public void getPrevious(Song currentSong) {
int position = (int) (currentSong.getID() - 1);
if(position < 0)
{
String previousSong = songList.get(songList.size()).getPathSong();
Song previous = songList.get(songList.size());
((MainActivity)getActivity()).playerStart(previousSong, previous);
}else{
String previousSong = songList.get(position).getPathSong();
Song previous = songList.get(songList.size());
((MainActivity)getActivity()).playerStart(previousSong, previous);
}
}
}
This is what I am trying to do. But I know I can't do " ((MainActivity)getActivity()).playerStart(previousSong, previous);" but can I do to bring my currentsong and path to my main activity?
Thank you in advance
Two ways:
1.Use EvenBus for that.
https://github.com/greenrobot/EventBus
In your fragment:
public AppCompatActivity mActivity;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.mActivity = (BaseActivity) context;
}
and call after :
((MainActivity)mActivity).playerStart(previousSong, previous);

Mutiple Contact Picker not working in Android api level less than 17

I have a code to read the contacts from the inbuilt phone contacts and it displays all the contacts in a list view in my app.The user can select multiple contacts and display them in another activity.
This code works fine in Android API level 18 and above,but gives an error in the versions below API 18.
I'm attaching the code of the contact picker activity and its adapter.
Error Logcat
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(bean.getNumber());
sb.append("1");
values.put(DbHelper.KEY_FNAME,bean.getName());
values.put(DbHelper.KEY_LNAME,bean.getNumber() );
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
}
dataBase.close();
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
/**
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
**/
Intent i = new Intent(Contacts_main.this, MainActivity.class);
i.putExtra("NAME", name);
i.putExtra("EVT_Name", event_name);
i.putExtra("EVT_Date", event_date);
startActivity(i);
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//String pImage =
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
//cp.setImage(getResources(R.drawable.prof_active));
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setDividerHeight(0);
lv.setDivider(null);
lv.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(Contacts_main.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter); //ERROR SHOWING HERE
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
// e.printStackTrace();
//Toast.makeText(context, "Crash",Toast.LENGTH_SHORT).show();
}
hidePB();
}
};
thread.start();
}
Adapter Class:
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private List<ContactObject> mainInviteesList = null;
private ArrayList<ContactObject> arraylist;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
mHelper=new DbHelper(context);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
protected EditText invitees;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
holder.invitees = (EditText) view.findViewById(R.id.editInvites);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
view.setTag(R.id.editInvites, holder.invitees);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
/**
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,mainDataList.get(getPosition).getName());
values.put(DbHelper.KEY_LNAME,mainDataList.get(getPosition).getNumber());
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
dataBase.close();
**/
}
});
// holder.invitees.addTextChangedListener(watcher);
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
//holder.invitees.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if(getByteContactPhoto(mainDataList.get(position).getImage())==null){
holder.image.setImageResource(R.drawable.prof_active);
}else{
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[] {Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream( new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}

Passing bundle from activity to fragment

I am fairly new to android programming and ran to a small problem. I have an activity that lets users select names from a muli-select listview. I can store it in an ArrayList fine but how do I pass that ArrayList as a bundle to be retrieved from the fragment? Thank you for any future answers.
MainActivity.java:
public class MainActivity extends Activity {
ListView myListView;
Button getResult;
ConnectionClass connectionClass;
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
MyArrayAdapter myArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
emp_names_list.add("LOL");
//PAGKUHA NG RESULTS SA DB
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
String query = "select * from users WHERE user_type=3";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
String fname =rs.getString("user_fname");
String lname =rs.getString("user_lname");
String name = String.valueOf(fname)+" "+String.valueOf(lname);
emp_names_list.add(fname);
}
Toast.makeText(getApplicationContext(), "FETCH SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "FETCH FAIL", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
myListView = (ListView)findViewById(R.id.list);
//PARA SA LAYOUT
myArrayAdapter = new MyArrayAdapter(
this,
R.layout.row,
android.R.id.text1,
emp_names_list
);
myListView.setAdapter(myArrayAdapter);
myListView.setOnItemClickListener(myOnItemClickListener);
getResult = (Button)findViewById(R.id.getresult);
getResult.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String result = "";
/*
//getCheckedItemPositions
List<Integer> resultList = myArrayAdapter.getCheckedItemPositions();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + " ";
}
*/
//getCheckedItems
List<String> resultList = myArrayAdapter.getCheckedItems();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + "\n";
}
myArrayAdapter.getCheckedItemPositions().toString();
//Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {
//FOR INSERTION ITO USING ARRAYLIST
String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));
//data1.add(samp);
for(String name : data1)
{
names = name;
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}
}});
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
myArrayAdapter.toggleChecked(position);
}};
private class MyArrayAdapter extends ArrayAdapter<String>{
private HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
public MyArrayAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
for(int i = 0; i < objects.size(); i++){
myChecked.put(i, false);
}
}
public void toggleChecked(int position){
if(myChecked.get(position)){
myChecked.put(position, false);
}else{
myChecked.put(position, true);
}
notifyDataSetChanged();
}
public List<Integer> getCheckedItemPositions(){
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems(){
List<String> checkedItems = new ArrayList<String>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItems).add(emp_names_list.get(i));
}
}
return checkedItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.checkedTextView);
checkedTextView.setText(emp_names_list.get(position));
Boolean checked = myChecked.get(position);
if (checked != null) {
checkedTextView.setChecked(checked);
}
return row;
}
}
}
I have tried the following example but returns null:
Bundle bundle=new Bundle();
bundle.putBundle("bundle_DescriptioneTab",bundle_DescriptioneTab);
bundle.putBundle("bundle_User_Review",bundle_User_Review);
The first thing is that you have to declare your Class as Serializable
public class MyClass implements Serialisable{
}
and using
Bundle bundle = new Bundle();
bundle.putSerialisable("myclass",MyClass);
to send data of only class
And
If you want to send Arraylisyt use:
public class MyClass implements Parcelable{
}
Intent intent = new Intent(this,SecondaryActivity.class);
ArrayList<MyClass> mArrayList = new ArrayList<MyClass>();
and using
intent.putParcelableArrayListExtra("key", mArrayList);
You can store it in an object:
public class Thing implements Serializable {
private ArrayList<String> emp_names_list = new ArrayList<String>();
public ArrayList<Integer> emp_id_list = new ArrayList<Integer>();
[...]
}
And pass it like so:
bundle.putBundle("thing",object_thing);

Categories