Android: how to play audio file? - java

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();

Related

How to handle loading large amounts of data in android

I have an activity with a button upon clicking which opens a new activity with 3 fragments with tab layout, The first fragment loads files from the internal storage in recyclerview, 2nd one loads installed apps in recyclerview and the 3rd loads contacts in a recyclerview, But the problem I'm facing is that when I click the button to launch the activity it takes 2-3 seconds to launch the activity & I tested it on a device which contained a lot of apps and contacts it crashed the app and didn't opened the activity, I think this is because it is taking time to load all the data at once, How can I solve this problem?
This is the code from the fragments
FileListFragment.java
public class FileListFragment extends Fragment implements FilesStateManager {
private static final String TAG = "FileListFragment";
RecyclerView fileListRecyclerView,currentPathRecyclerView;
TextView currentPathTextView;
ArrayList<FileObject> fileObjects = new ArrayList<>();
ArrayList<FileObject> currentFolders = new ArrayList<>();
static ArrayList<FileObject> selectedFiles = new ArrayList<>();
String currentPath = "";
String initialPath = "";
String pathToShow = "/";
RelativeLayout grantPermissionContainer;
Button grantPermissionButton;
FileManager fileManager;
static DataSelectedManager dataSelectedManager;
public FileListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
private final int PERMISSION_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_file_list,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
currentPathRecyclerView = view.findViewById(R.id.current_folder_recyclerview);
fileListRecyclerView = view.findViewById(R.id.folder_list_recyclerview);
grantPermissionContainer = view.findViewById(R.id.grant_permission_container);
grantPermissionButton = view.findViewById(R.id.grant_permission_button);
init();
}
private void init(){
fileManager = new FileManager(getContext());
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
grantPermissionContainer.setVisibility(View.VISIBLE);
fileListRecyclerView.setVisibility(View.GONE);
}
grantPermissionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT < 16) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
} else {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_CODE);
}
}
});
try{
String path = getActivity().getExternalFilesDir(null).getPath();
currentPath = path.split("Android")[0];
initialPath = currentPath;
FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
currentFolders.add(fileObject);
setupCurrentPathRecyclerView();
readFiles();
Log.d(TAG, "init: " + path);
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult: Called");
if (requestCode == PERMISSION_CODE){
Log.d(TAG, "onRequestPermissionsResult: Codes matched");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
grantPermissionContainer.setVisibility(View.GONE);
fileListRecyclerView.setVisibility(View.VISIBLE);
FileObject fileObject = new FileObject("/",initialPath,null,true,"none","0",false);
currentFolders.add(fileObject);
setupCurrentPathRecyclerView();
readFiles();
}
}
}
private void readFiles(){
fileObjects = fileManager.readFiles(currentPath,selectedFiles);
setupRecyclerView();
}
private void setupRecyclerView(){
FileListAdapter fileListAdapter = new FileListAdapter(fileObjects,selectedFiles,getContext(),this);
fileListRecyclerView.setAdapter(fileListAdapter);
fileListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
private void setupCurrentPathRecyclerView(){
FolderPathAdapter folderPathAdapter = new FolderPathAdapter(currentFolders,getContext(),this);
currentPathRecyclerView.setAdapter(folderPathAdapter);
currentPathRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,false));
currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
}
#Override
public void folderClicked(FileObject fileObject) {
currentPath = fileObject.getPath();
currentFolders.add(fileObject);
currentPathRecyclerView.getAdapter().notifyItemInserted(currentFolders.size() - 1);
currentPathRecyclerView.smoothScrollToPosition(currentFolders.size());
readFiles();
}
#Override
public void pathFolderClicked(FileObject fileObject) {
Log.d(TAG, "pathFolderClicked: Called");
if (!fileObject.getPath().equals(currentFolders.get(currentFolders.size() - 1).getPath())){
for (FileObject folder : currentFolders){
if (folder.getPath().equals(fileObject.getPath())){
int index = currentFolders.indexOf(folder) + 1;
int size = currentFolders.size();
currentFolders = new ArrayList<>(currentFolders.subList(0,index));
Log.d(TAG, "pathFolderClicked: Number of item " + (size - index) + " Index: " + index);
// currentPathRecyclerView.getAdapter().notifyItemRangeRemoved(index,size - index);
setupCurrentPathRecyclerView();
currentPath = currentFolders.get(currentFolders.size() - 1).getPath();
readFiles();
Log.d(TAG, "pathFolderClicked: Notified");
}
}
Log.d(TAG, "pathFolderClicked: " + Arrays.toString(currentFolders.toArray()));
}
}
#Override
public void fileSelected(FileObject fileObject) {
selectedFiles.add(fileObject);
dataSelectedManager.dataSelected();
}
#Override
public void fileDeselected(FileObject fileObject) {
ArrayList<FileObject> filesToRemove = new ArrayList<>();
for (FileObject fileObject1 : selectedFiles){
if (fileObject.getPath().equals(fileObject1.getPath())){
filesToRemove.add(fileObject1);
}
}
dataSelectedManager.dataDeSelected();
selectedFiles.removeAll(filesToRemove);
}
public static void triggerDataTransfer(){
dataSelectedManager.sendSelectedFiles(selectedFiles);
}
}
AppListFragment.java
public class AppListFragment extends Fragment implements AppsStateManager {
RecyclerView appListRecyclerView;
TextView selectAllTextView;
CheckBox selectAllCheckBox;
static ArrayList<App> apps = new ArrayList<>();
AppsManager appsManager;
static DataSelectedManager dataSelectedManager;
public AppListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_app_list,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
appListRecyclerView = view.findViewById(R.id.app_recycler_view);
selectAllTextView = view.findViewById(R.id.select_all_text_view);
selectAllCheckBox = view.findViewById(R.id.select_all_checkbox);
appsManager = new AppsManager(getActivity().getPackageManager(),getActivity().getApplicationContext().getPackageName());
getInstalledApps();
setupRecyclerView();
selectAllCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!selectAllCheckBox.isChecked()){
for (App app : apps){
if (app.isSelected()){
app.setSelected(false);
dataSelectedManager.dataDeSelected();
}
}
}
else {
for (App app : apps){
if (!app.isSelected()){
app.setSelected(true);
dataSelectedManager.dataSelected();
}
}
}
appListRecyclerView.getAdapter().notifyDataSetChanged();
}
});
}
private void getInstalledApps(){
apps = appsManager.getInstalledApps();
selectAllTextView.setText("Select All (" + apps.size() + ")");
}
private void setupRecyclerView(){
AppListAdapter appListAdapter = new AppListAdapter(apps,getContext(),this);
appListRecyclerView.setAdapter(appListAdapter);
appListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
#Override
public void deSelected() {
selectAllCheckBox.setChecked(false);
dataSelectedManager.dataDeSelected();
}
#Override
public void selected() {
dataSelectedManager.dataSelected();
}
public static void triggerDataTransfer(){
ArrayList<App> selectedApps = new ArrayList<>();
for (App app : apps){
if (app.isSelected()){
selectedApps.add(app);
}
}
dataSelectedManager.sendSelectedApps(selectedApps);
}
}
ContactListFragment.java
public class ContactListFragment extends Fragment implements ContactsStateManager {
private static final String TAG = "ContactListFragment";
static ArrayList<Contact> contacts = new ArrayList<>();
TextView selectAllTextView;
CheckBox selectAllRadioButton;
Button grantPermissionButton;
RelativeLayout grantPermissionLayout;
RecyclerView contactsRecyclerView;
ContactsManager contactsManager;
static DataSelectedManager dataSelectedManager;
public ContactListFragment(DataSelectedManager dataSelectedManager) {
this.dataSelectedManager = dataSelectedManager;
}
private final int PERMISSION_CODE = 101;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_contact_list,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
contactsRecyclerView = view.findViewById(R.id.contacts_recycler_view);
selectAllTextView = view.findViewById(R.id.select_all_text_view);
selectAllRadioButton = view.findViewById(R.id.select_all_checkbox);
grantPermissionLayout = view.findViewById(R.id.grant_permission_container);
grantPermissionButton = view.findViewById(R.id.grant_permission_button);
contactsManager = new ContactsManager(getActivity().getContentResolver());
selectAllRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!selectAllRadioButton.isChecked()){
for (Contact contact: contacts){
if (contact.isSelected()){
contact.setSelected(false);
dataSelectedManager.dataDeSelected();
}
}
}
else{
for (Contact contact: contacts){
if (!contact.isSelected()){
contact.setSelected(true);
dataSelectedManager.dataSelected();
}
}
}
contactsRecyclerView.getAdapter().notifyDataSetChanged();
}
});
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
grantPermissionLayout.setVisibility(View.VISIBLE);
contactsRecyclerView.setVisibility(View.GONE);
}
else{
readContacts();
setupRecyclerView();
}
grantPermissionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},PERMISSION_CODE);
}
});
}
private void readContacts(){
contacts = contactsManager.getContacts();
selectAllTextView.setText("Select All (" + contacts.size() + ")");
}
private void setupRecyclerView(){
ContactListAdapter contactListAdapter = new ContactListAdapter(contacts,getContext(),this);
contactsRecyclerView.setAdapter(contactListAdapter);
contactsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d(TAG, "onRequestPermissionsResult: Called");
if (requestCode == PERMISSION_CODE){
Log.d(TAG, "onRequestPermissionsResult: Codes matched");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult: Permission Granted");
grantPermissionLayout.setVisibility(View.GONE);
readContacts();
contactsRecyclerView.setVisibility(View.VISIBLE);
setupRecyclerView();
}
}
}
#Override
public void deSelected() {
selectAllRadioButton.setChecked(false);
dataSelectedManager.dataDeSelected();
}
#Override
public void selected() {
dataSelectedManager.dataSelected();
}
public static void triggerDataTransfer(){
ArrayList<Contact> selectedContacts = new ArrayList<>();
for(Contact contact : contacts){
if (contact.isSelected()){
selectedContacts.add(contact);
}
}
dataSelectedManager.sendSelectedContacts(selectedContacts);
}
}
AppsManager.java
public class AppsManager {
PackageManager packageManager;
private String PACKAGE_NAME;
public AppsManager(PackageManager packageManager,String PACKAGE_NAME) {
this.packageManager = packageManager;
this.PACKAGE_NAME = PACKAGE_NAME;
}
public ArrayList<App> getInstalledApps(){
PackageManager packageManager = this.packageManager;
ArrayList<App> apps = new ArrayList<>();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++){
PackageInfo packageInfo = packs.get(i);
if ((!isSystemApp(packageInfo)) && !packageInfo.packageName.equals(PACKAGE_NAME)){
String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
Drawable icon = packageInfo.applicationInfo.loadIcon(packageManager);
String packages = packageInfo.applicationInfo.packageName;
apps.add(new App(appName,icon,packages,false));
}
}
return apps;
}
private boolean isSystemApp(PackageInfo packageInfo){
return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
}
ContactsManager.java
public class ContactsManager{
ContentResolver contentResolver;
public ContactsManager(ContentResolver contentResolver) {
this.contentResolver = contentResolver;
}
public ArrayList<Contact> getContacts(){
ContentResolver cr = contentResolver;
ArrayList<Contact> contacts = new ArrayList<>();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = "";
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
Contact contact = new Contact(name,id,phone,false);
contacts.add(contact);
}
}
return contacts;
}
}
FileManager.java
public class FileManager {
private static final String TAG = "FileManager";
Context context;
public FileManager(Context context) {
this.context = context;
}
public ArrayList<FileObject> readFiles(String path, ArrayList<FileObject> selectedFiles){
ArrayList<FileObject> filesList = new ArrayList<>();
File file = new File(path);
File[] files = file.listFiles();
for (File file1 : files){
String name = file1.getName();
String filePath = file1.getAbsolutePath();
boolean isDirectory = file1.isDirectory();
String fileSize = "";
if (isDirectory){
int count = file1.listFiles().length;
if (count > 0){
fileSize = count + "";
}
}
else{
long fileSizeInBytes = file1.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB >= 1){
fileSize = fileSizeInMB + " MB";
}
else{
fileSize = fileSizeInKB + " KB";
}
}
boolean selected = isSelected(filePath,selectedFiles);
String extension = "";
if (isDirectory){
extension = "none";
}
else{
Log.d(TAG, "readFiles: " + filePath);
String[] splitArray = filePath.split("\\.");
Log.d(TAG, "readFiles: " + splitArray.length);
extension = splitArray[splitArray.length - 1];
}
Drawable icon;
if (isDirectory){
icon = context.getResources().getDrawable(R.drawable.ic_folder_skin_24dp);
}
else{
switch (extension){
case "pdf":
icon = context.getResources().getDrawable(R.drawable.ic_picture_as_pdf_red_24dp);
break;
default:
icon = context.getResources().getDrawable(R.drawable.ic_insert_drive_file_skin_24dp);
break;
}
}
FileObject fileObject = new FileObject(name,filePath,icon,isDirectory,extension,fileSize,selected);
filesList.add(fileObject);
}
return filesList;
}
boolean isSelected(String path, ArrayList<FileObject> selectedFiles){
boolean isSelected = false;
for (FileObject fileObject : selectedFiles){
if (fileObject.getPath().equals(path)){
isSelected = true;
}
}
return isSelected;
}
}
When you are performing heavy operations consider using Threads.

How to populate numbers from call log into a onClick list?

I am building an app where I am suppose to view my call log in a list and make a call when pressing an item in the list.
What is the best option for this?
I wanna try to make a custom adapter but I am unsure if it is the right way to do or if there is an easier way?
Thanks for any help!
For the moment I am using a text view and a string buffer to populate the list with my call log.
public class LastCallActivity extends Activity {
private List<LastCallModel> wlistCalls;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_call);
if (ContextCompat.checkSelfPermission(LastCallActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(LastCallActivity.this, Manifest.permission.READ_CALL_LOG)) {
ActivityCompat.requestPermissions(LastCallActivity.this, new String[]{Manifest.permission.READ_CALL_LOG}, 1);
} else {
ActivityCompat.requestPermissions(LastCallActivity.this, new String[]{Manifest.permission.READ_CALL_LOG}, 1);
}
} else {
// do stuff
TextView textView = (TextView) findViewById(R.id.textViewen);
textView.setText(getCallDetails());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(LastCallActivity.this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted!", Toast.LENGTH_SHORT).show();
TextView textView = (TextView) findViewById(R.id.textViewen);
textView.setText(getCallDetails());
}
} else {
Toast.makeText(this, "No permission GRANTED!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
private String getCallDetails() {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details:\n\n");
while (managedCursor.moveToNext()) {
String phName = managedCursor.getString(name);
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
if (phName != null && phNumber != null) {
wlistCalls.add(new LastCallModel(phName, phNumber));
}
Date callDayTime = new Date(Long.valueOf(callDate));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm");
String dateString = formatter.format(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nName: " + phName + "\nPhone Number: " + phNumber + " \nCallType: " + dir + "\nCall Date: " + dateString + "\nCall Duration: " + callDuration);
sb.append("\n-------------");
sb.append("\n*************");
sb.append("\n*************");
}
managedCursor.close();
return sb.toString();
}
}
I solved it by using a RecyclerView with an custom adapter!
This is my custom adapter.
public class LastCallAdapter extends RecyclerView.Adapter<LastCallAdapter.ViewHolder> {
private LayoutInflater layoutInflater;
private Context mContext;
private ArrayList<String> phoneNumber;
public LastCallAdapter(Context mContext, ArrayList<String> phoneNumber) {
this.mContext = mContext;
this.phoneNumber = phoneNumber;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.from(parent.getContext()).inflate(R.layout.items_contacts, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.number.setText(phoneNumber.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callDial = new Intent(Intent.ACTION_DIAL);
callDial = callDial.setData(Uri.parse("tel:"+phoneNumber.get(position)));
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
mContext.startActivity(callDial);
return;
}
Toast.makeText(mContext, phoneNumber.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return phoneNumber.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView number;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
number = itemView.findViewById(R.id.contact_number);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
And this method in the main activity for starting the adapter
private void startAdapter(){
RecyclerView recyclerView = findViewById(R.id.recyclerViewen);
LastCallAdapter lastCallAdapter = new LastCallAdapter(this, phoneNumbers);
recyclerView.setAdapter(lastCallAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

Why List for Recyclerview returning same items in all positions? [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.

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;
}
}

Categories