2017年8月6日 星期日

How to load part of the image base on the height

image = (ImageView)findViewById(R.id.iv);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.ico_star_blue_full);
image.setBackgroundResource(R.drawable.ico_star_blue_empty);
float percent = 0.3f;
int height = (int)(bmp.getHeight() * percent);

Bitmap bmpProgress = bmp.createBitmap(bmp,0,bmp.getHeight()-height,bmp.getWidth(),height);
image.setImageBitmap(bmpProgress);
image.setScaleType(ImageView.ScaleType.FIT_END);





bmp.getHeight()-height is calculate the start point of the pixel,the top of the start point is 0

2017年6月19日 星期一

1.Maven setup


2.Spark for REST APIs: Using Spark, Lombok and Jackson to reduce Java boilerplate
http://sparkjava.com/tutorials/sql2o-database

3.connect the spark to the sql
http://sparkjava.com/tutorials/sql2o-database



2017年4月5日 星期三

2017年3月29日 星期三

Android how to parse the XML

XML Content


/*
<car>
<vacancyinfo capacity="327" vacancy="145"/>
</car>*/



parse Program

xml = connection(SharedUtils.CAR_VACANCY_URL, null);

InputStream inputStream = new    ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();
NodeList vacancyinfoNodeLis = doc.getElementsByTagName("vacancyinfo");
Element vacancyinfo = (Element) vacancyinfoNodeLis.item(0);
String capacity=vacancyinfo.getAttribute("capacity");
String vacancy=vacancyinfo.getAttribute("vacancy");

2017年3月21日 星期二

svn

use as git
see:http://johnwong.github.io/mobile/2015/04/30/using-git-with-svn.html
用Git的方式使用SVN

用Git的方式使用SVN

习惯用Git后的程序员一定对SVN不屑一顾。不过目前的开发环境必须使用SVN,用起来不开心。还好Git提供了对SVN的支持,让我们可以像使用Git一样使用SVN。当然一些Git的高级功能还是无法支持的。
有兴趣详细了解的同学可以参考git-svn文档。简单来说只需要几步就可以使用了。

检出SVN库

git svn clone http://PATH_TO_SVN
有了这一步就可以在命令行像操作Git一样操作SVN了。如果对git-svn的命令不习惯,可以试试用工具。

使用SourceTree

我经常使用的Git客户端是SourceTree。SourceTree支持git-svn,只需要将检出的目录拖到SourceTree的Repository Browser (Command + B),就可以使用了。
如果使用时遇到错误:
Can’t locate SVN/Core.pm in @INC (you may need to install the SVN::Core module)
解决方法是参考这里
sudo ln -s /Applications/Xcode.app/Contents/Developer/Library/Perl/5.18/darwin-thread-multi-2level/SVN /System/Library/Perl/Extras/5.18/SVN
sudo ln -s /Applications/Xcode.app/Contents/Developer/Library/Perl/5.18/darwin-thread-multi-2level/auto/SVN/ /System/Library/Perl/Extras/5.18/auto/SVN
然后就可以开心地继续开发了。
git-svn

自定义Action

使用过程中,因为我有一些改动不需要提交到svn上,所以每次提交或者更新时都需要先stash,完成操作再放回来。这样3步操作可以通过Source Tree的自定义Action合成一步。
定义了一些脚本pull.shpush.sh,例如:
#!/bin/sh
cd "$REPO"
git stash
git svn fetch
git svn rebase
git stash apply
#!/bin/sh
cd "$REPO"
git stash
git svn dcommit
git stash apply
打开Source Tree的Preferences->Custom Actions,新建pull与push,选择这两个脚本。以后打开项目后,就可以在Actions->Custom Actions下找到你添加的这两个Action。

if not work

try

Git svn not work

Or try this

svn checkout --username roy.leung --password ro436NG svn://svn.gravitas.com.hk/opt/svnrepos/Android/YOHOMall

2017年3月10日 星期五

android move a view

 float wechatIconX = ivWechat.getX();
        int weChatIconWidth = ivWechat.getWidth();
        float wechatIconCenterX = wechatIconX + weChatIconWidth / 2;
        float popupWidthPX = getResources().getDimension(R.dimen.wechatPopUp_width);
        ivWechatPopUp.setX(wechatIconCenterX - popupWidthPX / 2);

Load dimension value from res/values/dimension.xml from source code

In my dimens.xml I have

<dimen name="test">48dp</dimen>
In code If I do

int valueInPixels = (int) getResources().getDimension(R.dimen.test)
this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)

exactly as docs state :

Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.
so if you want exact dp value just as in xml just divide it with DisplayMetrics density



int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)

2017年3月3日 星期五

2017年2月12日 星期日

How to set language in Android

use the below class

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static void onCreate(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        setLocale(context, lang);
    }

    public static void onCreate(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static void setLocale(Context context, String language) {
        persist(context, language);
        updateResources(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    private static void updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    }
}



How to use?


In Application

  public void onCreate() {
        super.onCreate();
        LocaleHelper.onCreate(this, "en");

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LocaleHelper.setLocale(this, LocaleHelper.getLanguage(this));
    }


Set the language

LocaleHelper.setLocale(this, "en");

How to change the language without restart the activity

LocaleHelper.setLocale(this, "zh");


set the text that you can see
e.g.
tvEn.setText(getContext().getString(R.string.en));
        tvTc.setText(getContext().getString(R.string.tc));
        tvChangePsw.setText(getContext().getString(R.string.change_psw));
        tvChangeLang.setText(getContext().getString(R.string.change_lang));
        tvPushNote.setText(getContext().getString(R.string.push_notic));
        tvPromotion.setText(getContext().getString(R.string.promotion));
        tvHealthTips.setText(getContext().getString(R.string.health_tips));
        tvLogout.setText(getContext().getString(R.string.logout));

2017年1月26日 星期四

How to use Realm

Intsall



Create Models


public class User extends RealmObject {

   private String          name;
   private int             age;

   @Ignore
   private int             sessionId;

   // Standard getters & setters generated by your IDE…
   public String getName() { return name; }
   public void   setName(String name) { this.name = name; }
   public int    getAge() { return age; }
   public void   setAge(int age) { this.age = age; }
   public int    getSessionId() { return sessionId; }
   public void   setSessionId(int sessionId) { this.sessionId = sessionId; }
}


How to write

Realm realm = Realm.getDefaultInstance();

way 1

realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();


way 2

not block the UI thread
realm.executeTransactionAsync(new Realm.Transaction() {
           @Override
           public void execute(Realm bgRealm) {
               User user = bgRealm.createObject(User.class);
               user.setName("John");
               user.setEmail("john@corporation.com");
           }
       }, new Realm.Transaction.OnSuccess() {
           @Override
           public void onSuccess() {
               // Transaction was a success.
           }
       }, new Realm.Transaction.OnError() {
           @Override
           public void onError(Throwable error) {
               // Transaction failed and was automatically canceled.
           }
       });

if use primary key


@PrimaryKey
   private String name;


final String name = edName.getText().toString();
               final String old = edOld.getText().toString();

               Realm.Transaction transaction = new Realm.Transaction() {
                   @Override
                   public void execute(Realm bgrealm) {

                       User user = new User(name, old);
                       bgrealm.copyToRealmOrUpdate(user);

                   }
               };

How to query

RealmResults<User> result2 = realm.where(User.class)
                                 .equalTo("name", "John")
                                 .or()
                                 .equalTo("name", "Peter")
                                 .findAll();

result.get(result.size() - 1);


condition

  • between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
  • equalTo() & notEqualTo()
  • contains(), beginsWith() & endsWith()
  • isNull() & isNotNull()
  • isEmpty() & isNotEmpty()


and   or

Each condition is implicitly logical-and together. Logical-or must be applied explicitly with or().


RealmResults<User> r = realm.where(User.class)
                           .greaterThan("age", 10)  //implicit AND
                           .beginGroup()
                               .equalTo("name", "Peter")
                               .or()
                               .contains("name", "Jo")
                           .endGroup()
                           .findAll();


other…

Sorting

RealmResults<User> result = realm.where(User.class).findAll();
result.sort("age"); // Sort ascending
result.sort("age", RealmResults.SORT_ORDER_DESCENDING);



Auto-Updating Results
auto-updating views into the underlying data, which means results never have to be re-fetched



result = realm.where(User.class).findAll();
    

       result.addChangeListener(new RealmChangeListener<RealmResults<User>>() {
           @Override
           public void onChange(RealmResults<User> element) {
               useResultToSetTheUi(element);
           }
       });




Delete


// obtain the results of a query
final RealmResults<Dog> results = realm.where(Dog.class).findAll();

// All changes to data must happen in a transaction
realm.executeTransaction(new Realm.Transaction() {
   @Override
   public void execute(Realm realm) {
       // remove single match
       results.deleteFirstFromRealm();
       results.deleteLastFromRealm();

       // remove a single object
       Dog dog = results.get(5);
       dog.deleteFromRealm();

       // Delete all matches
       results.deleteAllFromRealm();
   }
});



Thread

Using a Realm across Threads
The only rule to using Realm across threads is to remember that Realm, RealmObject or RealmResults instances cannot be passed across threads

Learn how to work with Android




use with RxJava