问:
How to give space between section and row of UITableView after expanding the tableview and remove space after collapse of tableview
I am designing a uitableview with multiple sections and row in that section i have expand and collapse functionality for that.Now when the row is expanded I have give space between row and section like below image.

here is my code for expand and collapsing the the section.and for section i use header view.

```<code>-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return menuarray.count;
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  //return menuarray.count;
if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
{
     NSArray *arr=[menuarray[section] valueForKey:@"menu"];
    return arr.count;
}else{
    return 0;
}
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {

static NSString *CellIdentifier = @"MenudetailsTblCell";

menudetailscell = ( MenudetailsTblCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    [self.tblview registerNib:[UINib nibWithNibName:@"MenudetailsTblCell" bundle:nil]
//forCellReuseIdentifier:@"MenudetailsTblCell"];
if (menudetailscell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MenudetailsTblCell" owner:self options:nil];
    menudetailscell = [nib objectAtIndex:0];

}

if (menudetailscell == nil)
{
    menudetailscell = [[MenudetailsTblCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
     }
menudetailscell.contentView.layer.cornerRadius = 5;
menudetailscell.contentView.layer.masksToBounds = YES;
NSArray *arr=[menuarray[indexPath.section] valueForKey:@"menu"];
menudetailscell.typelbl.text=[[arr objectAtIndex:indexPath.row]valueForKey:@"name"];
 menudetailscell.describtionlbl.text=[[arr objectAtIndex:indexPath.row]valueForKey:@"description"];
NSString *cost=[NSString stringWithFormat:@"%@%@",[[arr objectAtIndex:indexPath.row]valueForKey:@"price"],@".00"];
    NSString *imgid=[NSString stringWithFormat:@"%@",[[arr objectAtIndex:indexPath.row]valueForKey:@"idmenus"]];
NSString *tax=[NSString stringWithFormat:@"%@",[[arr objectAtIndex:indexPath.row]valueForKey:@"tax"]];
if ([tax isEqualToString:@"tax"]) {
  menudetailscell.taxlbl.text=@"(*Inclusive all taxes)";
}else{

menudetailscell.taxlbl.text=@"(*Exclusive all taxes)";
}
menudetailscell.ratelbl.text=[NSString stringWithFormat:@"%@ %@",[[arr objectAtIndex:indexPath.row]valueForKey:@"country"],cost];

NSString *typeimgUrl1 = [NSString stringWithFormat:@"%s/presignin/menu/showMedia?idMenu=%@",urlPath,imgid];
NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];
menudetailscell.imgview.imageURL=imageURL;

menudetailscell.selectionStyle = UITableViewCellSelectionStyleNone;
return menudetailscell;

 }

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 70.0f;
 }

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

static NSString *CellIdentifier = @"Menusectioncell";

menusectioncell = ( Menusectioncell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (menusectioncell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"Menusectioncell" owner:self options:nil];
    menusectioncell = [nib objectAtIndex:0];

   }

if (menusectioncell == nil)
{
    menusectioncell = [[Menusectioncell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
   }

if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
{
    menusectioncell.Sectiomtitlebtn.selected = YES;
     menusectioncell.dotlbl.hidden=NO;
}
else{
menusectioncell.dotlbl.hidden=YES;
}
menusectioncell.Sectiomtitlebtn.tag=section;

menusectioncell.dotlbl.layer.cornerRadius = menusectioncell.dotlbl.frame.size.height/2;
menusectioncell.dotlbl.layer.masksToBounds = YES;

[menusectioncell.Sectiomtitlebtn addTarget:self action:@selector(btnTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];
NSString *btntitle=[menuarray[section] valueForKey:@"catagory"];
itemarr=[menuarray[section] valueForKey:@"menu"];
NSString *items=[itemarr[0] valueForKey:@"name"];
menusectioncell.sectiontitleilb.text=btntitle;
menusectioncell.itemslbl.text=[NSString stringWithFormat:@"%@.,etc...",items];
menusectioncell.selectionStyle = UITableViewCellSelectionStyleNone;
return menusectioncell.contentView;

 }

  -(IBAction)btnTapShowHideSection:(UIButton*)sender
 {

if (!sender.selected)
{
    if (!isMultipleExpansionAllowed) {
        [arrSelectedSectionIndex replaceObjectAtIndex:0 withObject:[NSNumber numberWithInteger:sender.tag]];
    }else {
        [arrSelectedSectionIndex addObject:[NSNumber numberWithInteger:sender.tag]];
    }
    menusectioncell.dotlbl.hidden=YES;
    sender.selected = YES;
}
else{
    sender.selected = NO;
    menusectioncell.dotlbl.hidden=NO;
    if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:sender.tag]])
    {
        [arrSelectedSectionIndex removeObject:[NSNumber numberWithInteger:sender.tag]];
    }
}

if (!isMultipleExpansionAllowed) {
    [_tblview reloadData];
}else {
    [_tblview reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];

}

}

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

return 75;

 }
</code>```

I just wanted to give space between  maincourse  and down details for headerview and rows I am using 2 different cell. Please help me out to solve this.

答:
then just return more height in heightForHeaderInSection. For example 80 instead of 70. that's it!

And you could manage height of menusectioncell.contentView also according to header height!

Body:
I am designing a uitableview with multiple sections and row in that section i have expand and collapse functionality for that.Now when the row is expanded I have give space between row and section like below image.

here is my code for expand and collapsing the the section.and for section i use header view.

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return menuarray.count;
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  //return menuarray.count;
if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
{
     NSArray *arr=[menuarray[section] valueForKey:@"menu"];
    return arr.count;
}else{
    return 0;
}
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {

static NSString *CellIdentifier = @"MenudetailsTblCell";

menudetailscell = ( MenudetailsTblCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    [self.tblview registerNib:[UINib nibWithNibName:@"MenudetailsTblCell" bundle:nil]
//forCellReuseIdentifier:@"MenudetailsTblCell"];
if (menudetailscell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MenudetailsTblCell" owner:self options:nil];
    menudetailscell = [nib objectAtIndex:0];

}

if (menudetailscell == nil)
{
    menudetailscell = [[MenudetailsTblCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
     }
menudetailscell.contentView.layer.cornerRadius = 5;
menudetailscell.contentView.layer.masksToBounds = YES;
NSArray *arr=[menuarray[indexPath.section] valueForKey:@"menu"];
menudetailscell.typelbl.text=[[arr objectAtIndex:indexPath.row]valueForKey:@"name"];
 menudetailscell.describtionlbl.text=[[arr objectAtIndex:indexPath.row]valueForKey:@"description"];
NSString *cost=[NSString stringWithFormat:@"%@%@",[[arr objectAtIndex:indexPath.row]valueForKey:@"price"],@".00"];
    NSString *imgid=[NSString stringWithFormat:@"%@",[[arr objectAtIndex:indexPath.row]valueForKey:@"idmenus"]];
NSString *tax=[NSString stringWithFormat:@"%@",[[arr objectAtIndex:indexPath.row]valueForKey:@"tax"]];
if ([tax isEqualToString:@"tax"]) {
  menudetailscell.taxlbl.text=@"(*Inclusive all taxes)";
}else{

menudetailscell.taxlbl.text=@"(*Exclusive all taxes)";
}
menudetailscell.ratelbl.text=[NSString stringWithFormat:@"%@ %@",[[arr objectAtIndex:indexPath.row]valueForKey:@"country"],cost];

NSString *typeimgUrl1 = [NSString stringWithFormat:@"%s/presignin/menu/showMedia?idMenu=%@",urlPath,imgid];
NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];
menudetailscell.imgview.imageURL=imageURL;

menudetailscell.selectionStyle = UITableViewCellSelectionStyleNone;
return menudetailscell;

 }

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 70.0f;
 }

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

static NSString *CellIdentifier = @"Menusectioncell";

menusectioncell = ( Menusectioncell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (menusectioncell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"Menusectioncell" owner:self options:nil];
    menusectioncell = [nib objectAtIndex:0];

   }

if (menusectioncell == nil)
{
    menusectioncell = [[Menusectioncell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
   }

if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:section]])
{
    menusectioncell.Sectiomtitlebtn.selected = YES;
     menusectioncell.dotlbl.hidden=NO;
}
else{
menusectioncell.dotlbl.hidden=YES;
}
menusectioncell.Sectiomtitlebtn.tag=section;

menusectioncell.dotlbl.layer.cornerRadius = menusectioncell.dotlbl.frame.size.height/2;
menusectioncell.dotlbl.layer.masksToBounds = YES;

[menusectioncell.Sectiomtitlebtn addTarget:self action:@selector(btnTapShowHideSection:) forControlEvents:UIControlEventTouchUpInside];
NSString *btntitle=[menuarray[section] valueForKey:@"catagory"];
itemarr=[menuarray[section] valueForKey:@"menu"];
NSString *items=[itemarr[0] valueForKey:@"name"];
menusectioncell.sectiontitleilb.text=btntitle;
menusectioncell.itemslbl.text=[NSString stringWithFormat:@"%@.,etc...",items];
menusectioncell.selectionStyle = UITableViewCellSelectionStyleNone;
return menusectioncell.contentView;

 }

  -(IBAction)btnTapShowHideSection:(UIButton*)sender
 {

if (!sender.selected)
{
    if (!isMultipleExpansionAllowed) {
        [arrSelectedSectionIndex replaceObjectAtIndex:0 withObject:[NSNumber numberWithInteger:sender.tag]];
    }else {
        [arrSelectedSectionIndex addObject:[NSNumber numberWithInteger:sender.tag]];
    }
    menusectioncell.dotlbl.hidden=YES;
    sender.selected = YES;
}
else{
    sender.selected = NO;
    menusectioncell.dotlbl.hidden=NO;
    if ([arrSelectedSectionIndex containsObject:[NSNumber numberWithInteger:sender.tag]])
    {
        [arrSelectedSectionIndex removeObject:[NSNumber numberWithInteger:sender.tag]];
    }
}

if (!isMultipleExpansionAllowed) {
    [_tblview reloadData];
}else {
    [_tblview reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationAutomatic];

}

}

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

return 75;

 }

I just wanted to give space between  maincourse  and down details for headerview and rows I am using 2 different cell. Please help me out to solve this.


来源: stackexchange

问:
gst-launch-1.0 can't stream audio/video through UDP and display it on a window simultaneously
I am successfully streaming a file (audio/video) through UDP on Windows and watching it on another machine with VLC (this was covered on Stackoverflow before):

```<code>gst-launch-1.0 -v filesrc location=video.mkv ! decodebin name=dec ! videoconvert ! x264enc ! video/x-h264 ! mpegtsmux name=mux ! queue ! udpsink host=127.0.0.1 port=5000 sync=true dec. ! queue ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.
</code>```

You can test this on VLC: Media > Open Network Stream > Network URL > udp://@:5000

However, while the video is being streamed I would like to also display it on a window, so I could watch the stream myself (no audio needed).

To accomplish this, I started with a series of small experiments so I could change the original pipeline without any surprises. If you are reading this question you know my plan didn't work so well.

My first experiment was to display just the video on single window:

```<code>gst-launch-1.0 -v filesrc location=video.mkv ! decodebin ! autovideosink
</code>```

Then, I changed it to display the same video on 2 windows, to make sure I understood how to work with multithreading:

```<code>gst-launch-1.0 -v filesrc location=video.mkv ! decodebin name=dec ! queue ! tee name=t t. ! queue ! videoconvert ! autovideosink t. ! autovideosink
</code>```

Finally, it came the moment to blend those 2 parts together and stream the video through the network while it is displayed locally. The result is not what I expected, of course: only the first frame appears to be streamed and then everything freezes:

```<code>gst-launch-1.0 -v filesrc location=video.mkv ! decodebin name=dec ! tee name=t ! queue ! autovideosink t. ! queue ! videoconvert ! x264enc ! video/x-h264 ! mpegtsmux name=mux ! queue ! udpsink host=127.0.0.1 port=5000 sync=true dec. ! queue ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.
</code>```

It seems that the data is not flowing through the pipeline anymore (for some reason unknown to me) and my attempt to add autovideosink broke everything.

Any tips on how to do this correctly?

答:
The right moment to split the data is right after filesrc:

```<code>gst-launch-1.0 -v filesrc location=video.mkv ! tee name=t ! queue ! decodebin ! autovideosink t. ! queue ! decodebin name=dec ! videoconvert ! x264enc ! video/x-h264 ! mpegtsmux name=mux ! queue ! udpsink host=127.0.0.1 port=5000 sync=true dec. ! queue ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.
</code>```

So the data flows directly to autovideosink before anything else happens while the other thread also joins at this very same moment, carrying the data flow to queue and the 2nd decodebin.

ContentLicense: CC BY-SA 3.0

Body:
I am successfully streaming a file (audio/video) through UDP on Windows and watching it on another machine with VLC (this was covered on Stackoverflow before):

gst-launch-1.0 -v filesrc location=video.mkv ! decodebin name=dec ! videoconvert ! x264enc ! video/x-h264 ! mpegtsmux name=mux ! queue ! udpsink host=127.0.0.1 port=5000 sync=true dec. ! queue ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.

You can test this on VLC: Media > Open Network Stream > Network URL > udp://@:5000

However, while the video is being streamed I would like to also display it on a window, so I could watch the stream myself (no audio needed).

To accomplish this, I started with a series of small experiments so I could change the original pipeline without any surprises. If you are reading this question you know my plan didn't work so well.

My first experiment was to display just the video on single window:

gst-launch-1.0 -v filesrc location=video.mkv ! decodebin ! autovideosink

Then, I changed it to display the same video on 2 windows, to make sure I understood how to work with multithreading:

gst-launch-1.0 -v filesrc location=video.mkv ! decodebin name=dec ! queue ! tee name=t t. ! queue ! videoconvert ! autovideosink t. ! autovideosink

Finally, it came the moment to blend those 2 parts together and stream the video through the network while it is displayed locally. The result is not what I expected, of course: only the first frame appears to be streamed and then everything freezes:

gst-launch-1.0 -v filesrc location=video.mkv ! decodebin name=dec ! tee name=t ! queue ! autovideosink t. ! queue ! videoconvert ! x264enc ! video/x-h264 ! mpegtsmux name=mux ! queue ! udpsink host=127.0.0.1 port=5000 sync=true dec. ! queue ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.

It seems that the data is not flowing through the pipeline anymore (for some reason unknown to me) and my attempt to add autovideosink broke everything.

Any tips on how to do this correctly?

Body:
The right moment to split the data is right after filesrc:

gst-launch-1.0 -v filesrc location=video.mkv ! tee name=t ! queue ! decodebin ! autovideosink t. ! queue ! decodebin name=dec ! videoconvert ! x264enc ! video/x-h264 ! mpegtsmux name=mux ! queue ! udpsink host=127.0.0.1 port=5000 sync=true dec. ! queue ! audioconvert ! voaacenc ! audio/mpeg ! queue ! mux.

So the data flows directly to autovideosink before anything else happens while the other thread also joins at this very same moment, carrying the data flow to queue and the 2nd decodebin.


问:
Java DB / Apache Derby with Android
Can I integrate Java DB or Apache Derby in my Android application? Or any inline or embedded database. Can anyone suggest code for it?
I need some code because i have to make examples, not in theory.

Anyone knows if this databases is supported or not?

I thinks these are the inMobile DB, but i didn't find any related information in Google.

答:
Android includes SQLite, so this is normal choice.

There is an embedded Java database that supports the Android platform: the H2 database. However, support for Android is relatively new, and you probably shouldn't use it, unlike you really need features that SQLite doesn't support.

ContentLicense: CC BY-SA 2.5

Title: Java DB / Apache Derby with Android


问:
Change query from solr4 to solr6
I have a solr search in solr4. This is the url:
solr.int/bweb-solr/coreX/select?q=Tramitaci%C3%B3n&wt=json&indent=true

But when migrate this to solr6 I need add the field in the search to obtains the sames results, ex:
solr.int/bweb-solr/coreX/select?q=status:Tramitaci%C3%B3n&wt=json&indent=true

Can change this option to dont use the field in q paramter?
I have the same default field.

Thaks.

答: You can add/change df parameter in your select request handler, new value of df will be "status". After this you don't need to specify field name with every request. Solr will consider "status" as a default search field for every request.</p>

Title: Change query from solr4 to solr6


问:
UIDatePicker not showing up in UITextField. Swift 3
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

```<code>import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}
</code>```

答: At first glance it seems like you didn't set the delegate for pickerView5?</p>

Body:
I have 5 UITextFields in 1 view controller. The first 4 display a popup UIPickerView populated with data from a corresponding array. When I spin the picker the section is displayed in the text field.

The 5th UITextField displays a popup UIDatepicker but the date and time never show up in the text field.

I have watched countless tutorials and searched this forum for days for and still can't make it work.

What am I doing wrong? Any help would be greatly appreciated.

Here's my code:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView1 = UIPickerView()
    var pickerView2 = UIPickerView()
    var pickerView3 = UIPickerView()
    var pickerView4 = UIPickerView()
    var pickerView5 = UIDatePicker()

    @IBOutlet var mountainTextField: UITextField!
    @IBOutlet var difficultyTextField: UITextField!
    @IBOutlet var runTextField: UITextField!
    @IBOutlet var whenTextField: UITextField!
    @IBOutlet var snowTextField: UITextField!
    @IBAction func whenTextField(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(ViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)
    }

    var mountain = ["A", "B"]
    var difficulty = ["1", "2", "3", "4"]
    var run = ["5", "6", "7", "8"]
    var snow = ["C", "D", "E", "F"]

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView5 = UIDatePicker()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        pickerView1.tag = 0
        pickerView2.tag = 1
        pickerView3.tag = 2
        pickerView4.tag = 3
        pickerView5.tag = 4

        self.mountainTextField.inputView = self.pickerView1;
        self.difficultyTextField.inputView = self.pickerView2;
        self.runTextField.inputView = self.pickerView3;
        self.snowTextField.inputView = self.pickerView4;
        self.whenTextField.inputView = self.pickerView5;
    }

    func datePickerValueChanged(sender:UIDatePicker) {
        let dateFormatter = DateFormatter()

        whenTextField.text = dateFormatter.string(from: sender.date)
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 0 {
            return mountain.count
        } else if pickerView.tag == 1 {
            return difficulty.count
        } else if pickerView.tag == 2 {
            return  run.count
        } else if  pickerView.tag == 3 {
            return snow.count
        }

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 0 {
            return mountain[row]
        } else if pickerView.tag == 1 {
            return difficulty[row]
        } else if pickerView.tag == 2 {
            return run[row]
        } else if pickerView.tag == 3 {
            return snow[row]
        }

        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {
        if pickerView.tag == 0 {
            mountainTextField.text = mountain[row]
        } else if pickerView.tag == 1 {
            difficultyTextField.text = difficulty[row]
        } else if pickerView.tag == 2 {
            runTextField.text = run[row]
        } else if pickerView.tag == 3 {
            snowTextField.text = snow[row]
        }
    }
}


问:
If I delete an image in my application it has to be deleted in the gallery too (using objective C)
I have developed a camera application with all basic functionalities. When you take a picture that image will be saved in the newly created folder but if I delete an image in my application its not getting deleted in that folder. I need to delete it permanently using objective C</p>

答:
In collection view didselect method i getting the url of selected image

```<code> UIImage *viewImage = _myma; // --- mine was made from drawing context
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        // Request to save the image to camera roll
        [library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
            if (error) {
                NSLog(@"error");
            } else {
                NSLog(@"url %@", assetURL);

                NSString *urlString = [assetURL absoluteString];
                selectedurl = urlString;
                //NSLog(@"myurl%@", selectedurl);

            }
</code>```

the in action button used to delete the selected images

```<code> NSURL *deleteurl = [NSURL URLWithString:selectedurl];
       NSArray *arrDelete = [[NSArray alloc] initWithObjects:deleteurl , nil];
       NSEnumerator *asset = [PHAsset fetchAssetsWithALAssetURLs:arrDelete options:nil];

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetChangeRequest deleteAssets:asset];// asset is an array

        } completionHandler:^(BOOL success, NSError *error) {
            NSLog(@"Finished Delete asset. %@", (success ? @"Success." : error));
            if (success) {
                NSLog(@"deleted");
            }
        }];
</code>```

Body:
In collection view didselect method i getting the url of selected image

 UIImage *viewImage = _myma; // --- mine was made from drawing context
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        // Request to save the image to camera roll
        [library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
            if (error) {
                NSLog(@"error");
            } else {
                NSLog(@"url %@", assetURL);

                NSString *urlString = [assetURL absoluteString];
                selectedurl = urlString;
                //NSLog(@"myurl%@", selectedurl);

            }

the in action button used to delete the selected images

 NSURL *deleteurl = [NSURL URLWithString:selectedurl];
       NSArray *arrDelete = [[NSArray alloc] initWithObjects:deleteurl , nil];
       NSEnumerator *asset = [PHAsset fetchAssetsWithALAssetURLs:arrDelete options:nil];

        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetChangeRequest deleteAssets:asset];// asset is an array

        } completionHandler:^(BOOL success, NSError *error) {
            NSLog(@"Finished Delete asset. %@", (success ? @"Success." : error));
            if (success) {
                NSLog(@"deleted");
            }
        }];


问:
How to play a video using the Youtube API with Firebase?
To do this:

1.- I make the instance to firebase

```<code>  mDatabase = FirebaseDatabase.getInstance().getReference().child("Videos");
</code>```

2.- Then I link the layout to the code

```<code>mNoticiasSingleTitle = (TextView)findViewById(R.id.post_titleNoti);
mNoticiasSingleImage = (ImageView) findViewById(R.id.imageView);
mNoticiasSingleVid = (YouTubePlayerView) findViewById(R.id.videoView);
</code>```

3.- I work in onDataChange(DataSnapshot dataSnapshot){}

```<code>   String post_title = (String)dataSnapshot.child("title").getValue();
   String post_image = (String)dataSnapshot.child("image").getValue();
   String post_video = (String)dataSnapshot.child("vid").getValue();

   mNoticiasSingleTitle .setText(post_consejo);
   Picasso.with(VideoAct.this).load(post_image).into(mNoticiasSingleImage);
   //Missing code here
</code>```

To load the image I use picasso and if I want to upload a video of youtube as I can do it, help please, thanks.

答:
Do this.</p>

```<code>youTubePlayerView.initialize("YOUR API KEY",
            new YouTubePlayer.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubePlayer.Provider provider,
                        YouTubePlayer youTubePlayer, boolean b) {

                    youTubePlayer.loadVideo("VIDEO_ID_HERE");
                }
                @Override
                public void onInitializationFailure(YouTubePlayer.Provider provider,
                        YouTubeInitializationResult youTubeInitializationResult) {

                }
    });
</code>```

Body:
To do this:

1.- I make the instance to firebase

  mDatabase = FirebaseDatabase.getInstance().getReference().child("Videos");

2.- Then I link the layout to the code

mNoticiasSingleTitle = (TextView)findViewById(R.id.post_titleNoti);
mNoticiasSingleImage = (ImageView) findViewById(R.id.imageView);
mNoticiasSingleVid = (YouTubePlayerView) findViewById(R.id.videoView);

3.- I work in onDataChange(DataSnapshot dataSnapshot){}

   String post_title = (String)dataSnapshot.child("title").getValue();
   String post_image = (String)dataSnapshot.child("image").getValue();
   String post_video = (String)dataSnapshot.child("vid").getValue();

   mNoticiasSingleTitle .setText(post_consejo);
   Picasso.with(VideoAct.this).load(post_image).into(mNoticiasSingleImage);
   //Missing code here

To load the image I use picasso and if I want to upload a video of youtube as I can do it, help please, thanks.

Body:
Do this.

youTubePlayerView.initialize("YOUR API KEY",
            new YouTubePlayer.OnInitializedListener() {
                @Override
                public void onInitializationSuccess(YouTubePlayer.Provider provider,
                        YouTubePlayer youTubePlayer, boolean b) {

                    youTubePlayer.loadVideo("VIDEO_ID_HERE");
                }
                @Override
                public void onInitializationFailure(YouTubePlayer.Provider provider,
                        YouTubeInitializationResult youTubeInitializationResult) {

                }
    });


问:
wholesale replacement of options html string within select?
I would like to 'toggle' the list of options in a select box.

I have the two sets of options as strings (American states and Canadian Provinces). However, I notice that in the DOM, the select object has no 'innerhtml' property (at least not according to w3schools).

Do I have to go and remove and replace the options one by one? How do I do this?

答: Just add a multiple="multiple" attribute to your select tag if you want multiple selection or add size=".." if you want single selection


问:
Is there syntax just like #region #endregion in Kotlin?
I know I can use #region #endregion to surround a code snippets in C#, is there a similar syntax in Kotlin? Thanks!</p>

```<code>   #region MyRegion
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    #endregion
</code>```

答:
There are more supported styles (https://www.jetbrains.com/help/idea/code-folding.html#supported_comments)

The Netbeans Style

```<code>//<editor-fold desc="YOUR REGION NAME">
fun main(vararg args: String) { ... }
...
//</editor-fold>
</code>```

or the visual studio style

```<code>//region YOUR REGION NAME
fun main(vararg args: String) { ... }
...
//endregion
</code>```

They can be collapsed and expanded in IntelliJ. When it's collapsed, only the description is displayed.

Body:
I know I can use #region #endregion to surround a code snippets in C#, is there a similar syntax in Kotlin? Thanks!

   #region MyRegion
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    #endregion

Body:
There are more supported styles (https://www.jetbrains.com/help/idea/code-folding.html#supported_comments)

The Netbeans Style

//<editor-fold desc="YOUR REGION NAME">
fun main(vararg args: String) { ... }
...
//</editor-fold>

or the visual studio style

//region YOUR REGION NAME
fun main(vararg args: String) { ... }
...
//endregion

They can be collapsed and expanded in IntelliJ. When it's collapsed, only the description is displayed.


问:
OSRM HTTP Queries
I was checking out the a way that I could query OSM using HTTP requests and I found this link where the guy uses this to query OSRM:

```<code>http://router.project-osrm.org/viaroute?loc=49.1716783,-0.34655726&loc=49.17131276,-0.34673758
</code>```

Now when I try this it gives the following error:

```<code>The OSRM Demo server has moved to API Version 5.
Documentation for the new version can be found at
https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md
</code>```

I went there and tried to form my own query using the new rules:

```<code>http://router.project-osrm.org/route/v1/car/{19.411989},{-99.164623}[;{19.412344},{-99.162805}
</code>```

And it does not work either. So my question is am I using this thing right? I am just discovering the service, and heard some people install OSRM servers. I don't really want to install anything just find a way to build HTTP requests, if possible of course.

答:
I think you can get rid of the curly braces in the request and the location should be in lon1,lat1;lon2,lat2 fashion. i.e.,
http://router.project-osrm.org/trip/v1/driving/19.411989,-89.164623;19.412344,-89.162805?overview=false</p>

Title: OSRM HTTP Queries

Body:
I was checking out the a way that I could query OSM using HTTP requests and I found this link where the guy uses this to query OSRM:

http://router.project-osrm.org/viaroute?loc=49.1716783,-0.34655726&loc=49.17131276,-0.34673758

Now when I try this it gives the following error:

The OSRM Demo server has moved to API Version 5.
Documentation for the new version can be found at
https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md

I went there and tried to form my own query using the new rules:

http://router.project-osrm.org/route/v1/car/{19.411989},{-99.164623}[;{19.412344},{-99.162805}

And it does not work either. So my question is am I using this thing right? I am just discovering the service, and heard some people install OSRM servers. I don't really want to install anything just find a way to build HTTP requests, if possible of course.


问:
Android: gridView set not scrollable?
I'm trying to do filter section by gridView. In a wide screen it's fine. But when it's small screen is not working correctly. (One view is two or three times, some is dissapearing) It's because gridView item's shrinking and scroll is appearing. So i trying to remove gridView scroll.

My activity is.

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="fill_parent"
     android:layout_width="fill_parent"
    android:fillViewport="true"
    android:scrollbars="vertical">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:titleTextColor="@android:color/white"
        app:contentInsetStartWithNavigation="0dp">
    </android.support.v7.widget.Toolbar>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="11"
            android:orientation="vertical"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

        <TextView
            android:text="Price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp" />

        <TextView
            android:id="@+id/seekbar_value"
            android:text="Any"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|bottom"
            android:textStyle="bold"/>

        <org.florescu.android.rangeseekbar.RangeSeekBar
            android:id="@+id/range_seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:showLabels="false"
            app:valuesAboveThumbs="false"
            app:barHeight="5dp"
            app:alwaysActive="true"
            app:thumbDisabled="@drawable/seekbar_button"
            app:textAboveThumbsColor="@color/colorPrimary"
            app:defaultColor="@color/colorPrimary"
            app:activeColor="@color/colorButton" />

        <TextView
            android:text="Block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

            <GridView
                android:id="@+id/gridViewBlock"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>

            <TextView
            android:text="Floor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

           <!--  This Grid View is my problem -->
            **<GridView
                android:id="@+id/gridViewFloor"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>**

        </LinearLayout>

        <Button
            android:text="See result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:textStyle="bold"
            android:background="@color/colorButton"
            android:textColor="@android:color/white" />

    </LinearLayout>

</LinearLayout>
</ScrollView>
</code>```

And i programmatically adding gridView items:

```<code>public class FIlterActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RangeSeekBar seekbar;
    private TextView seekbarValue;
    private GridView gridViewBlock;
    private GridView gridViewFloor;
    private FilterButtonAdapter filterBlockAdapter;
    private FilterButtonAdapter filterFloorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter);
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.activity_filter));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        gridViewBlock = (GridView) findViewById(R.id.gridViewBlock);

        filterBlockAdapter = new FilterButtonAdapter(this, Filter.filter_blocks, Filter.blocks_selected);
        gridViewBlock.setAdapter(filterBlockAdapter);

        gridViewBlock.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.blocks_selected.size(); i++){
                    if(value.equals(Filter.blocks_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.blocks_selected.remove(i);
                        if(Filter.blocks_selected.size() == 0){
                            Filter.blocks_selected.add(Filter.filter_blocks[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.blocks_selected.clear();
                        Filter.blocks_selected.add(Filter.filter_blocks[0]);
                        for(int i = 1; i < Filter.filter_blocks.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.blocks_selected.size(); i++){
                            if(Filter.blocks_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.blocks_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.blocks_selected.add(value);}
                filterBlockAdapter.notifyDataSetChanged();
            }
        });

        gridViewFloor = (GridView) findViewById(R.id.gridViewFloor);
        filterFloorAdapter = new FilterButtonAdapter(this, Filter.filter_floors, Filter.floor_selected);
        gridViewFloor.setAdapter(filterFloorAdapter);

        gridViewFloor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.floor_selected.size(); i++){
                    if(value.equals(Filter.floor_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.floor_selected.remove(i);
                        if(Filter.floor_selected.size() == 0){
                            Filter.floor_selected.add(Filter.filter_floors[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.floor_selected.clear();
                        Filter.floor_selected.add(Filter.filter_floors[0]);
                        for(int i = 1; i < Filter.filter_floors.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.floor_selected.size(); i++){
                            if(Filter.floor_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.floor_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.floor_selected.add(value);}
                filterFloorAdapter.notifyDataSetChanged();
            }
        });

        seekbar = (RangeSeekBar)findViewById(R.id.range_seekbar);
        seekbarValue = (TextView)findViewById(R.id.seekbar_value);

        seekbar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
            @Override
            public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                if(String.valueOf(bar.getAbsoluteMaxValue()).equals(maxValue.toString())){

                    if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString()))
                        seekbarValue.setText("Бүх");
                    else {
                        seekbarValue.setText(minValue.toString() + " $ - +");
                    }
                } else if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString())){
                    seekbarValue.setText(maxValue.toString() + " $ - -");
                } else{
                    seekbarValue.setText(minValue.toString() + " $ - " + maxValue.toString() + " $");
                }
            }
        });
    }
}
</code>```

And Filter Button Adapter

```<code>public class FilterButtonAdapter extends BaseAdapter {

    private Context context;
    private final String[] filterValues;
    private List<String> checkedFilterValues = new ArrayList<String>();

    public FilterButtonAdapter(Context context, String[] filterValues, List<String> checkedFilterValues){
        this.context = context;
        this.filterValues = filterValues;
        this.checkedFilterValues = checkedFilterValues;
    }
    @Override
    public int getCount() {
        return filterValues.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        if(convertView == null){

            gridView = new View(context);
            gridView = inflater.inflate(R.layout.layout_button, null);

            final TextView textView = (TextView)gridView.findViewById(R.id.filter_button);
            textView.setText(filterValues[position]);

            boolean contain = false;
            for(int i = 0; i < Filter.blocks_selected.size(); i++){
                if(filterValues[position].equals(checkedFilterValues.get(i)))
                {
                    gridView.setBackgroundResource(R.drawable.button_enabled);
                    contain = true;
                    break;
                }
            }
            if(!contain){
                gridView.setBackgroundResource(R.drawable.button_disabled);
            }
        } else gridView = (View)convertView;
        return gridView;
    }
}
</code>```

Filter class:

```<code>public class Filter {

    public static String price = "any";
    public static long priceMax = 0;
    public static long priceMin = 0;
    public static final String[] filter_blocks = new String[]{
            "any", "A", "B", "C"
    };
    public static final String[] filter_floors = new String[]{
            "any", "1", "2", "3", "4", "5", "6",
            "7", "8", "9", "10", "11", "12+"
    };

    public static List<String> blocks_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static List<String> floor_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static int floor = 10;

}
</code>```

My android studio emulator is 2.7 QVGA API 25

答:
Don't use GridView inside ScrollView, because both has scrolling functionality and due to this it will not work properly.

Use NestedScrollView instead of ScrollView.

NestedScrollView is just like ScrollView, but it supports acting
  as both a nested scrolling parent and child on both new and old
  versions of Android. Nested scrolling is enabled by default.

See documentation.

Update your layout structure as below:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
            app:titleTextColor="@android:color/white"
            app:contentInsetStartWithNavigation="0dp">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/layout_scorll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp">

                <TextView
                    android:text="Price"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="start|bottom"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:layout_marginTop="20dp" />

                <TextView
                    android:id="@+id/seekbar_value"
                    android:text="Any"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center|bottom"
                    android:textStyle="bold"/>

               <org.florescu.android.rangeseekbar.RangeSeekBar
                    android:id="@+id/range_seekbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:showLabels="false"
                    app:valuesAboveThumbs="false"
                    app:barHeight="5dp"
                    app:alwaysActive="true"
                    app:thumbDisabled="@drawable/seekbar_button"
                    app:textAboveThumbsColor="@color/colorPrimary"
                    app:defaultColor="@color/colorPrimary"
                    app:activeColor="@color/colorButton" />

                <TextView
                    android:text="Block"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="start|bottom"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:layout_marginTop="20dp"/>

                <GridView
                    android:id="@+id/gridViewBlock"
                    android:numColumns="auto_fit"
                    android:gravity="center"
                    android:columnWidth="60dp"
                    android:stretchMode="columnWidth"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:nestedScrollingEnabled="false"/>

                <TextView
                    android:text="Floor"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="start|bottom"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:layout_marginTop="20dp"/>

                <!--  This Grid View is my problem -->
                <GridView
                    android:id="@+id/gridViewFloor"
                    android:numColumns="auto_fit"
                    android:gravity="center"
                    android:columnWidth="60dp"
                    android:stretchMode="columnWidth"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:nestedScrollingEnabled="false"/>

            </LinearLayout>

            <Button
                android:text="See result"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:textStyle="bold"
                android:background="@color/colorAccent"
                android:textColor="@android:color/white" />

        </RelativeLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Android: gridView set not scrollable?

Body:
I'm trying to do filter section by gridView. In a wide screen it's fine. But when it's small screen is not working correctly. (One view is two or three times, some is dissapearing) It's because gridView item's shrinking and scroll is appearing. So i trying to remove gridView scroll.

My activity is.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="fill_parent"
     android:layout_width="fill_parent"
    android:fillViewport="true"
    android:scrollbars="vertical">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:titleTextColor="@android:color/white"
        app:contentInsetStartWithNavigation="0dp">
    </android.support.v7.widget.Toolbar>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="11"
            android:orientation="vertical"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

        <TextView
            android:text="Price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp" />

        <TextView
            android:id="@+id/seekbar_value"
            android:text="Any"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|bottom"
            android:textStyle="bold"/>

        <org.florescu.android.rangeseekbar.RangeSeekBar
            android:id="@+id/range_seekbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:showLabels="false"
            app:valuesAboveThumbs="false"
            app:barHeight="5dp"
            app:alwaysActive="true"
            app:thumbDisabled="@drawable/seekbar_button"
            app:textAboveThumbsColor="@color/colorPrimary"
            app:defaultColor="@color/colorPrimary"
            app:activeColor="@color/colorButton" />

        <TextView
            android:text="Block"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

            <GridView
                android:id="@+id/gridViewBlock"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>

            <TextView
            android:text="Floor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="start|bottom"
            android:textStyle="bold"
            android:textColor="@color/colorPrimary"
            android:layout_marginTop="20dp"/>

            **<GridView
                android:id="@+id/gridViewFloor"
                android:numColumns="auto_fit"
                android:gravity="center"
                android:columnWidth="60dp"
                android:stretchMode="columnWidth"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>**

        </LinearLayout>

        <Button
            android:text="See result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:textStyle="bold"
            android:background="@color/colorButton"
            android:textColor="@android:color/white" />

    </LinearLayout>

</LinearLayout>
</ScrollView>

And i programmatically adding gridView items:

public class FIlterActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private RangeSeekBar seekbar;
    private TextView seekbarValue;
    private GridView gridViewBlock;
    private GridView gridViewFloor;
    private FilterButtonAdapter filterBlockAdapter;
    private FilterButtonAdapter filterFloorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter);
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.activity_filter));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        gridViewBlock = (GridView) findViewById(R.id.gridViewBlock);

        filterBlockAdapter = new FilterButtonAdapter(this, Filter.filter_blocks, Filter.blocks_selected);
        gridViewBlock.setAdapter(filterBlockAdapter);

        gridViewBlock.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.blocks_selected.size(); i++){
                    if(value.equals(Filter.blocks_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.blocks_selected.remove(i);
                        if(Filter.blocks_selected.size() == 0){
                            Filter.blocks_selected.add(Filter.filter_blocks[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.blocks_selected.clear();
                        Filter.blocks_selected.add(Filter.filter_blocks[0]);
                        for(int i = 1; i < Filter.filter_blocks.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.blocks_selected.size(); i++){
                            if(Filter.blocks_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.blocks_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.blocks_selected.add(value);}
                filterBlockAdapter.notifyDataSetChanged();
            }
        });

        gridViewFloor = (GridView) findViewById(R.id.gridViewFloor);
        filterFloorAdapter = new FilterButtonAdapter(this, Filter.filter_floors, Filter.floor_selected);
        gridViewFloor.setAdapter(filterFloorAdapter);

        gridViewFloor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                final TextView textView = (TextView)view.findViewById(R.id.filter_button);
                String value = textView.getText().toString();
                boolean contain = false;

                for(int i = 0; i < Filter.floor_selected.size(); i++){
                    if(value.equals(Filter.floor_selected.get(i).toString())) {
                        view.setBackgroundResource(R.drawable.button_disabled);
                        Filter.floor_selected.remove(i);
                        if(Filter.floor_selected.size() == 0){
                            Filter.floor_selected.add(Filter.filter_floors[0]);
                            adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_enabled);
                        }
                        contain = true;
                        break;
                    }
                }
                if(!contain){
                    if(value.equals("Any")){
                        Filter.floor_selected.clear();
                        Filter.floor_selected.add(Filter.filter_floors[0]);
                        for(int i = 1; i < Filter.filter_floors.length; i++){
                            adapterView.getChildAt(i).setBackgroundResource(R.drawable.button_disabled);
                        }
                    }
                    else{
                        for(int i = 0; i < Filter.floor_selected.size(); i++){
                            if(Filter.floor_selected.get(i).toString().equals("Any")){
                                adapterView.getChildAt(0).setBackgroundResource(R.drawable.button_disabled);
                                Filter.floor_selected.remove(i);
                                break;
                            }
                        }
                    }
                    view.setBackgroundResource(R.drawable.button_enabled);
                    Filter.floor_selected.add(value);}
                filterFloorAdapter.notifyDataSetChanged();
            }
        });

        seekbar = (RangeSeekBar)findViewById(R.id.range_seekbar);
        seekbarValue = (TextView)findViewById(R.id.seekbar_value);

        seekbar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener() {
            @Override
            public void onRangeSeekBarValuesChanged(RangeSeekBar bar, Object minValue, Object maxValue) {
                if(String.valueOf(bar.getAbsoluteMaxValue()).equals(maxValue.toString())){

                    if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString()))
                        seekbarValue.setText("Бүх");
                    else {
                        seekbarValue.setText(minValue.toString() + " $ - +");
                    }
                } else if(String.valueOf(bar.getAbsoluteMinValue()).equals(minValue.toString())){
                    seekbarValue.setText(maxValue.toString() + " $ - -");
                } else{
                    seekbarValue.setText(minValue.toString() + " $ - " + maxValue.toString() + " $");
                }
            }
        });
    }
}

And Filter Button Adapter

public class FilterButtonAdapter extends BaseAdapter {

    private Context context;
    private final String[] filterValues;
    private List<String> checkedFilterValues = new ArrayList<String>();

    public FilterButtonAdapter(Context context, String[] filterValues, List<String> checkedFilterValues){
        this.context = context;
        this.filterValues = filterValues;
        this.checkedFilterValues = checkedFilterValues;
    }
    @Override
    public int getCount() {
        return filterValues.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        if(convertView == null){

            gridView = new View(context);
            gridView = inflater.inflate(R.layout.layout_button, null);

            final TextView textView = (TextView)gridView.findViewById(R.id.filter_button);
            textView.setText(filterValues[position]);

            boolean contain = false;
            for(int i = 0; i < Filter.blocks_selected.size(); i++){
                if(filterValues[position].equals(checkedFilterValues.get(i)))
                {
                    gridView.setBackgroundResource(R.drawable.button_enabled);
                    contain = true;
                    break;
                }
            }
            if(!contain){
                gridView.setBackgroundResource(R.drawable.button_disabled);
            }
        } else gridView = (View)convertView;
        return gridView;
    }
}

Filter class:

public class Filter {

    public static String price = "any";
    public static long priceMax = 0;
    public static long priceMin = 0;
    public static final String[] filter_blocks = new String[]{
            "any", "A", "B", "C"
    };
    public static final String[] filter_floors = new String[]{
            "any", "1", "2", "3", "4", "5", "6",
            "7", "8", "9", "10", "11", "12+"
    };

    public static List<String> blocks_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static List<String> floor_selected = new ArrayList<String>(){{
        add("any");
    }
    };

    public static int floor = 10;

}

My android studio emulator is 2.7 QVGA API 25

Body:
Don't use GridView inside ScrollView, because both has scrolling functionality and due to this it will not work properly.

Use NestedScrollView instead of ScrollView.

NestedScrollView is just like ScrollView, but it supports acting
  as both a nested scrolling parent and child on both new and old
  versions of Android. Nested scrolling is enabled by default.

See documentation.

Update your layout structure as below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
            app:titleTextColor="@android:color/white"
            app:contentInsetStartWithNavigation="0dp">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/layout_scorll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp">

                <TextView
                    android:text="Price"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="start|bottom"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:layout_marginTop="20dp" />

                <TextView
                    android:id="@+id/seekbar_value"
                    android:text="Any"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center|bottom"
                    android:textStyle="bold"/>

               <org.florescu.android.rangeseekbar.RangeSeekBar
                    android:id="@+id/range_seekbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:showLabels="false"
                    app:valuesAboveThumbs="false"
                    app:barHeight="5dp"
                    app:alwaysActive="true"
                    app:thumbDisabled="@drawable/seekbar_button"
                    app:textAboveThumbsColor="@color/colorPrimary"
                    app:defaultColor="@color/colorPrimary"
                    app:activeColor="@color/colorButton" />

                <TextView
                    android:text="Block"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="start|bottom"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:layout_marginTop="20dp"/>

                <GridView
                    android:id="@+id/gridViewBlock"
                    android:numColumns="auto_fit"
                    android:gravity="center"
                    android:columnWidth="60dp"
                    android:stretchMode="columnWidth"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:nestedScrollingEnabled="false"/>

                <TextView
                    android:text="Floor"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="start|bottom"
                    android:textStyle="bold"
                    android:textColor="@color/colorPrimary"
                    android:layout_marginTop="20dp"/>

                <!--  This Grid View is my problem -->
                <GridView
                    android:id="@+id/gridViewFloor"
                    android:numColumns="auto_fit"
                    android:gravity="center"
                    android:columnWidth="60dp"
                    android:stretchMode="columnWidth"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:nestedScrollingEnabled="false"/>

            </LinearLayout>

            <Button
                android:text="See result"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:textStyle="bold"
                android:background="@color/colorAccent"
                android:textColor="@android:color/white" />

        </RelativeLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>


答:
I believe you have to give the dateFormat for the DateFormatter while converting date to string.
Try using</p>

```<code>func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    whenTextField.text = dateFormatter.string(from: sender.date)
}
</code>```

Title: UIDatePicker not showing up in UITextField. Swift 3

Body:
I believe you have to give the dateFormat for the DateFormatter while converting date to string.
Try using

func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    whenTextField.text = dateFormatter.string(from: sender.date)
}


问:
Java Thread: Run method cannot throw checked exception
In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1)  book. Can someone please explain the reasoning behind it? </p>

答:
The reason is that exception is thrown back to the caller. Caller of run() method is not your code. It is the Thred itself. So even if run() throws exception the program cannot catch it. </p>

<p>You should put thread execution result to some class level variable and then read it from there. Or alternatively use new API: executors and interface Callable that declares method call() that returns future result  of the thread execution. </p>

Body:
The reason is that exception is thrown back to the caller. Caller of run() method is not your code. It is the Thred itself. So even if run() throws exception the program cannot catch it.

You should put thread execution result to some class level variable and then read it from there. Or alternatively use new API: executors and interface Callable that declares method call() that returns future result  of the thread execution.


问:
Azure StorageException: An unknown failure occurred : Connection timed out: connect
I am creating small JAVA program to access Azure blob storage as follows.

However I can able to access same Storage using Storage explorer (with same connection string)

But am failing to access the same with JAVA code in eclipse.

```<code>CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);

CloudBlobClient serviceClient = account.createCloudBlobClient();

// Container name must be lower case.
CloudBlobContainer container = serviceClient.getContainerReference("testeventdata");

// Download the JSON file.
CloudBlockBlob blob = container.getBlockBlobReference("TEST2.json");

// Download file
File sourceFile = new File("d:\\LHWMSGDownLoad.json");

File destinationFile = new File(sourceFile.getParentFile(),
                            "TESTDownLoad.json");

// **** On following line I am getting ERROR *****
// ***********************************************
blob.downloadToFile(destinationFile.getAbsolutePath());
</code>```

Error Description:

```<code>StorageException encountered: com.microsoft.azure.storage.StorageException: An unknown failure occurred : Connection timed out: connect
    at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:66)
    at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:200)`enter code here`
    at com.microsoft.azure.storage.blob.CloudBlob.download(CloudBlob.java:1083)
    at com.microsoft.azure.storage.blob.CloudBlob.downloadToFile(CloudBlob.java:1771)
    at com.microsoft.azure.storage.blob.CloudBlob.downloadToFile(CloudBlob.java:1743)
    at com.iot.tme.EventDataBlobAccess.EventDataBlobAccess.main(EventDataBlobAccess.java:67)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source`enter code here`)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:119)
    ... 4 more
</code>```

答: Per my experience, I think it's not your code fault obviously, but it might be caused by some configuration on your local machine or network environment very likely, such as firewall to block the request from Java. Please inspect and make sure whether these possible system configuration or softwares block it.</p>

Body:
I am creating small JAVA program to access Azure blob storage as follows.

However I can able to access same Storage using Storage explorer (with same connection string)

But am failing to access the same with JAVA code in eclipse.

CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);

CloudBlobClient serviceClient = account.createCloudBlobClient();

// Container name must be lower case.
CloudBlobContainer container = serviceClient.getContainerReference("testeventdata");

// Download the JSON file.
CloudBlockBlob blob = container.getBlockBlobReference("TEST2.json");

// Download file
File sourceFile = new File("d:\\LHWMSGDownLoad.json");

File destinationFile = new File(sourceFile.getParentFile(),
                            "TESTDownLoad.json");

// **** On following line I am getting ERROR *****
// ***********************************************
blob.downloadToFile(destinationFile.getAbsolutePath());

Error Description:

StorageException encountered: com.microsoft.azure.storage.StorageException: An unknown failure occurred : Connection timed out: connect
    at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:66)
    at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:200)`enter code here`
    at com.microsoft.azure.storage.blob.CloudBlob.download(CloudBlob.java:1083)
    at com.microsoft.azure.storage.blob.CloudBlob.downloadToFile(CloudBlob.java:1771)
    at com.microsoft.azure.storage.blob.CloudBlob.downloadToFile(CloudBlob.java:1743)
    at com.iot.tme.EventDataBlobAccess.EventDataBlobAccess.main(EventDataBlobAccess.java:67)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source`enter code here`)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:119)
    ... 4 more


问:
Pause an android application until input is provided
I have made an application where in the starting we ask for username and security password and then let the user use the application.

Currently, my application asks for username and security question one after the other in a pop out box but in the background the application also runs.

The application is waiting for the user to enter the username and security question answer because of which post url request fails to get a request because by that time "ans1[0]" variable is not set.

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    securityquestion(); // **This part calls the pop up dialog boxes**
    statusTxtView = (TextView) findViewById(R.id.status_text);
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
   // super.onPause();
    startRegistrationAndDiscovery();
    //super.onResume();
    servicesList = new WiFiDirectServicesList();
    getFragmentManager().beginTransaction()
            .add(R.id.container_root, servicesList, "services").commit();

}

    public void securityquestion(){
        final EditText txtUrl = new EditText(this);
        final EditText txtUrl2 = new EditText(this);
        final String[] ans1 = {""};
        final String[] ans2 = {""};
// Set the default text to a link of the Queen
        int num = getradomquestionumber();
        String messge = "";
        if(num==1)
        {
            txtUrl.setHint("First Pet name");
            messge = "What is your first pet name?";
        }else{
            txtUrl.setHint("Mother's maiden name");
            messge = "What is your mother's maiden name?";
        }
        txtUrl2.setHint("User Name");

        new AlertDialog.Builder(this)
                .setTitle("Security Question")
                .setMessage(messge)
                .setView(txtUrl)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans2[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        new AlertDialog.Builder(this)
                .setTitle("User Name")
                .setMessage("Enter UserName")
                .setView(txtUrl2)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans1[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        HashMap<String , String> postDataParams = new HashMap<String, String>();
        postDataParams.put("key", String.valueOf(num));
        postDataParams.put("key2", ans1[0]);
        response = performPostCall("http://10.19.23.2/NEWS/SecurityQuestion.php", postDataParams);
        System.out.println("response -------------- "+response);
        if(response == ans2[0]){

        }else{
            System.exit(0);
        }
    }
</code>```

Currently I am unable to get a response from the server because the application doesn't wait for the response from the user. How do I pause the application so that fir the dialog box appears first, takes users input and then further after authentication, only continue the application.

Requesting you to please help me with your suggestions.

答:
You need to do something like this:

Your main page is created (initialize what needs) and is started

Your main page opens the pop up dialog

User type in name and question, click something

At this point, you make the server request (on background). Here your main page or pop up must show some indicator that it's waiting, like a spinner

If server is successful, you stop spinning and continue

If server is unsuccessful, you stop spinning, print some error to the user, and let her try again

Also, execution code shouldn't be done in onCreate(), but in onStart() and then whenever the server is back to you with a positive answer. See activity lifecycle for this really basic stuffs

Body:
I have made an application where in the starting we ask for username and security password and then let the user use the application.

Currently, my application asks for username and security question one after the other in a pop out box but in the background the application also runs.

The application is waiting for the user to enter the username and security question answer because of which post url request fails to get a request because by that time "ans1[0]" variable is not set.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    securityquestion(); // **This part calls the pop up dialog boxes**
    statusTxtView = (TextView) findViewById(R.id.status_text);
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
   // super.onPause();
    startRegistrationAndDiscovery();
    //super.onResume();
    servicesList = new WiFiDirectServicesList();
    getFragmentManager().beginTransaction()
            .add(R.id.container_root, servicesList, "services").commit();

}

    public void securityquestion(){
        final EditText txtUrl = new EditText(this);
        final EditText txtUrl2 = new EditText(this);
        final String[] ans1 = {""};
        final String[] ans2 = {""};
// Set the default text to a link of the Queen
        int num = getradomquestionumber();
        String messge = "";
        if(num==1)
        {
            txtUrl.setHint("First Pet name");
            messge = "What is your first pet name?";
        }else{
            txtUrl.setHint("Mother's maiden name");
            messge = "What is your mother's maiden name?";
        }
        txtUrl2.setHint("User Name");

        new AlertDialog.Builder(this)
                .setTitle("Security Question")
                .setMessage(messge)
                .setView(txtUrl)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans2[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        new AlertDialog.Builder(this)
                .setTitle("User Name")
                .setMessage("Enter UserName")
                .setView(txtUrl2)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans1[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        HashMap<String , String> postDataParams = new HashMap<String, String>();
        postDataParams.put("key", String.valueOf(num));
        postDataParams.put("key2", ans1[0]);
        response = performPostCall("http://10.19.23.2/NEWS/SecurityQuestion.php", postDataParams);
        System.out.println("response -------------- "+response);
        if(response == ans2[0]){

        }else{
            System.exit(0);
        }
    }

Currently I am unable to get a response from the server because the application doesn't wait for the response from the user. How do I pause the application so that fir the dialog box appears first, takes users input and then further after authentication, only continue the application.

Requesting you to please help me with your suggestions.