I want to load data from server and show in my application (RecyclerView), for this job, when the application starts it shows 10 posts and when scrolling recyclerView show another post .

I want when users click on Favorite button, save this and when go to Favorite page show this items!
My items loaded from server (json) but and I want save favorite items in android device not server!

I want save items (posts) ID and when go to favorite page, fetch posts from server.

How can I it? I am amateur please help me. Thanks all <3

what I want to achieve is Upon click, app shows toasts message "TEXT1", and keeps showing TEXT1 until finish other function call 20 times at a random interval/delay. After calling function,shows toast message "TEXT2". My problem: TEXT1 does not show until app finishes function call. and TEXT1 keeps up for the time it takes to execute 20 times function call,then TEXT2 shows up.My code:

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.example:
                Toast.makeText(getBaseContext(),"Please wait until finish",Toast.LENGTH_SHORT).show();
                int i = 0;
                while (i <= 19 ){

                    int delay = new Random().nextInt(5000);
                    try {
                            Thread.sleep(delay);
                        } catch(InterruptedException ex) {
                            Thread.currentThread().interrupt();
                        }
                    //some function here
                    i++;
                }
                Toast.makeText(getBaseContext(),"Finished",Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

I am encountering a lot of my users complaining about their app freezing, and I suspect it is due to the network requests.

It has been hard to reproduce tho, but my solution has been to add a subscribeOn and observeOn to my custom mapArray function, which is chained after the moya request but before any ui usage.

Questions:

  • does this sequence of calling subscribeOn and observeOn make sense as an approach to solve the freezing issue?
  • it feels weird to be calling subscribeOn after the function to call, but i do not want to wrap my request in yet another dispatch block

Overall, i am pretty confused by thread switching in Moya and Alamofire, and hoping someone can shine some light:

PS: I have read up the issue in moya discussing this, and it mentions that alamofire does the network call on the main thread, which is also confusing to me

PS2: this solution is also based on this blog post, but my question, besides the above ones, is why it might advocate for running the network call on a background thread when it does not appear to be the case for the Moya guys.

 // How the network call is 
 func load() -> Observable<Void> {
    let apiProvider: RxMoyaProvider()
    return apiProvider.request(.GetFeed(page: 1))
      .mapArray(Question.self, keyPath: "questions")
      .doOnNext { questions, pagination in
        // updates the results to a variable, which is bound to the UI
        self.pagination = pagination
        self.data.value = questions
      }
      .flatMapLatest { _ in
        Observable.just()
      }
  }

 // My observable extension, a function to map responses to a 
extension ObservableType where E == Response {

  func mapObject<T: Mappable>(type: T.Type, keyPath: String) -> Observable<T> {
    return
      // this makes sure that the beginning of the call is made on the background thread. but it can be changed later, so we need an observe on later on
      subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
      .doOnError(networkFailureCallback)
      .filterSuccessfulStatusCodes()
      .handleUnauthorizedRequest()
        // this makes sure that the mapping happens on a background thread as well
      .observeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
      .flatMap { response -> Observable<T> in
        return Observable.just(try response.mapObject(T.self, keyPath: keyPath))
      }
  }



// In my viewController
dataAccessor.load()
  .observeOn(MainScheduler.instance)
  .subscribe { error in
    // do actions
  }
  .addDisposableTo(self.disposeBag)

}

There is custom textfield cell which being added to tableview as per user input. Something similar to Contact book when user add multiple mobile numbers. Nib is register with table view using below code.

[self.tableView registerNib:[UINib nibWithNibName:@"TextFieldTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:textFieldTableViewCellIdentifier];

The method which add dynamic cell

-(void)addAccoladesValue { NSMutableArray *DataArray = [self.tableData[SectionTagAccolades-1][sectionDataKey] mutableCopy]; NSMutableArray *DataValueArray = [self.tableData[SectionTagAccolades-1][sectionDataValue] mutableCopy]; self.accoladesArray = self.accoladesArray ? self.accoladesArray : [NSMutableArray new]; TextFieldTableViewCell *accoladesCell = [self setupTextField:self.accoladesArray tag:TextFieldTagFirstName placeholder:@"Description" cellTextFieldIdentifier:textFieldTableViewCellIdentifier]; accoladesCell.hidden = NO; [DataArray addObject:accoladesCell]; [DataValueArray addObject:@""]; self.tableData[SectionTagAccolades-1][sectionDataKey] = DataArray; self.tableData[SectionTagAccolades-1][sectionDataValue] = DataValueArray; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:SectionTagAccolades-1]] withRowAnimation:UITableViewRowAnimationAutomatic]; [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:SectionTagAccolades-1]] withRowAnimation:UITableViewRowAnimationTop]; [self.tableView endUpdates]; } Code seems to work expected but some times cell disappear and for few times it the newly added cell is getting added to top section which is wrong. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TextFieldTableViewCell cell = (TextFieldTableViewCell)self.tableData[indexPath.section][sectionDataKey][indexPath.row]; if ([cell isKindOfClass:[TextFieldTableViewCell class]]) { cell.textfield.tag = indexPath.row; cell.textfield.superview.tag = indexPath.section; cell.textfield.text = self.tableData[indexPath.section][sectionDataValue][indexPath.row];

}
cell.hidden = NO;
[cell setNeedsUpdateConstraints];
[cell setNeedsLayout];
return cell;

} What could you be possible reasons for this weird behaviour ? any suggestions or input will highly appericiate.

Thanks for your value time.

I have a service that runs to get user current location through LocationListener. I stop the service on the activity's onDestroy() but this method is only called when the user hits the back button to exit the app. I want the service to stop both when the user hits the back button to exit and when they hit the home button. However, as far as i know, there's no way to intercept the home button. How do people deal with this issue? Is it normal to leave the location listener running after the user hits the home button?

I am using AIDE to programming in my android phone And i must download any support library to use it in my project libs folder So i want to tell me how to download google support libraries Like firebase.google.jar And google gms library and other libraries Is there a link? Help me how to download it?

I added a ListView to my app and i determined the entries of it and they appeared on the screen but when i gave the ListView an id the entries disappeared and a list of default items appeared like : item 1 item 2 item 3 ..

I m working on a xamarin android app where am required to store pictures of users. One user can see pictures(at least profile picture) of another user. To accomplish this, I thought of storing all images(including) the profile pic uploaded by the user on each user's device storage. But I couldn't figure out how one user is able to see other user's profile pic if they are stored locally on each users device storage. Or may be I didn't uderstand. Can you guys help? I would very much appreciate any ideas or directions.

Animations I use in my applications don't work for the first time , but after that if I go back and forth between activities and stuff (so animation code invokes again) , they work fine. This applies to all kind of animations. Like the default FAB hide&show , shared element transition , circular reveal... My english isn't good so I hope you got the point.

What may be causing this? In case the activities were doing heavy work at start so animations couldn't be shown , I also tried using animations in an empty project. Still didn't work.

i'm trying to make a photo crop app and i want to load a large size image and scale it to to 480 Width and 800 Height (keep aspect ratio) but the problem is if i scale bitmap it shrinks image and when i save it the result get low quality so i decided to scale its canvas to keep bitmap original size. i need to keep original size but scale the image to fit in screen?

here is my code:

public void setBitmap(Bitmap bitmap) {

finalBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
myCanvas = new Canvas(finalBitmap);
myCanvas.drawBitmap(bitmap, 0, 0, null);
myCanvas.scale(scaleFactor,scaleFactor);
isLoaded = true;
}

draw method:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (isLoaded)
        canvas.drawBitmap(finalBitmap, 0, 0, null);

}

i changed scalefactor with 0.9f ,480,... but non of them had effect on bitmap

I have a mobile app witch has a feature to recive by bluethoot a command to do stuffs. What I dont know is how to buy only this bluethoot device. There are some like flic.io, but I want my brand to use with the app. There are generic chips with bluethoot witch I can put into a plastic recipient with buttons like the selfies? What is the name of this kind of devices???

Thank you.

In Java / Android do you typically place the field names in the object classes or does everything go in the same DatabaseHelper class?

E.g. referring to SomeObject.FIELD_NAME or DatabaseHelper.SOMEOBJECT_COL_FIELD_NAME or some thing similar.

I'm not using an ORM if that impacts anything.

I have a RecyclerView whose adapter fetches details about a place ID using the Google Places API. The adapter then displays those details (eg. place address) in each element of the RecyclerView.

Is there a recommended way to achieve this asynchronously? In my current solution, the place addresses are sometimes displayed in the incorrect RecyclerView element when the user scrolls up or down. Also when tapping on a RecyclerView element to go to the detail screen, then going back to the original screen, some of the place addresses are missing in the RecyclerView (presumably there is a delay when the details are still being fetched from the Places API).

public void onBindViewHolder(final ViewHolder v, int position) {
    Places.GeoDataApi.getPlaceById(googleApiClient, placeID)
            .setResultCallback(new ResultCallback<PlaceBuffer>() {
                @Override
                public void onResult(PlaceBuffer places) {
                    Place place = places.get(0);

                    // Display address in the RecyclerView element
                    v.address.setText(place.getName());
                }
     }

I'm making an app that uses a bottom navigation bar (BottomBar) on its MainActivity. A FrameLayout is positioned above the BottomBar. Every time an icon in the bottom bar is clicked, the tab's fragment is inserted into the FrameLayout using FragmentTransaction's replace() function. That inserted fragment contains ViewPager, which results in more fragment launching and caching. Right now, there is only one Activity but many Fragments. I haven't load any data and I'm already receiving a OutOfMemory Exception even after setting the maxHeapSize to 4gb.

What can I do to improve the performance without changing the UI (still have a bottom navigation bar and each tab contains a viewpager)?

A have a list of Strings, lets say { "1", "2", "3" }

When using ArrayAdapters I know how to add these strings to a ListView. I also know how to strike out some items on click using OnItemClick.

What I don't understand is how to strike out items when the list is being populated. Basically when the ListView loads, some items should be striked out and some not.

I've played around with getAdapter and notifyDataSetChanged to no avail.

How would I go about doing this? The information on the internet is not so good.

I have a question about doing POST, PATCH, and PUT requests when using Alamofire and AlamofireObjectMapper. For example, lets say that I am doing a POST request to to send a object to a server. Can I pass a mapping as parameters for the request. Does it work similar to how RestKit encodes parameters into the body of the request as JSON?

I have a TableView and a Search Controller. They both work perfectly with regards to displaying the info, searching, etc. The problem arises when you go to select one of the cells.

In my code, there are 4 ways you can select the cell... If a bool isAboutNewPost == true / false, and if the search is active or not. If the search controller is active, I am using the data from a filtered array.

When you select a cell and the search controller is not active, it works perfectly. When you select a cell and the search controller is active, but the bool is false, it works perfectly. When you select a cell and the search controller is active and the bool is true, it crashes. I have no clue why, because it is almost identical code.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //
    self.resultSearchController.endEditing(true)

    switch(segmentControl.selectedSegmentIndex)
    {
    case 0:
        if self.theResultSearchController.active {


            self.theResultSearchController.hidesNavigationBarDuringPresentation = false

            print("it is in search")
            let indexPath = tableView.indexPathForSelectedRow

            let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! NewAddPostTableViewCell
            theResultSearchController.active = false

            print("Going to Did Select Name!")
            //            self.performSegueWithIdentifier("transferToAddChinUp", sender: currentCell.name.text)

            let sb = UIStoryboard(name: "Main", bundle: nil)

            if self.isAboutNewPost == true {

                print("There was a new post.")
                let messagesVC = sb.instantiateViewControllerWithIdentifier("AddChinUpScreen") as! AddChinUpViewController
                messagesVC.userObjectId = currentCell.nameLabel.text
                messagesVC.thereWasJustANewPost = true
                print("i got to right here.")
                self.navigationController?.pushViewController(messagesVC, animated: true)

                // new line
                //self.performSegueWithIdentifier("transferToAddChinUp", sender: currentCell.nameLabel.text)

            } else {
                print("There wasn't a new post.")
                let messagesVC = sb.instantiateViewControllerWithIdentifier("AddChinUpScreen") as! AddChinUpViewController
                messagesVC.userObjectId = currentCell.nameLabel.text
                self.navigationController?.pushViewController(messagesVC, animated: true)
                //self.performSegueWithIdentifier("didSelectName", sender: currentCell.nameLabel.text)

            }

        } else {

            if self.isAboutNewPost == true {
                print("it is not in search")
                let indexPath = tableView.indexPathForSelectedRow

                let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! NewAddPostTableViewCell

                print("Going to transferToAddChinUp!")
                self.performSegueWithIdentifier("transferToAddChinUp", sender: currentCell.nameLabel.text)
            } else {
                print("it is not in search")
                let indexPath = tableView.indexPathForSelectedRow

                let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! NewAddPostTableViewCell

                print("Going to Did Select Name!")
                self.performSegueWithIdentifier("didSelectName", sender: currentCell.nameLabel.text)
            }



        }
        break

    case 1:
        if self.theResultSearchController.active {


            self.theResultSearchController.hidesNavigationBarDuringPresentation = false

            print("it is in search")
            let indexPath = tableView.indexPathForSelectedRow

            let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! NewAddPostTableViewCell
            theResultSearchController.active = false

            print("Going to Did Select Name!")
            //            self.performSegueWithIdentifier("transferToAddChinUp", sender: currentCell.name.text)

            let sb = UIStoryboard(name: "Main", bundle: nil)

            if isAboutNewPost == true {
                print("There was a new post!!!!!!")
                let messagesVC = sb.instantiateViewControllerWithIdentifier("AddChinUpScreen") as! AddChinUpViewController
                messagesVC.userObjectId = currentCell.nameLabel.text
                messagesVC.thereWasJustANewPost = true
                self.navigationController?.pushViewController(messagesVC, animated: true)
               // self.performSegueWithIdentifier("transferToAddChinUp", sender: currentCell.nameLabel.text)
            } else {
                let messagesVC = sb.instantiateViewControllerWithIdentifier("AddChinUpScreen") as! AddChinUpViewController
                messagesVC.userObjectId = currentCell.nameLabel.text
                self.navigationController?.pushViewController(messagesVC, animated: true)
              //  self.performSegueWithIdentifier("didSelectName", sender: currentCell.nameLabel.text)

            }

        } else {

            if isAboutNewPost == true {
                print("it is not in search")
                let indexPath = tableView.indexPathForSelectedRow

                let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! NewAddPostTableViewCell

                print("Going to transferToAddChinUp!")
                self.performSegueWithIdentifier("transferToAddChinUp", sender: currentCell.nameLabel.text)
            } else {
                print("it is not in search")
                let indexPath = tableView.indexPathForSelectedRow

                let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! NewAddPostTableViewCell

                print("Going to Did Select Name!")
                self.performSegueWithIdentifier("didSelectName", sender: currentCell.nameLabel.text)
            }


        }
        break

    default:
        break
    }

    //AddChinUpScreen

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "didSelectName" {

        let completeSignUpVC = segue.destinationViewController as! AddChinUpViewController
        let selectedRowIndex = self.theTableView.indexPathForSelectedRow
        let currentCell = theTableView.cellForRowAtIndexPath(selectedRowIndex!) as! NewAddPostTableViewCell
        completeSignUpVC.userObjectId = currentCell.nameLabel.text

    } else if segue.identifier == "transferToAddChinUp" {
        let completeSignUpVC = segue.destinationViewController as! AddChinUpViewController
        //let selectedRowIndex = self.theTableView.indexPathForSelectedRow
        //let currentCell = theTableView.cellForRowAtIndexPath(selectedRowIndex!) as! NewAddPostTableViewCell

        completeSignUpVC.userObjectId = sender as! String
        completeSignUpVC.thereWasJustANewPost = true
    } else if segue.identifier == "tappedOnProfilePicture" {
        let completeSignUpVC = segue.destinationViewController as! AddChinUpViewController

        completeSignUpVC.userObjectId = sender as! String
        if self.isAboutNewPost == true {
            completeSignUpVC.thereWasJustANewPost = true

        } else {
            //completeSignUpVC
        }
    }

}

Here is the Error:

   Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIFullscreenPresentationController adaptivePresentationController]: unrecognized selector sent to instance 0x7febc34cdf60'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001072e3f65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001069d5deb objc_exception_throw + 48
    2   CoreFoundation                      0x00000001072ec58d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x0000000107239f7a ___forwarding___ + 970
    4   CoreFoundation                      0x0000000107239b28 _CF_forwarding_prep_0 + 120
    5   UIKit                               0x00000001084fb389 -[UISearchController _searchPresentationController] + 134
    6   UIKit                               0x00000001080d7755 -[_UISearchControllerTransplantSearchBarAnimator animateTransition:] + 215
    7   UIKit                               0x0000000107c81ede __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 2638
    8   UIKit                               0x0000000107b2e4be _runAfterCACommitDeferredBlocks + 317
    9   UIKit                               0x0000000107b407ee _cleanUpAfterCAFlushAndRunDeferredBlocks + 95
    10  UIKit                               0x0000000107b4c4e6 _afterCACommitHandler + 90
    11  CoreFoundation                      0x000000010720f9d7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    12  CoreFoundation                      0x000000010720f947 __CFRunLoopDoObservers + 391
    13  CoreFoundation                      0x000000010720559b __CFRunLoopRun + 1147
    14  CoreFoundation                      0x0000000107204e98 CFRunLoopRunSpecific + 488
    15  GraphicsServices                    0x000000010a6c0ad2 GSEventRunModal + 161
    16  UIKit                               0x0000000107b22676 UIApplicationMain + 171
    17  Chin Up 2                           0x0000000104d180fd main + 109
    18  libdyld.dylib                       0x0000000109a5792d start + 1
    19  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

I like AvPlayerViewController, it overlays a nice video player with a "Done" button where ever in my app I segue to it. It has a player property of type AvPlayer.

I would like to use AvQueuePlayer instead, who's base class is AvPlayer. It seems though, to use AvQueuePlayer I will have to develop my on UI, the pop over, the "Done" that all just works with the AvPlayerViewController.player

I can of course assign an instance of AvQueuePlayer to self.Player where self is AvPlayerViewController but the AvQueuePlayer instance is just downcasted to an AvPlayer.

I can't extend aka inherit from AvPlayerViewController because I am still stuck making my own video player UI.

Anyway I can use or do a special cast of AvQueuePlayer and use it as my player for an AvPlayerViewController?

This question already has an answer here:

I have an iPhone app (iOS/Swift) Xcode project. I have an image called map_pin_icon.svg saved to my Desktop (from wikicommons @ https://commons.wikimedia.org/wiki/File:Map_pin_icon.svg).

I drag and drop it into my Xcode project's Assets.xcassets folder, and it shows up in the list. When I click on map_pin_icon in the list (below the app icon set) and it says the image set has a Universal image for Any/Any size, but the icon it shows is the blank file icon, not the icon in the image file. If I select the Universal image and press spacebar it shows the correct icon in a "quick view" window.

In ViewController.swift I have in viewDidLoad():

    let theImage = UIImage(named: "map_pin_icon.svg")
    if(theImage == nil) {
        print("NIL IS NOT ALLOWED")
    } else {
        print("\(theImage)")
    }
    let theImageView = UIImageView(image: theImage)

And sure enough when I run the simulator (iOS 8.0 on iPhone 4s, which is my minimum desired compatibility device) I get the following output log:

    NIL IS NOT ALLOWED

Where am I going wrong? Thanks in advance.

I'm developing an auto-update feature for my Java app which I'll eventually distribute, so I need to utilize an SFTP server which will hold the artifacts. SCP is an alternative but supposedly less interactive.

Which security measures should I take into consideration, in terms of setting up an SFTP server and uploading to it securely. Is simply purchasing a hosting account from NameCheap, GoDaddy, etc. all that's required? I'll be transferring very sensitive data so I need to ensure security. Our customer base is small but likely to grow so perhaps a dedicated server is better suited, or maybe just SSH keys on an SFTP server?

No sensitive customer data will be stored, only source code/artifacts. I'd prefer a reputable company to remain responsible for ensuring up-time, security, and speed.

I develop a high performance program to generate optimal addition chains. An addition chain is a sequence of numbers starting with 1 where each element in the sequence apart from the first is the sum of two prior elements. Optimal chains for a given target (the last value in the sequence) have the smallest number of elements and must be strictly increasing. In a simple implementation of a program (my actual program uses a different method) if we have a sequence of a_0,a_1,...,a_i we want to find all a_{i+1} = a_j + a_k > a_i with i >= j >= k >= 0 . We also typically know bounds calculated up front such that a_{i+1} >= b_{i+1}. It helps performance to eliminate duplicate a_{i+1} values since the same number can be created in multiple ways. For example:

1 2 3 4=(2+2 or 3+1)

It only just occurred to me (despite it being so simple) that you can eliminate duplicates fast by merging these streams of numbers:

s1: a_i + a_i, a_i + a_{i-1}, a_i + a_{i-2} + ... + a_i + a_0

s2: a_{i-1} + a_{i-1}, a_{i-1} + a_{i-2}, a_{i-1} + a_{i-3} + ... + a_{i-1} + a_0

s3: a_{i-2} + a_{i-2}, a_{i-2} + a_{i-3}, a_{i-2} + a_{i-4} + ... + a_{i-2} + a_0

...

It turns out the number of these streams is very limited by the mathematics. Having the element a_{i+1} be generated in decreasing order really helps with some optimizations and as a heuristic searching first using higher numbers is very effective. I would need to generalize this idea to handle sums of more than two prior elements. So for example I would want to merge all pair sums with all triplet sums etc. Once again though the maximal number of prior elements in each sum is very limited by the mathematics. I don't currently eliminate duplicates in the fastest algorithm but this is likely a good optimization if I can do it at a low enough cost.

So my question is has anyone seem similar things done in other domains?