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);
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 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.
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 building an app for Udacity called popular movies app which will fetch movies info from movieDB and display posters in the first activity than if the user clicked any poster it will take him to detailActivity where all the Movie detail will be displayed.
Now I am done with stage 1, stage 2 I am supposed to give the user the ability to make a favorite movie list which will be displayed in the first activity and deatilActivity and will be fetched from and to a database.
I already created the database and I have data saved there but I do not no how to retrieve it and display it to user kindly help me to do it.
below is my code:
First Activity the gridView for posters:
public class PhotoGrid extends Fragment {
//Create a string array variable for every item that we are going to recive from
// the movieDB
String[] movieId, movieTitle, movieReleaseDate, movieVoteAverage, movieOverview, moviePosterPath;
//use string1 to attach the poster path for every poster with the url so we can call the image
static String[] string1;
// define gridView here so we can use it in onPostexecute()
GridView gridView;
//movieUrl is used for the sortby setting
String movieUrl;
SQLiteDatabase db;
databaseHelper databaseHelper;
Cursor cursor;
ContentProvider contentProvider;
public PhotoGrid() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
} else if (id == R.id.action_settings) {
//if action_setting clicked SettingActivity will start
Intent intent = new Intent(getActivity(), SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateMovie() {
FetchMoviesPosters movieTask = new FetchMoviesPosters();
//make popularity as the default order or call for movieposters in settings
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sortby_key),
getString(R.string.pref_sortby_default));
movieTask.execute(sortBy);
}
#Override
public void onStart() {
super.onStart();
//update movies list on start
updateMovie();
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_photo_grid, container, false);
databaseHelper = new databaseHelper(getActivity(),MovieContract.MovieEntry.TABLE_NAME,null,2);
db = databaseHelper.getReadableDatabase();
gridView = (GridView) rootView.findViewById(R.id.grid_view);
updateMovie();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Here handle the on poster click action by assigning the clicked poster info
//to strings and send them to detail activity with different keys to be able to
// control each item alone
String movieIDText = movieId[i];
String movieTitleText = movieTitle[i];
String movieOverViewText = movieOverview[i];
String movieReleaseDateText = movieReleaseDate[i];
String movieRatingText = movieVoteAverage[i];
String movieDetailImage = moviePosterPath[i];
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie_id", movieIDText);
intent.putExtra("movie_overview", movieOverViewText);
intent.putExtra("movie_title", movieTitleText);
intent.putExtra("movie_release_date", movieReleaseDateText);
intent.putExtra("movie_rating", movieRatingText);
intent.putExtra("image_path", movieDetailImage);
startActivity(intent);
}
});
return rootView;
}
//ImageAdapter is used to control images dimensions and load them in the
// imageview using Picasso
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds;
public ImageAdapter(Context c, String[] str2) {
mContext = c;
mThumbIds = str2;
}
#Override
public int getCount() {
if (mThumbIds != null) {
return mThumbIds.length;
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(700, 1200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(mThumbIds[position]).into(imageView);
return imageView;
}
}
public class FetchMoviesPosters extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesPosters.class.getSimpleName();
//in this function the different order settings are defined
private String setOrder(String sortBy) {
if (sortBy.equals(getString(R.string.pref_sorting_popularity))) {
movieUrl = "https://api.themoviedb.org/3/movie/popular?";
} else if (sortBy.equals(getString(R.string.pref_sorting_highest_rating))) {
movieUrl = "https://api.themoviedb.org/3/movie/top_rated?";
}
else if (sortBy.equals(getString(R.string.pref_sorting_favorite))){
cursor = databaseHelper.retrieveData(db);
if (cursor.moveToFirst()){
do {
String id, title, overView, releaseDate, rating, posterPath;
id = cursor.getString(0);
title = cursor.getString(1);
overView = cursor.getString(2);
releaseDate = cursor.getString(3);
rating = cursor.getString(4);
posterPath = cursor.getString(5);
contentProvider = new ContentProvider(id , title , overView
, releaseDate, rating , posterPath);
}while (cursor.moveToNext());
}
}
return sortBy;
}
private String[] MoviesJasonPrase(String moviesPosterStr ) throws JSONException {
final String M_Result = "results";
final String M_ID = "id";
final String M_Title = "original_title";
final String M_Release = "release_date";
final String M_Vote = "vote_average";
final String M_OverV = "overview";
final String M_Poster = "poster_path";
JSONObject moviesJson = new JSONObject(moviesPosterStr);
JSONArray resultsArray = moviesJson.getJSONArray(M_Result);
movieId = new String[resultsArray.length()];
movieTitle = new String[resultsArray.length()];
movieReleaseDate = new String[resultsArray.length()];
movieVoteAverage = new String[resultsArray.length()];
movieOverview = new String[resultsArray.length()];
moviePosterPath = new String[resultsArray.length()];
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject movie = resultsArray.getJSONObject(i);
movieId[i] = movie.getString(M_ID);
movieTitle[i] = movie.getString(M_Title);
movieReleaseDate[i] = movie.getString(M_Release);
movieVoteAverage[i] = movie.getString(M_Vote);
movieOverview[i] = movie.getString(M_OverV);
moviePosterPath[i] = movie.getString(M_Poster);
}
return moviePosterPath;
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviePostersJsonStr = null;
try {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sortby_key),
getString(R.string.pref_sorting_popularity));
setOrder(sortBy);
final String APPID_PARAM = "api_key";
Uri builtUri = Uri.parse(movieUrl).buildUpon()
.appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DB)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
moviePostersJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PhotoGrid", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PhotoGrid", "Error closing stream", e);
}
}
}
try {
return MoviesJasonPrase(moviePostersJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] Strings) {
if (Strings != null) {
string1 = new String[Strings.length];
for (int i = 0; i < Strings.length; i++) {
//receive poster images path
String[] getImage = Strings[i].split("-");
//concatenate path to url "http://image.tmdb.org/t/p/w185/"
string1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
}
ImageAdapter imageAdapter = new ImageAdapter(getActivity(), string1);
//put images after going though the adapter in the gridview
gridView.setAdapter(imageAdapter);
}
}
}
}
The detailActivity:
public class DetailFragment extends Fragment {
String ID;
String title;
String overView;
String releaseDate;
String rating;
String posterPath;
String movieKey;
databaseHelper myDB ;
ImageButton favorite;
public DetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_detail, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(getActivity(), SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
myDB = new databaseHelper(getActivity(), MovieContract.MovieEntry.TABLE_NAME,null,2);
favorite = (ImageButton) rootView.findViewById(R.id.favorite);
final Intent intent = getActivity().getIntent();
// The detail Activity called via intent. Inspect the intent for
// movies data using movie ID.
if (intent != null && intent.hasExtra("movie_id")) {
//if true put each item in a textview and load the poster in imageView
ID = intent.getStringExtra("movie_id");
title = intent.getStringExtra("movie_title");
((TextView) rootView.findViewById(R.id.title_text))
.setText(title);
overView = intent.getStringExtra("movie_overview");
((TextView) rootView.findViewById(R.id.overview_text))
.setText(overView);
releaseDate = intent.getStringExtra("movie_release_date");
((TextView) rootView.findViewById(R.id.release_date_text))
.setText(releaseDate);
rating = intent.getStringExtra("movie_rating");
((TextView) rootView.findViewById(R.id.rating_text))
.setText(rating);
posterPath = intent.getStringExtra("image_path");
String posterImage = "http://image.tmdb.org/t/p/w185/" + posterPath;
ImageView imageView = (ImageView) rootView.findViewById(R.id.detail_image);
Picasso.with(getActivity()).load(posterImage).resize(500, 800).into(imageView);
}
Button button = (Button) rootView.findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playTrailer();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(String.valueOf("http://www.youtube.com/watch?v="+ movieKey)));
startActivity(intent);
}
});
Button button1 = (Button) rootView.findViewById(R.id.open_reviews);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = ID;
Intent intent1 = new Intent(getActivity(), ReviewActivity.class);
intent1.putExtra("movie_id", id);
startActivity(intent1);
}
});
addData();
return rootView;
}
public void playTrailer() {
FetchMoviesTrailer fetchMoviesTrailer = new FetchMoviesTrailer();
fetchMoviesTrailer.execute(ID);
}
public void addData(){
favorite.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInsearted = myDB.insert(ID, title, overView, releaseDate,
rating, posterPath);
if (isInsearted)
Toast.makeText(getActivity(),"Added to Favorite", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(getActivity(),"Not Added to Favorite", Toast.LENGTH_SHORT)
.show();
}
}
);
}
public class FetchMoviesTrailer extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTrailer.class.getSimpleName();
//in this function the different order settings are defined
private String[] MoviesJasonPrase(String moviesTrailerStr) throws JSONException {
final String T_Result = "results";
final String T_key = "key";
JSONObject moviesJson = new JSONObject(moviesTrailerStr);
JSONArray resultsArray = moviesJson.getJSONArray(T_Result);
String[] strings = new String[resultsArray.length()];
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject movie = resultsArray.getJSONObject(i);
movieKey = movie.getString(T_key);
strings[i] = movieKey;
}
return strings;
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieTrailerJsonStr = null;
try {
final String APPID_PARAM = "api_key";
final String Traile_Url = "http://api.themoviedb.org/3/movie/" + ID
+ "/videos?";
Uri builtUri = Uri.parse(Traile_Url).buildUpon()
.appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DB)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieTrailerJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PhotoGrid", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PhotoGrid", "Error closing stream", e);
}
}
}
try {
return MoviesJasonPrase(movieTrailerJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
}
}
The DataBase Helper:
public class databaseHelper extends SQLiteOpenHelper{
SQLiteDatabase db ;
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "FavoriteMovies.db";
public databaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_Movie_TABLE = "CREATE TABLE " + MovieEntry.TABLE_NAME + " (" +
MovieEntry.ID_COLUMAN + " TEXT PRIMARY KEY," +
MovieEntry.TITLE_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.OVERVIEW_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.RELEASE_DATE_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.RATING_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.POSTAR_PATH_COLUMAN+ " TEXT NOT NULL " +
" );";
db.execSQL(SQL_CREATE_Movie_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + MovieEntry.TABLE_NAME);
onCreate(db);
}
public boolean insert(String id, String title , String overView , String date, String rating,
String poster){
db = super.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MovieEntry.ID_COLUMAN,id);
contentValues.put(MovieEntry.TITLE_COLUMAN,title);
contentValues.put(MovieEntry.OVERVIEW_COLUMAN,overView);
contentValues.put(MovieEntry.RELEASE_DATE_COLUMAN,date);
contentValues.put(MovieEntry.RATING_COLUMAN,rating);
contentValues.put(MovieEntry.POSTAR_PATH_COLUMAN, poster);
long isAdded = db.insert(MovieEntry.TABLE_NAME, null ,contentValues);
if (isAdded == -1) {
return false;
}
else
return true;
}
public Cursor retrieveData(SQLiteDatabase db){
Cursor cursor;
String[] projection = {MovieEntry.ID_COLUMAN, MovieEntry.TITLE_COLUMAN,
MovieEntry.OVERVIEW_COLUMAN, MovieEntry.RELEASE_DATE_COLUMAN, MovieEntry.RATING_COLUMAN,
MovieEntry.POSTAR_PATH_COLUMAN};
cursor = db.query(MovieEntry.TABLE_NAME, projection, null,null,null,null,null);
return cursor;
}
}
The DataBase Contract:
public class MovieContract {
public MovieContract(){}
public static abstract class MovieEntry implements BaseColumns{
public static final String TABLE_NAME = "favorite";
public static final String ID_COLUMAN = "ID";
public static final String TITLE_COLUMAN = "title";
public static final String OVERVIEW_COLUMAN = "overView";
public static final String RELEASE_DATE_COLUMAN = "releaseDate";
public static final String RATING_COLUMAN = "rating";
public static final String POSTAR_PATH_COLUMAN = "posterPath";
}
}
The content Provider:
public class ContentProvider {
private String id;
private String title;
private String overView;
private String releaseDate;
private String rating;
private String posterPath;
public ContentProvider(String ID, String Title,String OverView, String ReleaseDate,
String Rating, String PosterPath){
this.id = ID;
this.title = Title;
this.overView = OverView;
this.releaseDate = ReleaseDate;
this.rating = Rating;
this.posterPath = PosterPath;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOverView() {
return overView;
}
public void setOverView(String overView) {
this.overView = overView;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
}
This is all covered in the Udacity course. I would suggest reviewing those videos.
However, the basic idea is that you need to create a query() method in your content provider class. The Sunshine example from Udacity looks something like this:
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Here's the switch statement that, given a URI, will determine what kind of request it is,
// and query the database accordingly.
Cursor retCursor;
switch (sUriMatcher.match(uri)) {
// "weather/*/*"
case WEATHER_WITH_LOCATION_AND_DATE:
{
retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
break;
}
// "weather/*"
case WEATHER_WITH_LOCATION: {
retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
break;
}
// "weather"
case WEATHER: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.WeatherEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
// "location"
case LOCATION: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
From there, if you aren't using a CursorLoader, you need to call the query method on your Content Resolver and pass in your parameters.
Here is an example from Google:
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
I would also take a look at this link to read more about Content Providers.