2012年6月29日 星期五

Android 重製ListView

在Google 搜尋這類的資料,其實還蠻多的,大致上都說明的很清楚

其中因為資料過多,當超過6~7筆(依螢幕大小,不同)

在滑動會有資料跳動要注意




在這邊,我是因為部份資料要使用刪除線,但滑動後卻都是刪除線

經過學長的指教,才知道資料一開始會全部已經轉成刪除線,當遇到不用改變時

已經變成刪除線TextView時,當然看到全都是刪除線!!!

所以這時要在另加入恢復成原本,才可以。


2012年6月4日 星期一

Android 讀取JSON

使用方法如下

//將資料寫入JSONArray
JSONArray result = new JSONArray(json_data);
//取出陣列內所有物件
for(int i = 0;i < result.length(); i++) {
    //取出JSON物件
    JSONObject stock_data = result.getJSONObject(i);
    //取得物件內資料
    System.out.println("t:"+stock_data.getString("t"));
    System.out.println("l_cur:"+stock_data.getString("l_cur"));
    System.out.println("c:"+stock_data.getString("c"));
    System.out.println("cp:"+stock_data.getString("cp"));
}


參考資料:http://kie0723.blogspot.tw/2010/12/android-json.html






Android TextView line-through 刪除線

在TextView上加入刪除線

方法如下
TextView textview = (TextView) findViewById(R.id.textview1);
Paint paint = textview.getPaint();
paint.setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
paint.setAntiAlias(true);


轉回來
TextView textview = (TextView) findViewById(R.id.textview1);
Paint paint = textview.getPaint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);



使用Android將檔案傳到Server use PHP

首先先說明Android

在這邊是使用HttpClient來實現上傳,程式如下
public void UploadFiles(String PathFile) {
    new Thread() {  
        @Override  
        public void run() {  
            super.run();  
            
            List< NameValuePair> params = new ArrayList< NameValuePair>();
            params.add(new BasicNameValuePair("file",PathFile));
            
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("Server Address/update.php");
            
            try{
                //setup multipart entity
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                for(int i=0;i< params.size();i++){
                    //identify param type by Key
                    if(params.get(i).getName().equals("file")){
                        File f = new File(params.get(i).getValue());
                        FileBody fileBody = new FileBody(f);
                        entity.addPart("image"+i,fileBody);
                    }else{
                        entity.addPart(params.get(i).getName(),new StringBody(params.get(i).getValue()));
                    }
                }
                post.setEntity(entity);

                //create response handler
                ResponseHandler< String> handler = new BasicResponseHandler();
                //execute and get response
                UploadFilesResponse = new String(client.execute(post,handler).getBytes(),HTTP.UTF_8);
                if(D) Log.e(TAG, "--- response ---"+ UploadFilesResponse);
            }catch(Exception e){
                e.printStackTrace();
            }
        }  
    }.start();  
}

粉紅字是你要上傳檔案的路徑
紅色字是你的Server路徑


接著在Server寫一隻PHP檔案

update.php
<?php 
    if(move_uploaded_file($_FILES['image0']['tmp_name'], "./ImageFiles/".$_FILES['image0']['name'])){
        echo "uploaded";
    }else{
        echo "unsuccessfully";
    }
?>

因為在Android在上傳資料寫法,是使用多檔案上傳的方式,也就是For迴圈那邊,

所以在PHP也應該是這樣寫,但我PHP並沒直接跑迴圈,就直接抓第一筆  $_FILES['image0']


如果在PHP有必要接收兩個檔案以上,直接在裡面加入迴圈,就可以了



最後記得在Server的路徑建立資料夾,不然傳不上去








Android開啟相機,讀取圖片

在Android開啟相機有幾種寫法,有使用預設相機拍攝,另外一種是自己去撰寫相機的APP

對於單純透過相機取得照片,使用預設相機拍攝就好

因為大部份預設都自動對焦、調整相機細節等等,很方便

除非你是要自己寫專屬的相機,就要自己去刻那些Code


在這裡提供使用預設相機拍攝



首先在Manifest加入使用相機的權限
<!-- Camera -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />


接在著程式寫入
//設定檔名
File tmpFile = new File( Environment.getExternalStorageDirectory(), "image.jpg");
Uri outputFileUri = Uri.fromFile(tmpFile);
 
Intent intent =  new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);    //利用intent去開啟android本身的照相介面 
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
startActivityForResult(intent, 0);

其中裡面的

new File( 路徑, 檔名)

Environment.getExternalStorageDirectory():指SD Card 路徑

這個也是之後拍完照後會儲存至指定的路徑


當拍完後會去丟一個回應,接著再用ImageView物件去顯示,顯示方如下
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    super.onActivityResult(requestCode, resultCode, data);
    if(D) Log.e(TAG, "--- onActivityResult  ---");
    if (resultCode == RESULT_OK) {
        String img_address = Environment.getExternalStorageDirectory()+"image.jpg";
        Bitmap bmp = BitmapFactory.decodeFile(img_address); //利用BitmapFactory去取得剛剛拍照的圖像
        ImageView ivTest = (ImageView)findViewById(R.id.imageView1);
        ivTest.setImageBitmap(bmp);
        
    }
}











2012年5月2日 星期三

在Android使用httpclient傳值讀值

在使用httpclient必需先去 這裡下載 java jar

我是使用HttpClient 4.1.3 (GA) 這個版本

首先先說明如何讀取HTML
public static String getHtmlContent(final String url) {
    String result="";
    HttpGet httpRequest = new HttpGet(url);
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse httpResponse = httpclient.execute(httpRequest);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result;
}

傳入URL後就會讀取HTML

如果要比對字串,會多一個字元,我不知道是不是因為我用PHP的echo的關係
在比對時要再後面多加一個 "\n"

在來是POST資料到指定的網址,並回傳字串
public static String postData(String url, List<NameValuePair> params) {
    String result="";
    HttpPost httpRequest = new HttpPost(url);
    try {
        httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
        
        if(httpResponse.getStatusLine().getStatusCode() == 200){
            result = EntityUtils.toString(httpResponse.getEntity());
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result;
}

不過在使用這函式時要配合使用
List<NameValuePair> params= new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data","1234567"));
params.add(new BasicNameValuePair("data1","000000"));
postData("http://iccl.nkmu.edu.tw/WSN/getData.php", params)

如果有兩個值就要像上面那樣add兩次,以此類推



2012年4月27日 星期五

C2DM Server(for PHP) (3)

更新:2013/04/01

發現有很多人搜尋到這篇,C2DM已經更名為GCM(Google Cloud Messaging for Android)

幫大家到找一個比較詳細的說明及操作,大家參考吧


參考資料:

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

=========================================================================================================================================


Server 這一端不管用什麼Server都可以,可以使用Google App Engine(GAE)或是PHP都可以

如果使用GAE可以參考KEN YANG  http://blog.kenyang.net/2012/03/android-c2dm-sever.html


這裡主要以PHP為主,在C2DM我們需要前面提到SENDER_ID的Email和密碼

因為需要透過驗證得到Auth,透過那個Auth將訊息傳送出去,接下來實作。


我Google了一下發現有人已經有提供C2DM-PHP   https://github.com/lytsing/c2dm-php

不過我使用過後發現不曉得是改版過後還是什麼問題,導致現在這個版本在讀取Auth時

會出現get auth token error錯誤,無法傳送訊息


因此我自己改寫了一下在這裡下載


我稍為節省了一個步驟,在一開始就先把基本資料輸入進去

$c2dm = new c2dm($useremail ,$useremail_passwd , $long_registration_id);

在這邊就會先去跟 https://www.google.com/accounts/ClientLogin 抓你的 auth

錯誤也會在這裡顯示

接著

$c2dm->sendMessage(1,"Hello World!!");

就可以把你的訊息傳送出去,就完成了


其中c2dm.php要注意一下 94行
'data.message'    => $message //TODO: Add your data here.

data.message是data.[key],所以你Android MESSAGE_KEY_ONE 裡的字串是要一樣的
也就是說如果要改變數,PHP和Android兩邊的變數名稱要一樣


大功告成





有興趣可以到以下的參考連結:
http://blog.kenyang.net/2011/12/android-c2dm.html                 :)
http://blog.kenyang.net/2011/12/android-c2dm_22.html           :P
http://blog.kenyang.net/2012/03/android-c2dm-sever.html        :D
http://blog.kenyang.net/2012/03/android-c2dm-android.html     XD