2016.04.22 16:03

Sparse arrays can be used to replace hash maps when the key is a primitive type. There are some variants for different key/value type even though not all of them are publicly available.

Benefits are:

  • Allocation-free
  • No boxing

Drawbacks:

  • Generally slower, not indicated for large collections
  • They won't work in non-android project

HashMap can be replaced by the followings:

SparseArray          <Integer, Object>
SparseBooleanArray   <Integer, Boolean>
SparseIntArray       <Integer, Integer>
SparseLongArray      <Integer, Long>
LongSparseArray      <Long, Object>
LongSparseLongArray  <Long, Long>   //this is not a public class                                 
                                    //but can be copied from  Android source code 

In terms of memory here is an example of SparseIntArray vs HashMap for 1000 elements

SparseIntArray:

class SparseIntArray {
    int[] keys;
    int[] values;
    int size;
}

Class = 12 + 3 * 4 = 24 bytes
Array = 20 + 1000 * 4 = 4024 bytes
Total = 8,072 bytes

HashMap:

class HashMap<K, V> {
    Entry<K, V>[] table;
    Entry<K, V> forNull;
    int size;
    int modCount;
    int threshold;
    Set<K> keys
    Set<Entry<K, V>> entries;
    Collection<V> values;
}

Class = 12 + 8 * 4 = 48 bytes
Entry = 32 + 16 + 16 = 64 bytes
Array = 20 + 1000 * 64 = 64024 bytes
Total = 64,136 bytes

Source: Android Memories by Romain Guy from slide 90.

The numbers above are the amount of memory (in bytes) allocated on heap by JVM. They may vary depending on the specific JVM used.

java.lang.instrument package contains some helpful methods for advanced operation like checking the size of an object with getObjectSize(Object objectToSize).

Extra info are available from official Oracle documentation

Class = 12 byte + (n instance variables) * 4 byte
Array = 20 byte + (n elements) * (element size)
Entry = 32 byte + (1st element size) + (2ns elements size)




After some googling I try to add some information to the already posted anwers:

Isaac Taylor made a performance comparision for SparseArrays and Hashmaps. He states that

the Hashmap and the SparseArray are very similar for data structure sizes under 1,000

and

when the size has been increased to the 10,000 mark [...] the Hashmap has greater performance with adding objects, while the SparseArray has greater performance when retrieving objects. [...] At a size of 100,000 [...] the Hashmap loses performance very quickly

An comparision on Edgblog shows that a SparseArray need much less memory than a HashMap because of the smaller key (int vs Integer) and the fact that

a HashMap.Entry instance must keep track of the references for the key, the value and the next entry. Plus it also needs to store the hash of the entry as an int.

As a conclusion I would say that the difference could matter if you are going to store a lot of data in your Map. Otherwise, just ignore the warning.

저작자 표시
신고
Posted by hoonihoon85 hoonihoon
2015.10.23 10:06


서버에서 응답받은 json 을 


오브젝트 리스트형태로 변경하는법!

ArrayList<MyObject> list = new Gson().fromJson(jsonString, new TypeToken<List<MyObject>>() { }.getType());




저작자 표시
신고
Posted by hoonihoon85 hoonihoon
2014.12.03 16:37

아래와 같은 솔루션을 이용하자.


setonItemselectedListener 전에  setselection(position, false); 를 넣으면 된다.



The use of Runnables is completely incorrect.

Use setSelection(position, false); in the initial selection before setOnItemSelectedListener(listener)

This way you set your selection with no animation which causes the on item selected listener to be called. But the listener is null so nothing is run. Then your listener is assigned.

So follow this exact sequence:

Spinner s = (Spinner)Util.findViewById(view, R.id.sound, R.id.spinner);
s.setAdapter(adapter);
s.setSelection(position, false);
s.setOnItemSelectedListener(listener);


저작자 표시
신고
Posted by hoonihoon85 hoonihoon
2014.12.03 14:32

volley post get 방법


출저  : http://stackoverflow.com/questions/16626032/volley-post-get-parameters


For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8"));to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.



출저  : http://stackoverflow.com/questions/16626032/volley-post-get-parameters

저작자 표시
신고
Posted by hoonihoon85 hoonihoon
2014.11.27 15:10




주제:   안드로이드에서 로그인 관련 기능 중에 핸드폰 고유값을 서버에 전송할 수 있을지 알아 보았다.


분석:    아래와 같은 코드로 핸드폰 고유의 값 3가지를 가져올수 있다.


TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);


// IMEI 

Log.d("kth", "telephonyManager.getDeviceId(); " + telephonyManager.getDeviceId());

// 핸드폰 번호

Log.d("kth", "telephonyManager.getLine1Number(); " + telephonyManager.getLine1Number());


// UDID 

String deviceId= Secure.getString(G.mainactivity.getContentResolver(), Secure.ANDROID_ID); 

Log.d("kth", "deviceId: " + deviceId);


결론:  위에 사용 되는 코드는 모두 서버로 전송하면 안된다. 


[테스트 내역]


1. IMEI 수집시에 압수수색  http://www.asiae.co.kr/news/view.htm?idxno=2010083114402683628

    md5 암호화해도 불법.


2. 폰 번호 수집  불법  

  http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_QnA_etc&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=3188


3. 다비이스 고유값 (UDID)

   애플에서 UDID 값 수집시 마켓 등록 거절.



다른방법 :  GCM에서 생성해준 디바이스key 값을 이용하는 방법으로 선택.

                단, 어플을 지우고 새로 받으면 디바이스 key 값을 새로 받기 때문에 주의해야 한다.

저작자 표시
신고
Posted by hoonihoon85 hoonihoon
2013.12.16 17:26

문제점: 

회사에서 Tomcat 컨테이너를 이용해 서버를 하나 만들었다. 내부 IP만 연결되어 폰에서는 불가능하고,

에뮬레이터에서 접속을 해야만 했다.

그런데 웹브라우저에  http://localhost:8080 입력하면 페이지를 찾을 수 없다고 나온다.


해결방법: 

http://192.0.0.88:8080 접속하면 서버에 연결 된다.

신고
Posted by hoonihoon85 hoonihoon
2013.10.08 17:35

This subject is discussed in the Android Training:

http://developer.android.com/training/multiscreen/screensizes.html#TaskUseSWQuali

If you read the entire topic, they explain how to set a boolean value in a specific value file (as res/values-sw600dp/):

<resources>
    <bool name="isTablet">true</bool>
</resources>

Because the sw600dp qualifier is only valid for platforms above android 3.2. If you want to make sure this technique works on all platforms (before 3.2), create the same file in res/values-xlarge folder:

<resources>
    <bool name="isTablet">true</bool>
</resources>

Then, in the "standard" value file (as res/values/), you set the boolean to false:

<resources>
    <bool name="isTablet">false</bool>
</resources>

Then in you activity, you can get this value and check if you are running in a tablet size device:

boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
    // do something
} else {
    // do something else
}


신고
Posted by hoonihoon85 hoonihoon
2013.08.22 17:40

출저: http://www.dibbus.com/2011/02/gradient-buttons-for-android/

Just some other stuff to share with you, no 3D, no Umbraco bust some new gradient buttons for Android.

Capture
Yes I’m into android now, and I just love it. Really fun programming for Android. Because I really like a nice layout here are, for a start some nice button layouts. Use them for a better layout and replace those gray android buttons.
I’ve used two color gradients. The sdk permits a third color, I’ll use a third color maybe in a next post. For the colors I just took 2 colors,not too much differ from each other. Take your own colors if you like.

Blue button

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#449def" />
            <stroke
                android:width="1dp"
                android:color="#2f6699" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#449def"
                android:endColor="#2f6699"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#2f6699" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Red button

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#ef4444" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#ef4444"
                android:endColor="#992f2f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Purple button

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#a276eb" />
            <stroke
                android:width="1dp"
                android:color="#6a3ab2" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#a276eb"
                android:endColor="#6a3ab2"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#6a3ab2" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Green button

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#70c656" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#70c656"
                android:endColor="#53933f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Yellowbutton

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35