Monday, September 10, 2012

Change two colors by percentage

In Android, it is not good when most of the views has alpha value. Therefore, it is better by changing color of the view.

Below is the color interplation between a and b with given proportion:

private float interpolate(float a, float b, float proportion) {
    return (a + ((b - a) * proportion));
}

/** Returns an interpoloated color, between a and b */
private int interpolateColor(int a, int b, float proportion) {
    float[] hsva = new float[3];
    float[] hsvb = new float[3];
    Color.colorToHSV(a, hsva);
    Color.colorToHSV(b, hsvb);
    for (int i = 0; i < 3; i++) {
        hsvb[i] = interpolate(hsva[i], hsvb[i], proportion);
    }
    return Color.HSVToColor(hsvb);
}

Thanks to:

Friday, August 31, 2012

Change XML Layout automatically when orientation happens

Most of Android developers know that Android has lots of unique and useful features. One of them is changing the layout based on current orientation. But it seems that it is not easy to manage what to do before and after changing the layout.

Before manage/control the layout, you must have two layouts, landscape (in layout-land/ folder) and portrait (in layout/ folder).




Then, we start to manage/control the layouts.

If you don't want to manage/control all stuffs, just let Android do it for you, by doing:
  1. Remove android:configChanged="orientation" of your activity.
    • This will cause that you don't receive onConfigurationChanged event.
    • By doing this, there are some pros and cons:
      • Pros:
        1. Android will reset the ContentView when onConfigurationChanged (we can't see it anymore).
        2. We just prepare the layouts easily.
      • Cons:
        1. All parameters/properties will be reset when Android resets the ContentView.
In the first step, it is hard to maintain your layout, parameters, and other things you want to do when receiving onConfigurationChanged event. Therefore, we do all stuffs by doing:
  1. Add android:configChanged="orientation" of your activity.
    1. Now you can use onConfigurationChanged event.
  2. Inside onConfigurationChanged, do:
// Remove all views that you want to reuse in new layout
View myreuseview = findViewById(R.id.myReuseView);
findViewById(R.id.myLayout).removeAllViews;

// Reset the layout, your layout name is activity_layout.xml
// inside (in layout/ and layout-land/ folders).
setContentView(R.layout.activity_layout);

// Remove all views in new layout
findViewById(R.id.myLayout).removeAllViews;

// Add the reuse view to new layout
findViewById(R.id.myLayout).addView(myreuseview);

// do other initialization stuffs, like init buttons, etc.

In conclusion, it is better to control all your stuffs. It will give you a lot of advantages from memory control, reuse contents, etc.

Try it!

Monday, July 30, 2012

Customize view using XIB

This is the example of how to customize UITableViewCell using XIB.

1. Create your XIB:

2. Load XIB and create it as a view:

3. Done

Friday, July 27, 2012

Force using english localized if current localized does not exists

Create a class:

CLocale.h
#undef NSLocalizedString#define NSLocalizedString(key, comment) \
[CLocale localizedString:(key)]
@interface CLocale : NSObject
+ (NSString*) localizedString:(NSString*)key;
@end

CLocale.m
#import "CLocale.h"
@implementation CLocale
+ (NSString*) localizedString:(NSString*)key
{
    NSArray* languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString* currentLocale = [languages objectAtIndex:0];
    NSString* localized = [[NSBundle mainBundle] localizedStringForKey:key value:@"" table:nil];
    // if key and localized are same, also it is not english,
    // then force to use english language
    if ([localized compare:key] == NSOrderedSame && [currentLocale compare:@"en"] != NSOrderedSame)
    {
        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"]];
        localized = NSLocalizedStringFromTableInBundle(key, nil, bundle, nil);
    }
    return localized;
}
@end

At last, include it into your pre-defined header (.pch)
#import "CLocale.h"

Done.


Wednesday, April 11, 2012

What should every programmer know about web development?

The idea here is that most of us should already know most of what is on this list. But there just might be one or two items you haven't really looked into before, don't fully understand, or maybe never even heard of.

Interface and User Experience
Security
Performance
  • Implement caching if necessary, understand and use HTTP caching properly as well as HTML5 Manifest.
  • Optimize images - don't use a 20 KB image for a repeating background.
  • Learn how to gzip/deflate content (deflate is better).
  • Combine/concatenate multiple stylesheets or multiple script files to reduce number of browser connections and improve gzip ability to compress duplications between files.
  • Take a look at the Yahoo Exceptional Performance site, lots of great guidelines including improving front-end performance and their YSlow tool. Google page speed is another tool for performance profiling. Both require Firebug to be installed.
  • Use CSS Image Sprites for small related images like toolbars (see the "minimize HTTP requests" point)
  • Busy web sites should consider splitting components across domains. Specifically...
  • Static content (i.e. images, CSS, JavaScript, and generally content that doesn't need access to cookies) should go in a separate domain that does not use cookies, because all cookies for a domain and its subdomains are sent with every request to the domain and its subdomains. One good option here is to use a Content Delivery Network (CDN).
  • Minimize the total number of HTTP requests required for a browser to render the page.
  • Utilize Google Closure Compiler for JavaScript and other minification tools.
  • Make sure there’s a favicon.ico file in the root of the site, i.e. /favicon.icoBrowsers will automatically request it, even if the icon isn’t mentioned in the HTML at all. If you don’t have a/favicon.ico, this will result in a lot of 404s, draining your server’s bandwidth.
SEO (Search Engine Optimization)
  • Use "search engine friendly" URLs, i.e. use example.com/pages/45-article-title instead ofexample.com/index.php?page=45
  • When using # for dynamic content change the # to #! and then on the server$_REQUEST["_escaped_fragment_"] is what googlebot uses instead of #!. In other words,./#!page=1 becomes ./?_escaped_fragments_=page=1. Also, for users that may be using FF.b4 or Chromium, history.pushState({"foo":"bar"}, "About", "./?page=1"); Is a great command. So even though the address bar has changed the page does not reload. This allows you to use ? instead of #! to keep dynamic content and also tell the server when you email the link that we are after this page, and the AJAX does not need to make another extra request.
  • Don't use links that say "click here". You're wasting an SEO opportunity and it makes things harder for people with screen readers.
  • Have an XML sitemap, preferably in the default location /sitemap.xml.
  • Use 

 when you have multiple URLs that point to the same content, this issue can also be addressed from Google Webmaster Tools.

  • Use Google Webmaster Tools and Bing Webmaster Tools.
  • Install Google Analytics right at the start (or an open source analysis tool like Piwik).
  • Know how robots.txt and search engine spiders work.
  • Redirect requests (using 301 Moved Permanently) asking for www.example.com to example.com(or the other way round) to prevent splitting the google ranking between both sites.
  • Know that there can be badly-behaved spiders out there.
  • If you have non-text content look into Google's sitemap extensions for video etc. There is some good information about this in Tim Farley's answer.
Technology
  • Understand HTTP and things like GET, POST, sessions, cookies, and what it means to be "stateless".
  • Write your XHTML/HTML and CSS according to the W3C specifications and make sure they validate. The goal here is to avoid browser quirks modes and as a bonus make it much easier to work with non-standard browsers like screen readers and mobile devices.
  • Understand how JavaScript is processed in the browser.
  • Understand how JavaScript, style sheets, and other resources used by your page are loaded and consider their impact on perceived performance. It may be appropriate in some cases to move scripts to the bottom of your pages.
  • Understand how the JavaScript sandbox works, especially if you intend to use iframes.
  • Be aware that JavaScript can and will be disabled, and that AJAX is therefore an extension, not a baseline. Even if most normal users leave it on now, remember that NoScript is becoming more popular, mobile devices may not work as expected, and Google won't run most of your JavaScript when indexing the site.
  • Learn the difference between 301 and 302 redirects (this is also an SEO issue).
  • Learn as much as you possibly can about your deployment platform.
  • Consider using a Reset Style Sheet.
  • Consider JavaScript frameworks (such as jQueryMooToolsPrototypeDojo or YUI 3), which will hide a lot of the browser differences when using JavaScript for DOM manipulation.
  • Taking perceived performance and JS frameworks together, consider using a service such as theGoogle Libraries API to load frameworks so that a browser can use a copy of the framework it has already cached rather than downloading a duplicate copy from your site.
  • Don't reinvent the wheel. Before doing ANYTHING search for a component or example on how to do it. There is a 99% chance that someone has done it and released an OSS version of the code.
Bug fixing
  • Understand you'll spend 20% of your time coding and 80% of it maintaining, so code accordingly.
  • Set up a good error reporting solution.
  • Have a system for people to contact you with suggestions and criticisms.
  • Document how the application works for future support staff and people performing maintenance.
  • Make frequent backups! (And make sure those backups are functional) Ed Lucas's answer has some advice. Have a restore strategy, not just a backup strategy.
  • Use a version control system to store your files, such as SubversionMecurial or Git.
  • Don't forget to do your Acceptance Testing. Frameworks like Selenium can help.
  • Make sure you have sufficient logging in place using frameworks such as log4j, log4n or log4r. If something goes wrong on your live site, you'll need a way of finding out what.
  • When logging make sure you're capture both handled exceptions, and unhandled exceptions. Report/analyse the log output, as it'll show you where the key issues are in your site.

Lots of stuff omitted not necessarily because they're not useful answers, but because they're either too detailed, out of scope, or go a bit too far for someone looking to get an overview of the things they should know. If you're one of those people you can read the rest of the answers to get more detailed information about the things mentioned in this list. If I get the time I'll add links to the various answers that contain the things mentioned in this list if the answers go into detail about these things. Please feel free to edit this as well, I probably missed some stuff or made some mistakes.

http://programmers.stackexchange.com/questions/46716/what-should-every-programmer-know-about-web-development

Friday, March 30, 2012

Cannot drop index needed in a foreign key constraint

When you receive the message
"MySQL Cannot drop index needed in a foreign key constraint"
You have to drop the foreign key. Foreign keys in MySQL automatically create an index on the table (There was a SO Question on the topic).

ALTER TABLE mytable DROP FOREIGN KEY mytable_ibfk_1;

Thursday, March 22, 2012

Share file between activites

1. Set this same shared user id in manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.a"
    android:versionCode="1"
    android:versionName="1.0"
    android:sharedUserId="com.example.id">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.b"
    android:versionCode="1"
    android:versionName="1.0"
    android:sharedUserId="com. example.id">

2. Get another app’s context with createPackageContext()
Context otherContext = context.createPackageContext("com.example.a", 0);
AssetManager am = otherContext.getAssets();

Monday, March 19, 2012

Using assets from any apk

Android allows a nice feature of adding your own files in the final apk package. These files are called “assets”. For adding assets to your project you simply add your files to the “prj_name/assets” directory.

The files you add in the assets directory will be zipped in the final “apk” project, along with the executable-files and the other resources.

One has two methods to access the asset files:

  1. use android.content.res.AssetManager
    • Note that this will limit your asset files to 1Mb, at least for Android 1.5 release.
  2. use java.util.zip 
    1. This has no limitations to size, but will access all resources in the zip, so one has to filter the results.
    2. The implementations at a glance:
      1. android.content.res.AssetManager
        AssetManager am = getResources().getAssets(); // get the local asset manager
        InputStream is = am.open( asset ); // open the input stream for reading
        while ( true ) // do the reading
        {
        int count = is.read(buf, 0, MAX_BUF);
        // .. use the data as you wish
        }
      2. java.util.zip
        1. Your apk file is installed in /data/app/com.name.of.package.apk
        2. Given this location of your apk file, the unzip method is straight-forward:
          ZipFile zipFile = new ZipFile(m_sZipFilename); // create the zip file
          Enumeration entries = zipFile.entries(); // get the enumeration of the entries in the zip
          while (entries.hasMoreElements()) // while the zip still has elements
          {
          ZipEntry entry = (ZipEntry)entries.nextElement(); // get each entry at a time
          String filename = entry.getName(); // get entry name
          zipFile.getInputStream(entry); // get the input stream for the given entry – you can use this to unzip the asset
          // process the entry as you like (copy it in the
          }
        3. Some other useful methods of the ZipEntry class are: 
          • - getSize(): Gets the uncompressed size of this ZipEntry.
          • - isDirectory(): Gets the uncompressed size of this ZipEntry.
          • - getCompressedSize(): Gets the compressed size of this ZipEntry

http://www.itwizard.ro/android-phone-installing-assets-how-to-60.html 

Tuesday, February 14, 2012

Repair HFS+ when your BootCamp is error

  1. Restart your Mac.
  2. As soon as it turns on, even before you hear it go bong, hold down Cmd+S.
  3. The system will boot showing a lot of text. If it doesn't and you see the Apple logo, you've waited too long. Reboot and try again.
  4. When at the prompt type fsck -f. If changes are successfully made it will repeat the process then say "Modifications have been made".
  5. Then simply type in reboot and you should be able to partition your drive successfully.

Friday, February 3, 2012

How to remove default/preloaded applications like browser,camera,contacts...

Suppose u have developed a new contact application which is much better than the preloaded contact application in android..so when u want to install it eclipse will throw u bunch of error saying "Please uninstall the contact application first by adb uninstall "package name".

When u tried to do that...Alas...it did not work...saying FAILED

The reason for this is that u don't have the root access and u have only read only access..So to change the access and remove the contacts(any application) follow the below instructions..

  1. Start your emulator
  2. Execute "adb shell" in on terminal from SDK_ROOT/tool folder
  3. Mount your system folder with read/write permission

    mount -o remount,rw /dev/block/mtdblock3 /system
  4. Go to system/apps folder

    cd /system/apps
  5. Remove APK

    rm defaultapp.apk

 

Bingo Check your emulator.The default application is gone.Now u can install your application with eclipse.
N.B.:This is required to remove the apps already present in emulator...If u want to remove some of the application u've installed then just do


adb uninstall yourpackagename

or


adb shell
cd /data/app
rm yourapp.apk

So enjoy Being an Android Programmer........

Link: http://oneclickandroid.blogspot.com/2009/01/how-to-remove-defaultpreloaded.html

Thursday, January 12, 2012

Speed up SQLite insert

Using android.database.DatabaseUtils.InsertHelper class.

Sample code:

SQLiteDatabse db = getWriteableDatabase();
//use the db you would normally use for db.insert, and the "table_name"
//is the same one you would use in db.insert()
InsertHelper iHelp = new InsertHelper(db, "table_name");
//Get the indices you need to bind data to
//Similar to Cursor.getColumnIndex("col_name");                 
int first_index = iHelp.getColumnIndex("first");
int last_index = iHelp.getColumnIndex("last");

try{
   db.beginTransaction();
   for(int i=0 ; i<num_things ; ++i)
   {
       //need to tell the helper you are inserting (rather than replacing)
       iHelp.prepareForInsert();

       //do the equivalent of ContentValues.put("field","value") here
       iHelp.bind(first_index, thing_1);
       iHelp.bind(last_index, thing_2);

       //the db.insert() equilvalent
       iHelp.execute();
   }
   db.setTransactionSuccessful();
}
finally{
    db.endTransaction();
}
db.close();

Reference: http://stackoverflow.com/questions/3501516/android-sqlite-database-slow-insertion

Set up ADB environment in Mac OSX

  • Open Terminal
  • Type cd ~ this will take you to your home directory
  • Type touch .profile this will create a hidden file named profile
  • Type open -e .profile this will open the file you just created in TextEdit
  • In the file, type exportPATH=${PATH}:/pathToTheAndroidSdkFolder/android-sdk-mac_86/platform-tools
  • Save file, close TextEdit, Quit Terminal, and Relaunch Terminal
  • NOTE: By creating an environment variable you won't need to cd to the Android/tools folder every time you want to run ADB

Monday, January 9, 2012

Get mimetype from header file

// return: jpeg, png, bmp, unknown
public static String getMimeTypeFileByHeader(String realPath) 
{
    File f = new File(realPath);
    try {
        InputStream in = new FileInputStream(f);
       
        byte[] HEADERJPEG = new byte[] {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF};
        byte[] HEADERBMP = new byte[] { 0x42, 0x4d };
        byte[] HEADERPNG = new byte[] { (byte) 0x89, 0x50, 0x4e };

        byte[] header = new byte[3];
        int h = in.read(header);
       
        if (h==3 && Arrays.equals(header, HEADERJPEG)) {
            return "jpeg";
        }
       
        if (h==3 && Arrays.equals(header, HEADERPNG)) {
            return "png";
        }
       
        byte[] header2 = new byte[2];
        for (int i=0; i<2; i++)
            header2[i] = header[i];
       
        if (Arrays.equals(header2, HEADERBMP)) {
            return "bmp";
        }
       
    } catch (Throwable e) {}
   
    return "unknown";
}

// Others
/*
PDF("PDF", new byte[][] { { 0x25, 0x50, 0x44, 0x46 } }),
JPG("JPG", new byte[][] { { (byte) 0xff, (byte) 0xd8, (byte) 0xff, (byte) 0xe0 } }),
RAR("RAR", new byte[][] { { 0x52, 0x61, 0x72, 0x21 } }),
GIF("GIF", new byte[][] { { 0x47, 0x49, 0x46, 0x38 } }),
PNG("PNG", new byte[][] { { (byte) 0x89, 0x50, 0x4e, 0x47 } }),
ZIP("ZIP", new byte[][] { { 0x50, 0x4b } }),
TIFF("TIFF", new byte[][] { { 0x49, 0x49 }, { 0x4D, 0x4D } }),
BMP("BMP", new byte[][] { { 0x42, 0x4d } });
*/

[ROM] Samsung S7 Stock Firmware BRI (Taiwan台灣)

Latest ROM: G930FXXU1DQEU Download: https://kfhost.net/tpl/firmwares.php?record=B7E6DE774E3811E7963AFA163EE8F90B Reference: http://...