2013年7月8日 星期一

EditText 類別setText遇到數字型態會出錯?

EditText 類別setText遇到數字型態會出錯?
嗯,因為....setText(int)指的是從resource的id找出string對應物件出來設定文字的
沒給你出現亂碼已經很客氣了
那如何定「數字」進去?
跟javascript一樣,在前面加個空字元就可以了,ex: editTxt.setText(""+number);
就是這麼簡單.

For Android: How to setup checked radio button in RadioGroup programmatically

注意順序,是先加入RadioGroup再設定其checked Id.
===============================================
 LinearLayout.LayoutParams param4RdoGrp=new LinearLayout.LayoutParams(
 ViewGroup.LayoutParams.WRAP_CONTENT,
 ViewGroup.LayoutParams.WRAP_CONTENT
 );
 param4RdoGrp.setMargins(16, 0, 0, 0);
 radioGroup=new RadioGroup(activityContex);
 radioGroup.setOrientation(RadioGroup.HORIZONTAL);
 radioGroup.setLayoutParams(param4RdoGrp);
 currentView.addView(radioGroup);
      int checkId=-1;
 for(int i=0;i<options.length;i++){
          RadioButton rdoBtn=new RadioButton(activityContex);
          rdoBtn.setText(options[i]);
          radioGroup.addView(rdoBtn);  <--先加入有了id再決定怎麼做
          if(options[i].equals(selectedOption)){
        // rdoBtn.setChecked(true);   <--這樣不行,會把radio button 卡住!!
         checkId=rdoBtn.getId();
          }
         
 }
 if(checkId!=-1){
 radioGroup.check(checkId);   <--這時才能設定check!!
 }
=======================================

2013年7月7日 星期日

SharedPreferences無法儲存!?

這問題花了我幾小時,最後還是在另一本書上看到的
先看一下錯誤的寫法:
   =============以下是錯誤的,小心==============
  SharedPreferences prefer= PreferenceManager.getDefaultSharedPreferences(
 GeneralLib.APPLICATION_CONTEXT);
   prefer.edit().putString("xxxxxValue",xxxx);
   prefer.edit().putString("bbbbValue",bbb);
   prefer.edit().commit();
==========================================
這看起來是對的,不過值一直都沒存入

那,什麼才是正確寫法?
用pipe方式接力下去就可以了
===========正確寫法====================
   prefer.edit().putString("xxxxxValue",xxxx).putString("bbbbValue",bbb).commit();
================================
為什麼? 因為每次「prefer.edit()」會產生一個「新的」edit的內容
所以才會有這樣的現象,小心


2013年7月5日 星期五

how to calculate the height of ListView ?

since ScrcollView is not  allow to add a scrollable listview
so you have to findout the listview hieght after it's created.
here is  is the usefull LINK
see the code snippet:
==================================

        public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter(); 
            if (listAdapter == null) {
                // pre-condition
                return;
            }

            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }

            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
        }
    
===================================

how to scroll to top after showing a long big ScrollView?

    
=======in your activity,override the  onWindowFocusChanged event=============
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        ScrollView scrollView = (ScrollView) findViewById(R.id.someScrollView);
        scrollView.scrollTo(0, 0);
    }
======================================================================

2013年7月4日 星期四

如何取得extjs4 容器物件中的items內容?

有時我們必須列舉容器(container/panel)的內容
但items不是個陣列而已,是個「AbstractMixedCollection」
所以要用他的方法取得
        var attrItem = Ext.getCmp('xxxxx').items;
        for (var i = 0; i < attrItem.getCount() ; i++) {
           var panel=attrItem.getAt(i);
                panel.....
        }
====以上,加油了=====

for extjs4 一個有關動態resize window案例


請注意其中的「autoHeight」「resizable」「layout」等設定
還有「fire resize event」的動作
================================
Ext.define('GtmExtjs.view.WinEditProduct', {
    ...
    ....
     ....
    autoHeight: true,
    resizable :true,
    width: 428,
    layout: {
        type: 'fit'
    },
    title: 'Product Information',
    modal: true,
    ....
    ....
    ....
    initComponent: function () {
        var me = this;
        me.initialConfig = Ext.apply({
            trackResetOnLoad: true
        }, me.initialConfig);
        Ext.applyIf(me, {
            items: [
                {
                    xtype: 'form',
                    region: 'center',
                    itemId: 'formProdInfo',
                    method: 'POST',
                    trackResetOnLoad: true,
                    url: '/GoingTvMall/Product/handleProduct',

                    layout: {
                        columns: 3,
                        type: 'table'
                    },
                    autoHeight: true,
                    resizable: true,
                    bodyPadding: 10,
                    items: [
                              ....
                               ....
                        {
                            xtype: 'button',
                            margin: 5,
                            text:'add attr',
                            width: 100,
                            handler: function () {
                                var attrEditor = Ext.create('GtmExtjs.view.PnlAttrEditor',
                                    { parentPnl: Ext.getCmp('pnl4Attr') });
                                Ext.getCmp('pnl4Attr').add(attrEditor);
                                Ext.getCmp('pnl4Attr').updateLayout();
                                var xntHeight = me.height;
                                me.fireEvent('resize', me, 428, xntHeight, null);
                               
                            }
                        },
============================================

2013年6月28日 星期五

android : 確認google定位權限

原文參考在此
===================跳去權限設定畫面=======================
註:
Explanation of above code.

1. First we need to create LocationManager.

LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
2. using isProviderEnabled Check location providers are already enabled or not.
  1. private void checkLocationProviders(){  
  2.     //String provider = Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);  
  3.        if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
  4.              
  5.            Toast.makeText(EnableLocationActivity.this"GPS provider Enabled: ",Toast.LENGTH_LONG).show();  
  6.           
  7.        }else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){  
  8.              
  9.            Toast.makeText(EnableLocationActivity.this"Network provider Enabled: ",Toast.LENGTH_LONG).show();  
  10.              
  11.        }else{  
  12.            AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  13.            builder.setMessage("Location providers are not available. Enable GPS or network providers.")  
  14.                   .setCancelable(false)  
  15.                   .setPositiveButton("Yes"new DialogInterface.OnClickListener() {  
  16.                       public void onClick(DialogInterface dialog, int id) {  
  17.                           Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
  18.                       startActivityForResult(intent, 1);  
  19.                       }  
  20.                   })  
  21.                   .setNegativeButton("No"new DialogInterface.OnClickListener() {  
  22.                       public void onClick(DialogInterface dialog, int id) {  
  23.                           EnableLocationActivity.this.finish();  
  24.                       }  
  25.                   }).show();  
  26.              
  27.              
  28.        }  
  29.   
  30.    }  
  31.      
  32.    @Override  
  33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  34.        checkLocationProviders();  
  35. super.onActivityResult(requestCode, resultCode, data);  
  36. }  
以下原文參考

=========設定好之後,可以進行Google location功能了=================================
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        LocationListener locationListener = new LocationListener() {
          void onLocationChanged(Location location) {
          // redraw the marker when get location update.
          drawMarker(location);
        }

        if(location!=null){
           //PLACE THE INITIAL MARKER              
           drawMarker(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
    }
}

private void drawMarker(Location location){
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()));
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
    .title("ME"));
}

2013年6月24日 星期一

如何從android client post中文到server去?

Just give me the code!!
==============================
....
....
....
 HttpPost httppost = new HttpPost("http://"+SERVER_ADDRESS+destPath);
       // Add your param
   java.util.Iterator<String> keys= keyAndValue.keySet().iterator();
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
   while(keys.hasNext()){
    String key=keys.next();
    String value=keyAndValue.get(key);
       nameValuePairs.add(new BasicNameValuePair(key, value));
   }
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
       
       // Execute HTTP Post Request
       HttpResponse response = httpclient.execute(httppost);
     
       BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
       String str=reader.readLine();
   ...
  ....
  ...
==============================================================

2013年6月22日 星期六

for android : 最小單位的TabHost & Tabspec 框架

 layout---「activity_store_unit.xml」的內容
================================================
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/TabHost1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EF7B2F"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".StoreProdListActivity" >

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

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal" >

            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab2"
                android:layout_width="match_parent"
                android:layout_height="match_parent" 
                android:orientation="horizontal">
            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab3"
                android:layout_width="match_parent"
                android:layout_height="match_parent" 
                android:orientation="horizontal">
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>

</TabHost>
==============================================

*.java
============================================
package com.neo_tech.goingtvmall.frontend;

import android.os.Bundle;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.app.TabActivity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;

public class StoreUnitActivity extends Activity {
              //extends TabActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_unit);
TabHost tabHost=(TabHost)findViewById(R.id.TabHost1);
   //tabHost.setup();
LocalActivityManager mLocalActivityManager = new LocalActivityManager(this, false);
mLocalActivityManager.dispatchCreate(savedInstanceState);
tabHost.setup(mLocalActivityManager);
TabSpec tbs=tabHost.newTabSpec("tab1");
    tbs.setIndicator("店家資訊");
    tbs.setContent(new Intent(this,
StoreIntroductionActivity.class ));
    try{
    tabHost.addTab(tbs);
tabHost.addTab(
tabHost.newTabSpec("tab2").setIndicator("有什麼產品呢?").setContent(new Intent(this,
StoreProdListActivity.class ))
);
tabHost.addTab(
tabHost.newTabSpec("tab3").setIndicator("選了什麼?").setContent(new Intent(this,
StoreCartActivity.class ))
);
   
    }catch(Exception exp){
                   exp.printStackTrace();
                   Log.e("error",exp.getMessage());
    }
   
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.store_unit, menu);
return true;
}

}
================================================