Friday 31 October 2014

How to open an URL in a new window in Javascript

If you want to open a web page on another window using javascript, just use the method open of the object window.
Very useful to keep users on your web site
Example
Just add the line
  window.open("http://devhelpers.blogspot.ca");
Inside a <script> tag

Wednesday 29 October 2014

How to dynamically change the text of an android widget

This works for any android widget that support text labels, like TextViews and buttons


  // this code is assumed to run inside an activity class or view
  // in short, this must have the findViewById method
  // also, you need the text to be in your string resource file (usually strings.xml)

  TextView theLabelOnTheScreen = (TextView)this.findViewById(R.id.myLabel);
  theLabelOnTheScreen.setText(R.string.the_id_of_the_string_to_be_used);

How to make a TextView underlined

The best and easiest way to do that is use tags in your strings.xml (or whatever you call your strings resource file)

Example
<?xml version="1.0" encoding="utf-8"?>
  </resources>
    <string name="textview_string_id"><u>This is underlined text</u></string>
  <resources>


Other tags that also work
<i></i> (italic)
<b></b> (bold)

How to download files asynchronously using only HTTP

all you need is these 2 simple methods in your class.
private void downloadFile(string fileUrl)
{ 
  HttpWebRequest request;
 
  request = WebRequest.Create(fileUrl) as HttpWebRequest;
  // this reduces connection time considerably but it's not supported in windows phone 8
  request.Proxy = null; 
 
  if(request != null)
  {
    request.BeginGetResponse(downloadFile, request); 
  }
}
 
private void downloadFile(IAsyncResult responseResult)
{   
  HttpWebRequest request = responseResult.AsyncState as HttpWebRequest ;
  if(request != null)
  {
    // the using here is VERY important if you don't want leaks
    using (WebResponse response = request.EndGetResponse(responseResult))
    {
      if(((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
      {
        // if you want to use a dynamic file location, just make the file name a member variable in your class
        using(FileStream fileStream = File.Open(@"c:\files\my_downloaded.file", FileMode.Create))
        {
          Stream source = response.GetResponseStream();
          int bytesRead;
          byte[] streamBuffer = new byte[1024*64];
          while ((bytesRead = source.Read(streamBuffer, 0, streamBuffer.Length)) > 0)
          {
            fileStream.Write(streamBuffer, 0, bytesRead);
          }
        }
      }
    }
  }
}