2015年10月15日 星期四

Android Layout getHeight = 0問題解決

在onWindowFocusChanged取得就可以

@Override
 public void onWindowFocusChanged(boolean hasFocus) {
RelativeLayout.getHeight();

}

2015年7月22日 星期三

Android 相機 切換鏡頭

出處:http://stackoverflow.com/questions/16765527/android-switch-camera-when-button-clicked



Button otherCamera = (Button) findViewById(R.id.OtherCamera);

OtherCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (inPreview) {
    camera.stopPreview();
}
//NB: if you don't release the current camera before switching, you app will crash
camera.release();

//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
    currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
    currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);

setCameraDisplayOrientation(CameraActivity.this, currentCameraId, camera);
try {

    camera.setPreviewDisplay(previewHolder);
} catch (IOException e) {
    e.printStackTrace();
}
camera.startPreview();
}
If you want to make the camera image show in the same orientation as the display, you can use the following code.
public static void setCameraDisplayOrientation(Activity activity,
         int cameraId, android.hardware.Camera camera) {
     android.hardware.Camera.CameraInfo info =
             new android.hardware.Camera.CameraInfo();
     android.hardware.Camera.getCameraInfo(cameraId, info);
     int rotation = activity.getWindowManager().getDefaultDisplay()
             .getRotation();
     int degrees = 0;
     switch (rotation) {
         case Surface.ROTATION_0: degrees = 0; break;
         case Surface.ROTATION_90: degrees = 90; break;
         case Surface.ROTATION_180: degrees = 180; break;
         case Surface.ROTATION_270: degrees = 270; break;
     }

     int result;
     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
         result = (info.orientation + degrees) % 360;
         result = (360 - result) % 360;  // compensate the mirror
     } else {  // back-facing
         result = (info.orientation - degrees + 360) % 360;
     }
     camera.setDisplayOrientation(result);
 }

2015年6月16日 星期二

Android 變更Toast位置

Toast toast=Toast.makeText(mActivity,"test", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER, 0, 0);
toast.show();

2015年5月21日 星期四

Android ScrollView + WebView Layout

<ScrollView
        android:id="@+id/my_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

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

            <WebView
                android:id="@+id/my_web"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="125dp" >
            </WebView>
        </LinearLayout>
    </ScrollView>

2015年4月15日 星期三

Android Wear 取消往左滑關閉功能

If the user interaction model of your app interferes with the swipe-to-dismiss gesture, you can disable it for your app. To disable the swipe-to-dismiss gesture in your app, extend the default theme and set theandroid:windowSwipeToDismiss attribute to false:
<style name="AppTheme" parent="Theme.DeviceDefault">
    <item name="android:windowSwipeToDismiss">false</item>
</style>

2015年3月10日 星期二

android post

new Thread(new Runnable(){
   @Override
   public void run() {
       // TODO Auto-generated method stub        
   
    POST("http://210.243.166.178/apps/Exhibition/api/getSpecificData.php");
   }          
}).start();








public static String POST(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name","test");
            jsonObject.accumulate("number","001");

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // ** Alternative way to convert Person object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
         
            Log.d("ddddd", "ddddd result:"+result);

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
       BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
       String line = "";
       String result = "";
       while((line = bufferedReader.readLine()) != null)
           result += line;

       inputStream.close();
       return result;

   }

2015年3月4日 星期三

Android 發出嗶聲

ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);

2015年2月8日 星期日

Android internal storage file

//save

public static boolean storeInsideImage(Context context, Bitmap image, String filepath, String filename) {


 File infilepath = new File(context.getFilesDir().getAbsoluteFile(), filepath);
 if (!infilepath.exists()) {
  infilepath.mkdirs();
 }

 try {

  File imgfile = new File(infilepath, filename);
  if (!imgfile.exists()){
   imgfile.createNewFile();
  }
  FileOutputStream fileOutputStream = new FileOutputStream(imgfile);
  BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
  // choose another format if PNG doesn't suit you
  image.compress(CompressFormat.JPEG, 100, fileOutputStream);
//   fileOutputStream.flush();
//   fileOutputStream.close();
  bos.flush();
  bos.close();
  return true;
 } catch (FileNotFoundException e) {
  Log.w("TAG", "Error saving image file: " + e.getMessage());
  return false;
 } catch (IOException e) {
  Log.w("TAG", "Error saving image file: " + e.getMessage());
  return false;
 }
 }


//load & delete

private void loadImageFromStorage(String path)
{

   try {
    //先刪除上一張
    //File dir = getFilesDir();
    File file = new File("/data/data/com.udn.nm.food/files/GoodFood/data/Files", "login.jpg");
    boolean deleted = file.delete();
    Log.d("ddddddd", "ddddddd deleted"+deleted);
   
       File f=new File(path, "login.jpg");

       Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
       if(b !=null){
        imageView1.setImageBitmap(b);
       }
       else{
        imageView1.setBackgroundResource(R.drawable.login_bg);
       }
     
         //  ImageView img=(ImageView)findViewById(R.id.imgPicker);
      // img.setImageBitmap(b);
   }
   catch (FileNotFoundException e)
   {
    imageView1.setBackgroundResource(R.drawable.login_bg);
       e.printStackTrace();
   }

}

}


2015年1月22日 星期四

Android不讓弹出鍵盤擋住View

AndroidManifest.xml 加adjustPan
 <activity
....
....
.
 android:windowSoftInputMode="adjustPan"

</activity>

2015年1月21日 星期三

OpenLDAP for windows(連接mysql)

openldap 版本:openldap-2.4.38-x86

下載網址http://sourceforge.net/projects/openldapwindows/

安裝步驟 一直下一步就好(安裝路徑我是設在C:\OpenLDAP)

安裝完後打開 C:\OpenLDAP\etc\openldap\slapd.conf

找到BDB database definitions部分
可以修改下面3行(我是用默認的,做測試用的而已)         
suffix "dc=my-domain,dc=com"
rootdn "cn=Manager,dc=my-domain,dc=com"
rootpw test


過來就是連接mysql部分
找到# MySQL Database  修改資料庫資料
backend              sql
database             sql
suffix               "dc=example,dc=com"
rootdn               "cn=root,dc=example,dc=com"
rootpw               test
dbname               openldap    #資料庫表名稱
dbuser               root         #資料庫帳號
dbpasswd           ******     #資料庫密碼
insentry_stmt       "INSERT INTO ldap_entries (dn,oc_map_id,parent,keyval) VALUES (?,?,?,?)"
subtree_cond         "ldap_entries.dn LIKE CONCAT('%',?)"
upper_func           "upper"
concat_pattern       "?+?"
has_ldapinfo_dn_ru   no
check_schema         yes
database        monitor


修改完到C:\OpenLDAP\etc 打開odbc.ini

找到MySQLTestServer 改成

[openldap]  #資料庫表名稱
Driver=MySQL
Description=Test MySQL Database 2013
Server=localhost
Port=3306
Database=openldap #資料庫表名稱
# UID=openldap
Password=*****  #資料庫密碼


改完後到C:\OpenLDAP\etc\back-sql\mysql  

把01_backsql_create.sql,
   02_testdb_create.sql
   03_testdb_data.sql
   04_testdb_metadata.sql
都匯到資料庫


設定完後到C:\OpenLDAP\libexec  按StartLDAP.cmd  啟動

啟動完就可以連了

JavaScript‎ 列印

 <script type="text/JavaScript">
        function printpage()
        {
            window.print()
        }
    </script>

2015年1月14日 星期三

Android update ViewPager View


@Override
public Object instantiateItem(ViewGroup container, int position) {
    View view = null;
    view = mInflater.inflate(R.layout.record_list_layout, null);          
    TextView test= (TextView) view.findViewById(R.id.test);
    String key = "test" + position;

    test.setTag(key);
  ((ViewPager) arg0).addView(view );
    return view;
}

//0為第一筆
TextView test= myViewPager.findViewWithTag("test0");
// 更新內容
if (test!= null ) {
    test.setText("update");
}

2015年1月12日 星期一

JAVA 亂數排序 Collections.shuffle

        ArrayList<String> list=new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        Collections.shuffle(list);
         
        for(String result:list)
        {
         System.out.println(result);
        }