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.
Related
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();
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));
}
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.
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);
Hi in the below code I am getting array index out of bounds exception.Here friend array it's giving two values.
For ex:
friendinfo[0]=user1,friendinfo1=user2 and with checkbox when i am selecting user1 I want to show friend.length to 2 and checked value should be 1.
this is sample screen how to add the use3 and user1 when i am clicking the create button.
GroupList.java
public class GroupList extends ListActivity
{
boolean[] checkBoxState;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter
{
#SuppressWarnings("unused")
class ViewHolder {
TextView text;
ImageView icon;
CheckBox check1;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friends = friends;
}
public int getCount() {
return friends.length;
}
public FriendInfo getItem(int position) {
return friends[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grouplist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.check1 = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friends[position].userName);
holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
checkBoxState = new boolean[friends.length];
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBoxState[position]=isChecked;
String check=friends[position].userName;
Toast.makeText(getApplicationContext(),friends[position].userName+"checked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null)
{
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED))
{
GroupList.this.updateData(FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo();
if (friends != null) {
GroupList.this.updateData(friends, null);
}
String groupname = getIntent().getStringExtra("nick");
setTitle(groupname);
ownusername = imService.getUsername();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.group_list_screen);
friendAdapter = new FriendListAdapter(this);
Button create=(Button)findViewById(R.id.create);
create.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
#Override
public void onClick(View v) {
String groupname = getIntent().getStringExtra("nick");
try {
FriendInfo[] friend=FriendController.getFriendsInfo();
//checkBoxState = new CheckBox[friend.length];
/*try {
for(int i=0;i <=friend.length ;i++){
if(checkBoxState[i].isChecked()){
check[i]="1";
}
}
}catch (Exception e) {
e.printStackTrace();
}*/
String result1 = imService.CreateGroup(groupname,imService.getUsername(),friend);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();
}
});
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends)
{
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null)
{
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0)
{
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.stat_sample)
.setContentTitle(getText(R.string.new_friend_request_exist));
/*Notification notification = new Notification(R.drawable.stat_sample,
getText(R.string.new_friend_request_exist),
System.currentTimeMillis());*/
Intent i = new Intent(this, UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
i, 0);
mBuilder.setContentText("You have new friend request(s)");
mBuilder.setContentIntent(contentIntent);
NM.notify(R.string.new_friend_request_exist, mBuilder.build());
}
else
{
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onPause()
{
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(GroupList.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
You probably wanted to write :
if(checkBoxState[i]==isChecked)
if checkBoxState and friend arrays have the same length, checkBoxState[friend.length] is out of bounds, since the indices of an array are from 0 to length - 1.
Also note that your if condition contained an assignment operator = instead of a comparison operator ==.
Just use the index inside the for loop. Also since isChecked is already a boolean you can just assign it directly to checkBoxState
for (int i = 0; i < friend.length; i++) {
checkBoxState[i] = isChecked;
}
You are trying to access the index 2nd position in an array that has only a length of 2 (positions 0 and 1).
So please change the code as below,
if(checkBoxState[i]==isChecked)