顯示具有 [Android] 標籤的文章。 顯示所有文章
顯示具有 [Android] 標籤的文章。 顯示所有文章

2017年12月5日 星期二

Okhttp3 onResonse報java.lang.IllegalStateException: closed Error

今天在試OKhttp3時,

發現


 OkHttpClient okHttpClient = new OkHttpClient();


        Request request = new Request.Builder()
                .url(DATA_URL)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: " + response.body().string());
                String result = response.body().string();
                parseJson(result);
            }
        });


這樣寫居然會報

java.lang.IllegalStateException: closed

                                                                                 


此exception,

後來發現

原來

 response.body().string()

被調用一次就會被close了,

只要將 Log.d註解起來,直接存入String再使用即可通過編譯

2015年6月2日 星期二

Android Studio 使用Git設定

Android Studio 使用Git設定

1. 先到Android Studio VCS→ Import into Version Control → Create Git Repository

2. 在GitLab或GitHub上建立專案。

3. 將Git上面的指令選擇Https, Git init那幾行指令 貼到你的terminal

4. 專按右鍵Git→Add 後 就可以進行commit 、push

2014年11月18日 星期二

Git "....java did not match any file(s) known to git..."問題

今天使用IntelliJ IDEA的Git pull 與 push時,

一直出現以下的錯誤

Error:error: pathspec 'src/com/aaaa/bbbb/cccc/dddd/DMF.java' did not match any file(s) known to git.
  during executing git commit --only -F /private/var/folders/6h/zv5mh4px15d6yjksw693q_s40000gp/T/git-commit-msg-5225757047314811222.txt -- src/com/aaaa/bbbb/cccc/dddd/DMF.java

苦惱了一個上午,

最後找到原因是因為IDEA的IDE透逗怪怪的,

只要把該檔案做commit 但不要用IDE去做

去terminal下指令


git commit -m commitMessage


再用IDE或指令去pull  or push

這樣就可以正常囉


2014年9月15日 星期一

Android 分享文字訊息至Line

Android 指定開Line App傳入文字訊息

通常Android要開啟第三方App需知道對方app的package name


 PackageManager pm = mContext.getPackageManager();
        List<applicationinfo>  appList =  pm.getInstalledApplications(0);
        for(ApplicationInfo app: appList )
        {
            Log.i("info","app:" +  app );
            if( app.packageName.equals(LINE_PACKAGE_NAME))
            {

                return true;
            }
        }

上面的方法 可以抓出手機內所有的App package name

而你會發現Line的App Package Name的名稱是 jp.naver.line.android

故當程式可用此方式來檢查是否裝此app

若要從程式碼傳送文字至 Line訊息的話


intent.setAction(Intent.ACTION_SEND);
intent = mContext.getPackageManager().getLaunchIntentForPackage(AppConfig.LINE_PACKAGE_NAME);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "this is test! oh ya!");
mContext.startActivity(intent);

上面是送文字訊息

而AndroidManifest.xml 記得要加接收到ACTION_SEND的intent filter


<intent-filter >
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter >


2014年9月1日 星期一

[android]BaseAdapter 刷新資料避免重覆內容

這幾天在Android遇到了這個問題

就是在自訂Android的BaseAdapter的時候

getView重覆進去跑了

查到有人說

listview的layout 長寬要設定為match_parent


另一種是說ListView要更新

yourAdapter.notifyDataSetChanged();

但結果還是一樣

因為我在getview去動態產生內容

所以要去把之前的layout刪除 

才不會有重覆的內容產生在listview



 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewTag viewTag;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.layout_item, null);
            viewTag = new ViewTag((TableLayout) convertView.findViewById(R.id.tableLL),
                    (TextView) convertView.findViewById(R.id.question));
            convertView.setTag(viewTag);
        }
        else
        {
            viewTag = (ViewTag) convertView.getTag();
            viewTag.tableLL.removeAllViews();
        }

2014年3月19日 星期三

Android Webview javascript與Java 互動傳參數

重點是 要先設定

webview.setWebChromeClient(new WebChromeClient());
webview.addJavascriptInterface(new JavaScriptInterface(), "android");

於 HTML 的javascript加入

function executeFromObjCall(str)
{
    alert("execute from objective c call params:" + str);
            
}


然後在你的java檔加入

webview.loadUrl("javascript:executeFromObjCall('passValue');");


這樣就可以呼叫webview javascript檔

並由java傳值到javascript

 若要從javascript呼叫java的code的話

 我們先在javascript去呼叫某個function

如call callJavaFunction:


function callJavaFunction()
{                
   var str = window.android.callJavaMethod();
   alert(str);
}


在java code去新增

 public class JavaScriptInterface {
      public String callJavaMethod() {
           
       Log.i("info", "called from javascript execute in java");
       return "this is return params from java";
   }
}

JavaScriptInterface 是在上面有new JavaScriptInterface()的關係~ 

這樣就可以透過javascript呼叫java並回傳java的值到javascript了


2013年12月18日 星期三

Android APK 反編譯 為Java檔

若要參考別人的原始碼來學習,

一種方式就是將APK檔 反編譯回 JAVA檔,

此種方式需先下載兩個檔

分別是

dex2jar

JD-GUI

首先先將 手上的apk檔 把副檔名改成壓縮檔(zip or rar...),

再將此壓縮檔解壓縮出來,你會看見有一個classes.dex檔,

我們要將此.dex檔轉成jar檔再透過JD-GUI反編譯為原始的java程式碼。

下載完dex2jar後,到dos下執行指令

dex2jar.bat  classes.dex

接下來你會看見classes.dex.dex2jar.jar的檔生成在dex2jar.bat這個目錄之下。

接下來再去執行 JD-GUI 將這個jar檔開啟..所有的程式碼就出現囉..

2013年10月15日 星期二

Android GCM問題 -- GCMIntentService (has extras) }: not found

這個問題卡了我好久多天

Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTRATION flg=0x10 pkg=   cmp=xxx.xxx.xxx  /.GCMIntentService (has extras) }: not found


通常GCMIntentService都會存在根目錄(root)之下,
所以android的gcm去抓GCMIntentService是去抓root的file,


但如果的project有許多package name的話,


你必須要去修改 GCMBroadcastReceiver 回傳GCMIntentService的class package name,



所以要自訂一個GCMReceiver去繼承GCMBroadcastReceiver,

並Override 掉 getGCMIntentServiceClassName 回傳你的GCMIntentService的package name,



再去修改AndroidMainfest.xml 的receiver android:name 與service android name



您可以參考 這篇:

http://stackoverflow.com/questions/12089428/gcm-with-custom-broadcastreceiver



http://dexxtr.com/post/28188228252/rename-or-change-package-of-gcmintentservice-class

2013年10月2日 星期三

google-play-services_lib/bin(missing) 錯誤問題

原本要來試 Google Play Services的功能,

但第一步居然就讓我卡關卡了幾天= =

使用Google play services 需要先到AVD安裝Google Play Services 的SDK,

然後再到eclipse內 import->android->existing android code into workspace

匯入google play services的專案,

專案路徑是在你Android SDK的資料夾/extras/google/google_play_services

把此專案import後,

重點是在你自己的專案按右鍵->Properties ->Android->Add->會看見google-play-services-lib的專案,點選他,

若您沒有看見就是前面的步驟有誤。

記得is Library不需要打勾,

照理說這樣就可以很容易的使用到Google play services的lib了,

可是在發佈時會出現

google-play-services_lib/bin(missing) 錯誤問題

最後我的解決方案是

按下我的專案右鍵->java compiler->enable project is specific打勾

把compiler compilance level: 1.6先改1.7 按下確定後

再按專案右鍵  android tools->fix project properties

然後發佈看是否能成功編譯

成功的話再將1.7再改回1.6 重新再做一次fix project properties

然後也把專案project->clean

這樣就正常了= =

感覺是eclipse的問題..

以上是我個人試成功的經驗,不一定是最正確的方式~提供參考

=============2013.10.07===============
今天又遇到此問題

以上方式還是出現一樣error

後來嘗試把jar檔通通移除重新加次一次就可以囉~





2013年10月1日 星期二

更新ADT後發出 Multiple dex..錯誤解決方案

昨日更新了ADT,

把之前的專案發佈一直出現以下error,

花了一個小時才解決..


Dex Loader] Unable to execute dex: Multiple dex files define Lorg/kobjects/isodate/IsoDate

我的解決方式是將jar檔刪除,重新加入一次,

然後記得不要加到沒有用到的jar檔,

我把android-support-v4.jar拿掉,

重新發佈問題就解決了~

2013年7月29日 星期一

screen size 網站

http://screensiz.es/phone

2013年7月23日 星期二

限制app只能在平板上執行

可以參考官網說明: http://developer.android.com/guide/practices/screens-distribution.html#FilteringTabletApps

在manifest內加入



 ... >
     android:smallScreens="false"
                      android:normalScreens="false"
                      android:largeScreens="true"
                      android:xlargeScreens="true"
                      android:requiresSmallestWidthDp="600" />
    ...
     ... >
        ...
    

其中要注意的是   android:requiresSmallestWidthDp="600" 這一項

要在properties build Target執行android 3.2以上才有支援提供,

不然你會出現以下error訊息:

No resource identifier found for attribute 'requiresSmallestWidthDp' in package 'android



Android ksoap發生status:500 error

昨天使用 ksoap 卡了幾小時的關,

錯誤訊息如下:


: W/System.err(10053): java.io.IOException: HTTP request failed, HTTP status: 500
: W/System.err(10053):  at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:195)
: W/System.err(10053):  at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:116)
: W/System.err(10053):  at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:111)
: W/System.err(10053):  at net.xxx.ooo.activity.abc.loadWebService(HospitalVisitMain.java:147)
: W/System.err(10053):  at net.xxx.ooo.activity.abc.access$4(HospitalVisitMain.java:130)
: W/System.err(10053):  at net.xxx.ooo.activity.abc$2.run(HospitalVisitMain.java:98)
: I/info(10053): HTTP request failed, HTTP status: 500




後來發現的原因是,沒有輸入參數送到webservice,= =

網路有查到也有人遇到是ksoap的jar檔有問題,

若有遇到的人也可以嘗試更換ksoap的jar檔~

傳參數到webservice

只要加入


SoapObject request = new SoapObject(SysServerParam.getInstance()
    .getNameSpace(), SysServerParam.getInstance().getWebSiteMeth());
  

  request.addProperty("username", SysServerParam.getInstance().getUserName() );
  
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
  envelope.bodyOut = request;
  envelope.dotNet = true;
  envelope.setOutputSoapObject(request);

HttpTransportSE androidHttpTtansport = new HttpTransportSE(
    SysServerParam.getInstance().getServerURL(), 10000);

  androidHttpTtansport.debug = true;

而上面我多加了10000 是指定若網頁讀取超過10秒鐘

則跳到catch事件~

2013年6月10日 星期一

android dialog

此文章您無權限 呼叫 getAlertDialog("警告", "請輸入帳號").show();



private AlertDialog getAlertDialog(String title, String message){

        //產生一個Builder物件

        Builder builder = new AlertDialog.Builder(this);
        //設定Dialog的標題
        builder.setIcon(R.drawable.alert_icon);
        builder.setTitle(title);
        //設定Dialog的內容
        builder.setMessage(message);
        //設定Positive按鈕資料
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
               
            }
        });
        //利用Builder物件建立AlertDialog
        return builder.create();

    }

2013年5月6日 星期一

Android設備統計

在Android平台開發到底要合適哪個版本的平台是很重要的~

可以參考google 的統計

http://developer.android.com/about/dashboards/index.html


這是到2013.05.01的統計  android 2.3.3 已經有38.4%了




2013年5月5日 星期日

mac安裝eclipse的svn外掛(subclipse)


mac安裝eclipse的svn外掛(subclipse)

我的系統是mac os 10.7.5

eclipse-->help-->install new software --> add

name就隨意打(ex:subclipse) ,網址打 

http://subclipse.tigris.org/update_1.8.x 

出現subclipse與svnKit 都打勾,一直下一步安裝結束重開ecilpse。

重開完畢到偏好設定->Team->SVN ->team

發現javaHL出問題,

然後網路說要自己更新javaHK

http://www.macports.org/install.php  下載對應的 pkg檔(看你是Lioin還是mountain還是雪豹)

下載完安裝,

然後去terminal執行  (先移到root根目錄)

sudo port install subversion-javahlbindings

若發現 出現   

Error: Port subversion-javahlbindings not found 的錯誤,

請先執行

sudo port -v selfupdate

結果若又出現 

-->  Updating MacPorts base sources using rsync
rsync: failed to connect to rsync.macports.org: Connection refused (61)
rsync error: error in socket IO (code 10) at /SourceCache/rsync/rsync-42/rsync/clientserver.c(105) [receiver=2.6.9]
Command failed: /usr/bin/rsync -rtzv --delete-after rsync://rsync.macports.org/release/tarballs/base.tar /opt/local/var/macports/sources/rsync.macports.org/release/tarballs
Exit code: 10
Error: /opt/local/bin/port: port selfupdate failed: Error synchronizing MacPorts sources: command execution failed

的錯誤的話,

先確認 你網路的port或防火牆是不是有檔,

或你先換個3G網路試試

執行  sudo port -v selfupdate 成功的話會出現以下

-macteki-MacBook-Pro:/ mac$ sudo port selfupdate

--->  Updating MacPorts base sources using rsync
MacPorts base version 2.1.3 installed,
MacPorts base version 2.1.3 downloaded.
--->  Updating the ports tree
--->  MacPorts base is already the latest version

The ports tree has been updated. To upgrade your installed ports, you should run
  port upgrade outdated
  
  
 然後再執行  

 sudo port install subversion-javahlbindings

 就會開始安裝,要一陣子讓他跑一下~

 以上~

2013年4月26日 星期五

android模擬器安裝中文輸入法


這次來寫一下 如何使用android模擬器安裝中文輸入法,

發現自己的android模擬器裡居然沒有中文輸入法,

但要輸入中文做測試居然不行= =

後來查到是說,

先去下載注音輸入法的apk檔,

Android 注音輸入法 這裡可以下載到
http://code.google.com/p/android-zhuyin-ime/downloads/list

把apk檔放到 android sdk目錄\android-sdk\platform-tools資料夾內

用終端機執行

./adb install ZhuYinIME_2010030801.apk

windows執行

adb install ZhuYinIME_2010030801.apk

開啟android 模擬器 點選 menu -> 系統設定 -> 語言與輸入設定 ->勾選注音輸入法

然後就可以了。

但是 在edittext中發現點了後還是出現英文的小鍵盤!!!

找不到哪裡切換的話,

只要在edittext長按滑鼠左鍵,就會跳出輸入法切換囉~!

2013年4月15日 星期一

webservice抓取namespace資訊

使用android連接web service時,會透過soap的library,

其連連線到web service需要填入web service 的name space,

要如何抓取namespace為何呢?

只要在你的web service網址後加上 wsdl,就可以看見  

targetNamespace="http://tempuri.org/"

 的資訊囉~

例如:





在activity group 使用dialog alert報錯

今天使用activity group的時候,

要在裡面加dialog alert,居然報錯,

我是用tab group -> 透過 activity group -> 載顯示的activity

在顯示的activity下dialog的語法發現以下error:

04-15 15:04:25.027: E/AndroidRuntime(31825): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@40d861c0 is not valid; is your activity running?

查了網路後,

可以參考以下兩篇的作法

http://blog.csdn.net/biangren/article/details/7514722

http://blog.csdn.net/hillpool/article/details/7560600


實際作法, 加上 getParent() 即可


Builder b = new Builder(YourActivity.this.getParent());
b.setTitle("alertTitle");
b.setMessage("AlertMessage");
b.setPositiveButton("positive", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which)
{

}
});
b.show();

2013年4月14日 星期日

取消EditText Focus

在android native code裡,

若使用TextField(EditText)的話,

一進入預設會幫你直接focus在TextField(EditText),

有時候我們不需要一開始就focus在TextField(EditText),

可以在上層的Layout中加入兩行



LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center"
        android rientation="horizontal" >

這樣就可以取消自動focus~