Blog Archives


To check a string exists in other string in JavaScript, we can use indexOf function, if exists this function return 》=0 value,otherwise it will return -1.

For example:

if(str.indexOf(substr)>=0){

// exist

} else{

// not exist

}


Sometimes, we need read an image in assets directory to display in android, at this situation, we may need read data of image into a byte array so that we can use it in other place of our program. To read data of an image into a byte data is very simple, we can do like this:

Step 1: Put an image into assets directory in Android project

Before we start to coding, we should place an image into assets directory in android project, it may like this:

image in assets directory

Step 2: Read data of image into a byte array

After we have place an image into assets directory, we can read its data into a byte array, this sample code realize read data of an image  in assets directory into a byte array, then display it on imageview.

show image from assets in android

Smaple code like this:


public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ImageView imageView = (ImageView) this.findViewById(R.id.image_id);
 //read an image in assets
 byte[] data = readImageFromAssets("logo.png");
 Bitmap bitmap = null;
 try {
 bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
 } catch(Exception e) {
 if(null != bitmap) {
 bitmap.recycle();
 bitmap = null;
 }
 }
 if(bitmap != null) {
 Drawable drawable =new BitmapDrawable(bitmap);
 imageView.setBackgroundDrawable(drawable);
 }
 }
 /** read a image into byte array from assets */
 private byte[] readImageFromAssets(String imageName) {
 InputStream is = null;
 ByteArrayOutputStream out = null;
 try {
 is = getBaseContext().getAssets().open(imageName);
 out = new ByteArrayOutputStream(1024);
 byte[] temp = new byte[1024];
 int size = 0;
 while ((size = is.read(temp)) != -1) {
 out.write(temp, 0, size);
 }
 byte[] content = out.toByteArray();

 if(is != null) {
 is.close();
 }
 if(out != null) {
 out.close();
 }
 return content;
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } finally {

 }
 return null;

 }


In article “2 Steps to solve problem:Can’t create handler inside thread that has not called Looper.prepare() in Android“, We know a truth: a toast can not be run in no-ui thread in android, if you should realize it you should use Looper.prepare().

How to use Looper.prepare() you may ask me, you can use it like follow steps:

Step 1: Effect of Loop.prepare() and Looper.loop()

In Anroid Looper you can get some very useful information on Loop.prepare, however, if you think that is too hard to you ,you can understand it like this.

Loop.prepare and Looper.loop() can create a ui thread, then you can run some ui process between them.

Step 2: Example of using Loop.prepare() and Looper.loop()

To understand how to use Loop.prepare() and Looper.loop(), you can read example below.

We know we can not show a toast in a no-ui thread in android, so if you run this code below, you will find a toast will be showed in ui thread.


public class TestActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState){
 super.onCreate(savedInstanceState);
 this.setContentView(R.layout.test);
 Button btn = (Button) this.findViewById(R.id.back_id);
 btn.setOnClickListener(new OnClickListener() {
 public void onClick(View v) {
 new Thread(new Runnable(){

@Override
 public void run() {
 // TODO Auto-generated method stub
 Looper.prepare();
 showToast("Toast run in sub thread");
 Looper.loop();
 }

 }).start();
 }
 });
 showToast("Toast run in UI thread");
 }
 private void showToast(String msg) {
 Toast.makeText(TestActivity.this, msg, Toast.LENGTH_LONG).show();
 }
}

However, if you plan to show it in a no-ui thread,you must use key code:


Looper.prepare();
showToast("Toast run in sub thread");
Looper.loop();

Then we will create a ui thread, which can show my toast.

taost run in sub thread

Tips and Warnings:

(1) code above if you remove Loop.prepare() and Looper.loop(), this application will break down and stop.


Today when i programming a android project, i met with this problem:

Can’t create handler inside thread that has not called Looper.prepare()

From the error message, we should create a handler after calling Looper.prepare.

However, i know i have not used handler in code snippet when problem occurred.

This code snippet is:

new Thread() {
 @Override
 public void run() {
 super.run();
 String url = HaikangVideoManager.getRTSPURL(cameraID);
 if("".equals(url)) {
 Toast.makeText(context, "url invalid", Toast.LENGTH_LONG).show();
 return;
 }
 mLiveControl.setLiveParams(url, HaikangVideoManager.mName, HaikangVideoManager.mPassword);
 if(mLiveControl.LIVE_PLAY == mLiveControl.getLiveState()){
 mLiveControl.stop();
 }
 if (mLiveControl.LIVE_INIT == mLiveControl.getLiveState()) {
 mLiveControl.startLive(surfaceView);
 }
 }
 }.start();

How to solve this problem? you can do as follow step.

Step 1: Find position of problem occurred

Only when i find position of problem occurred, we can solve this problem easily, by logcat tool in  eclipse, we can find it very easily.

Step 2: Analysis this problem and Solve it

By Logcat tool, i know this problem occurred in Toast.makeText(context, “url invalid”, Toast.LENGTH_LONG).show();

Then i know why this problem occurred, because Tost.make should be run in main thread in android, but no in a sub thread.

To solve this problem is very simple, remove Toast.makeText(context, “url invalid”, Toast.LENGTH_LONG).show();


In Android project, we often have to get the height and width of a device, so that we can change our size of our ui to adjust to different devices, In android, to get these two information is simple, you can do one step.

Step 1: Use DisplayMetrics to get width and height of a device

In android, wen can use class DisplayMetrics to get the with and height of a device, code like this:


private void getScreenSize(){
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels; // width of screen
int screenHeight = dm.heightPixels;// height of screen
}

From code above, the screenWidth and screenHeight are what you want.


As a website designer, when we are designing our website, we should know whether people are using mobile ,pad or pc to visit our website, then our website can display them different scale page, mobile is small, pad is media and at last display big page in pc.

To answer this question we can use php, if your website is built by php, you can do like these two steps.

Step 1: Create a php function to check visitor are using mobile

To create a php function which can tell you whether visitors are using mobile or not, you can use code below:


function is_mobile_request()
{
 $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
 $mobile_browser = '0';
 if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
 $mobile_browser++;
 if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
 $mobile_browser++;
 if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
 $mobile_browser++;
 if(isset($_SERVER['HTTP_PROFILE']))
 $mobile_browser++;
 $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
 $mobile_agents = array(
 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
 'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
 'wapr','webc','winw','winw','xda','xda-'
 );
 if(in_array($mobile_ua, $mobile_agents))
 $mobile_browser++;
 if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
 $mobile_browser++;
 // Pre-final check to reset everything if the user is on Windows
 if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
 $mobile_browser=0;
 // But WP7 is also Windows, with a slightly different characteristic
 if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
 $mobile_browser++;
 if($mobile_browser>0)
 return true;
 else
 return false;
}


In an android project, I need create a oval shape textview to show some warning information, a demo like below.

oval shape textview in android

In this demo, i created a oval shap textview to show “This is a text”, if you also want to realize it, you can do as these steps.

Step 1: Create a background drawable xml file for this textview

You can create a xml file in res/drawable , it may call floatwarning_text.xml, then you can copy code below into this file and save it.


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
 <solid android:color="#cce8cf" />
 <corners android:radius="100dp"/>
 <stroke android:color="#cccacb" android:width="1dp"/>
 <padding android:left="5dp" android:top="5dp"
 android:right="5dp" android:bottom="5dp" />
</shape>


Yesterday, my boss asked me to write a program demo to get data at other website.His need is: if we use url:http://www.***.com/coord.php?coord=51.00, coord.php page will send a post request to website: http://www.***.com to and get ,print data.

From need, i know i should program a jsp demo, this functions are:

1.JSP page should send a post request to other website

2.JSP page should get response data and echo it.

To realize this need, we can do as follow:

Step 1: Create a jsp file

We can use eclipse to create a jsp file,meanwhile, you should make sure your created jsp file can be executed in your program, which means you should have a tomcat+jdk environment.

2 Steps to use http referer in php


Recently, When i see the traffic number of my blog, i notice most of visitors come form other website. Google Analytics shows what they are,as picture below shows.

php link reference

By Google Analytics, i find most of visitors of my sites are from linkreferral.com, once i find it, i have a question:How to know google analytics know where these visitor come from?

I have search some papers by google and know it is that http referer helps google analytics to know where these visitors are from.

Step 1: What is http referer

I think http referer is a link, which means if you visit my blog by click a google search result, the information ‘google.com’ will be stored up in http referer, then my website or other website statistics tool,like google analytics, will know where you are from.


Today i open a url by my browser, i find my eclipse show error:java.lang.OutOfMemoryError: PermGen space,which means tomcat use too much memory.Then the web system can not be opened correctly.

To fix this problem is easy, you can search much solutions by google, today i introduce my solution steps.

Step 1: Close your eclipse and edit eclipse.ini

If you have opened window of eclipse, you should close it.

Then you should open eclipse.ini file and edit it.

If you do not know where this file is, you can find it at the install path of your eclipse. For example, paht:D:\Program Files\eclipse is my eclipse install path and eclipse.ini file is in directory of D:\Program Files\eclipse.


Nowadays,QR code is used widely,we can see it almost everywhere, cell app, advertisements and some news websites. It is a type of tow-dimensional barcode and provide a new and fashion way to get new message for us. if you plan to add it to your website, your advertisement or video, you may wonder how to create it and today we introduce  to use php and google api to create one.

Step 1: Check some useful information before creating a qr code

qr code is a carrier of message and massage it can carry is limited, 4,296 alphanumeric characters is its toplimit. So if you plan to use a qr code to store up your information, you must be sure the length of your information is not longer than 4,296.

Category: PHP Programming

TAG


In article 2 Steps to convert png into ico file , i introduce steps to convert a png image into a ico, In that article, we use some online tools to do it.However, if you want to do it by php and plan to build a website to supply service of converting png to ico. I think you can read this post.

To convert png into ico file by php script, you use phpthumb to help us to do it, you can do as follow steps.

Step 1: Download phpthumb

You can click phpThumb to open page to download it, to realize function of converting png into ico, you should download these file:

phpthumb.ico.php

phpthumb.functions.php

Tips and Warnings:

1. If you can not download these two files, you can email me or leave your comment, i will send to you

2.To use phpthumb, you should make your php gd library enable, you can read article “2 Steps to make PHP GD library enable”  to enable it.