JSON이란, Javascript Object Notaion의 약자로써, 자바스크립트 객체 표기법을 뜻하며

쉽게 생각하면 그냥 데이터 표현 방법이다. JSON은 실무에서도 굉장히 많이 쓰이니 꼭 알아 놓도록하자.

JSON의 구조는 크게 2가지인데, JSONObject와 JSONArray이다. 순서대로 알아보도록하다.


1. JSONObject

구조 : {"name", "shin", "age": 24}

사용방법 :

JSONObject jObj = new JSONObject;

jObj.put("name": "shin");

jObj.put("age": "24");


String input = jObj.toString();

input값 :  {"name", "shin", "age": 24}


String data = jObj.get("name");

get값 : shin


2. JSONArray

구조 : [{"name":"shin"},{"name":"kang"}]

사용방법 : 

String data = "[{\"Product\" : \"Mouse\", \"Maker\":\"Samsung\", \"Price\":23000},"
               + "{\"Product\" : \"KeyBoard\", \"Maker\":\"LG\", \"Price\":12000},"
               + "{\"Product\":\"HDD\", \"Maker\":\"Western Digital\", \"Price\":156000}]";
try{
   String result = "";
   JSONArray jArray = new JSONArray(data);
   for (int i = 0; i < jArray.length(); i++){
      JSONObject jObj = jArray.getJSONObject(i);
      result += "product: " + jObj.getString("Product") + ", maker: " + jObj.getString("Maker") +
                  ", price: " + jObj.getInt("Price") + "\n";
   }
}catch (JSONException e){ }

결과값 :  result : product: Mouse, maker: Samsung, price: 23000
product: KeyBoard, maker: LG, price: 12000
product: HDD, maker: Western Digital, price: 156000
출처 : http://biig.tistory.com/52



JSONObject 안에 Array를 넣어서 사용할수도 있다.

"jObj":{
"name" : "me",
"entuty":[
{"name":"shin"},
{"name":"kang"},
{"name":"choi"}
]
}


'Programming > Android' 카테고리의 다른 글

manifest  (0) 2016.09.02
notification 고정시키기  (1) 2016.08.28
AsyncTask  (0) 2016.08.26
AccessibilityService  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
Android는 Java로 되어 있어 Java에서 제공하는 기능을 사용하여 Thread를 구현할 수 있습니다. 그러나, 안드로이드 화면의 각 요소(View)에 정보를 표시한다든지 하는 UI와 관련된 작업을 하는 경우에는 여러가지 제약 사항이 따릅니다.

Google에서는 AsyncTask라는 것을 제공하여 Android에서 UI 작업과 관련된 Thread의 구현을 손쉽게 할 수 있도록 지원 합니다
 
 

  Thread with AsyncTask

UI Thread를 구현하기 위해서는 해당 Thread가 Activity에서 구현이 되어야 하며, 주고 받는 인자들의 타입이 일치 하여야 합니다. 아래 설명에서는 서로 일치해야 하는 인자들의 경우에는 동일한 색으로 표시를 해서 구분 합니다.

* AsyncTask 호출 구현
private Activity activity = null;

activity = this;
(new theAsyncThread()).execute(para1para2para3);


*AsyncTask 구현
private class theAsyncThread extends AsyncTask<StringStringString> {
    //--- Thread를 시작하기 전에 호출되는 함수
    protected void onPreExecute() {
        if ((activity != null) && (activity.isFinishing() == false)) {
            Toast.makeText(activity, "Before thread", Toast.LENGTH_SHORT).show();
        }
        super.onPreExecute();
    }

    //--- Thread의 주요 작업을 처리 하는 함수
    //--- Thread를 실행하기 위해 excute(~)에서 전달한 값을 인자로 받습니다.
    protected String doInBackground(String... arg) {
        int argCnt = 0;
        
        argCnt = arg.length;
        if (argCnt != 3) {
            return "Error";
        }
        
        //--- onProgressUpdate(~) 실행하기 위해서는 아래 함수를 호출 합니다.
        publishProgress("Thread processing.");
        return "OK";
    }

    //--- doInBackground(~)에서 호출되어 주로 UI 관련 작업을 하는 함수
    protected void onProgressUpdate(String... progress) {
        if ((activity != null) && (activity.isFinishing() == false)) {
            Toast.makeText(activity, progress[0], Toast.LENGTH_SHORT).show();
        }
    }

    //--- Thread를 처리한 후에 호출되는 함수
    //--- doInBackground(~)의 리턴값을 인자로 받습니다.
    protected void onPostExecute(String result) {
        if ((activity != null) && (activity.isFinishing() == false)) {
            Toast.makeText(activity, "After thread", Toast.LENGTH_SHORT).show();
        }
        super.onPostExecute(result);
    }

    //--- AsyncTask.cancel(true) 호출시 실행되어 thread를 취소 합니다.
    protected void onCancelled() {
        super.onCancelled();
    }      
}    


출처 : http://cuteelfluv.cafe24.com/xe/index.php?mid=etc&page=4&document_srl=5803

'Programming > Android' 카테고리의 다른 글

notification 고정시키기  (1) 2016.08.28
JSONobject 과 JSONarray  (0) 2016.08.27
AccessibilityService  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
화면이 변경되었을때 해당 package가 아니면 /*실행*/부분을 실행하는 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
public class WindowDetecter extends AccessibilityService 
{
 
 @Override
 public void onAccessibilityEvent(AccessibilityEvent event) {
  if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
   Log.d(TAG, "Package is " + event.getPackageName());
   if!"패키지명".equals(event.getPackageName())){
      /*실행*/
   }
  }
 }
}
cs


AccessibilityService.class란, 접근성에 관련된 클래스이다.

TYPE_WINDOW_STATE_CHANGED

Added in API level 4
int TYPE_WINDOW_STATE_CHANGED

Represents the event of opening a PopupWindowMenuDialog, etc.

팝업윈도우나, 메뉴, 다이얼로그같이 현재 열려있는 이벤트에 대한 상수

Constant Value: 32 (0x00000020)


getEventType

Added in API level 4
int getEventType ()

Gets the event type.

이벤트 타입을 얻는다.

Returns
intThe event type.


출처 : https://developer.android.com/reference/android/view/accessibility/AccessibilityEvent.html

'Programming > Android' 카테고리의 다른 글

JSONobject 과 JSONarray  (0) 2016.08.27
AsyncTask  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
ProgressDialog 와 Toast  (0) 2016.08.25

인텐트


Intent의 첫번째 매개변수는 호출하는 액티비티를 나타내고, 두번째 매개변수에는 호출할 액티비티를 나타냅니다.

  그리고 Intent하는 두 액티비티는 모두 manifest에 등록되어 있어야한다!!!!

1
2
3
 Intent intent = new Intent(this, MainActivity.class);
 startActivity(intent);
 finish();
cs



인텐트(Intent)는 컴포넌트에 액션, 데이터 등을 전달하는 메시지 객체이다. 인텐트 객체의 구성 요소는 다음과 같다.

 

Action (액션): 수행할 액션 이름(ACTION_DIAL)

Data (데이터): 수행할 데이터의 URI(tel:)

Category (카테고리): 수행할 액션에 대한 추가적인 정보

Type (타입): 수행할 인텐트 데이터의 명시적인 타입(MIME 타입) (video/mpeg)

Component name (컴포넌트 이름): 대상 컴포넌트의 완전한 클래스 이름

Extras (추가 정보): 인텐트를 다루는 컴포넌트에 추가적으로 전달할 한 쌍의 키 /

 

컴포넌트 활성화 시점

컴포넌트

활성화 시점

Activity

인텐트에 의해 활성화

Service

인텐트에 의해 활성화

Broadcast Receiver

인텐트에 의해 활성화

Content provider

ContentResolver에 의해 활성화

 

컴포넌트 활성화

컴포넌트

활성화

Activity

Context.startActivity()

Activity.startActivityForResult()에 인텐트 객체를 전달해서 활성화

Service

Context.startService()에 인텐트 객체를 전달해서 활성화 
안드로이드는 인텐트 객체를 ServiceonStart() 메소드에 전달

Broadcast Receiver

Context.sendBroadcast()

Context.sendOrderedBroadcast()

Context.sendStickyBroadcast()에 인텐트 객체를 전달해서 활성화



인텐트 필터

인텐트 필터(Intent Filter)는 특정 인텐트를 받을지 말지를 정의하는 역할을 수행하며, 이를 통해 컴포넌트의 특징이 정해진다. 예를 들어, 인텐트 필터에 android.intent.action.MAIN을 선언하고 다음에 android.intent.category.HOME을 선언하면, 해당 컴포넌트는 홈 애플리케이션이 되어 디바이스가 시작될 때 자동으로 시작될 수 있는 애플리케이션이 된다. 인텐트 필터를 구성하는 요소는 인텐트에 작성할 수 있는 요소들과 동일하다.

- 앱 컴포넌트는 인텐트 필터를 가질 수 있고, 안드로이드는 인텐트 필터를 이용하여 어떤 앱 컴포넌트에 암시적 인텐트를 전달할지를 결정.


- 명시적 인텐트에는 클래스 이름이 설정되어 있어 무엇을 실행할지가 명확함.

-  - 묵시적 인텐트는 클래스 이름 대신 액션 이름이 설정됨.

         (액션 이름만으로는 어떤 앱 컴포넌트를 실행할지가 명확하지 않다.)

 


새로운 액티비티가 뜨면, HOME화면으로 이동하는 예제와 설명


1
2
3
4
5
6
7
8
9
10
 private void fobidden_activity() {
  Intent intent = new Intent();
  intent.setAction("android.intent.action.MAIN");
  intent.addCategory("android.intent.category.HOME");
  intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS 
   | Intent.FLAG_ACTIVITY_FORWARD_RESULT
      | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP
      | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
  startActivity(intent);
 }
cs

setAction

Added in API level 1
Intent setAction (String action)

Set the general action to be performed.

Parameters
actionString: An action name, such as ACTION_VIEW. Application-specific actions should be prefixed with the vendor's package name.
Returns
IntentReturns the same Intent object, for chaining multiple calls into a single statement.


ACTION_MAIN

Added in API level 1
String ACTION_MAIN

Activity Action: Start as a main entry point, does not expect to receive data.

Input: nothing

Output: nothing

Constant Value: "android.intent.action.MAIN"



addCategory

Added in API level 1
Intent addCategory (String category)

Add a new category to the intent. Categories provide additional detail about the action the intent performs. When resolving an intent, only activities that provide all of the requested categories will be used.

Parameters
categoryString: The desired category. This can be either one of the predefined Intent categories, or a custom category in your own namespace.
Returns
IntentReturns the same Intent object, for chaining multiple calls into a single statement.


addFlags

Added in API level 1
Intent addFlags (int flags)

Add additional flags to the intent (or with existing flags value).

Parameters
flagsint: The new flags to set.
Returns
IntentReturns the same Intent object, for chaining multiple calls into a single statement.

CATEGORY_HOME

Added in API level 1
String CATEGORY_HOME

This is the home activity, that is the first activity that is displayed when the device boots.

Constant Value: "android.intent.category.HOME"



intFLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

If set, the new activity is not kept in the list of recently launched activities.

intFLAG_ACTIVITY_FORWARD_RESULT

If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.

intFLAG_ACTIVITY_NEW_TASK

If set, this activity will become the start of a new task on this history stack.

intFLAG_ACTIVITY_PREVIOUS_IS_TOP

If set and this intent is being used to launch a new activity from an existing one, the current activity will not be counted as the top activity for deciding whether the new intent should be delivered to the top instead of starting a new on

intFLAG_ACTIVITY_RESET_TASK_IF_NEEDED

If set, and this activity is either being started in a new task or bringing to the top an existing task, then it will be launched as the front door of the task.


출처 : https://developer.android.com/reference/android/content

'Programming > Android' 카테고리의 다른 글

AsyncTask  (0) 2016.08.26
AccessibilityService  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
ProgressDialog 와 Toast  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25

kakao 패키지명 - com.kakao.talk

카메라 패키지명 - com.android.camera

갤러리 패키지명 -  com.android.gallery

'Programming > Android' 카테고리의 다른 글

AccessibilityService  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
ProgressDialog 와 Toast  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25
SharedPreferences  (0) 2016.08.24

1. ProgressDialog

setMessage로 세팅하고,

show로 보여주고 dismiss로 안보여주고...


1
2
3
4
5
6
7
8
9
10
static ProgressDialog dialog;
 
dialog = new ProgressDialog(this);
        dialog.setMessage(string);
        dialog.show();
    }
)
 
dialog.dismiss();
   
cs


2. Toast

Toast는 첫번째 매개변수에 Context를 넣어야하는데 GetApplicationContext()를 사용하여 해당 Context를 받아 오도록하자

Toast.LENGTH_SHORT와 LONG가 있는데 취향에 맞춰 골라 쓰세요.


1
2
 Toast.makeText(getApplicationContext(), "Test",Toast.LENGTH_SHORT).show();
 
cs


'Programming > Android' 카테고리의 다른 글

Intent와 Intent Filter  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25
SharedPreferences  (0) 2016.08.24
Context  (0) 2016.08.24

 HttpURLConnection이 Httppost와 다른 이유는 전송 데이터를 URL에 넣어 전송하느냐 body에 넣어 전송하느냐이다.

후자가 데이터를 감추기에 더 좋을꺼 같긴하다..


1
2
3
4
5
6
7
8
9
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

try {
 
                URL obj = new URL(url+"?"+paramString.toString());
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
 
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                conn.setDefaultUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
 
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
                pw.write(paramString);
                pw.flush();
                pw.close();
                int retCode = conn.getResponseCode();
 
                if (retCode == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is)."UTF-8");
                    String line;
                    StringBuffer response = new StringBuffer();
                    while((line = br.readLine()) != null){
                        response.append(line);
                    }
                    br.close();
                    Log.d(TAG,"responvalue: "+response.toString());
                    return response.toString();
                }else{
                    Log.d(TAG,"error code is " + retCode);
                }
 
            } catch (Exception e) {
                e.printStackTrace();
            }
cs

22번 라인에 "UTF-8"을 추가하면 한글깨짐현상을 막을수 있다.



'Programming > Android' 카테고리의 다른 글

어플 패키지명  (0) 2016.08.25
ProgressDialog 와 Toast  (0) 2016.08.25
SharedPreferences  (0) 2016.08.24
Context  (0) 2016.08.24
Activity 생명주기  (0) 2016.08.24

0. 사용용도

 - 초기 설정값이나 자동로그인 여부, 진동 유무등 간단한 값을 저장하고 싶을때 사용

 - 어플리케이션 파일형태로 데이터를 저장

 - 어플리케이션이 삭제 전까지 보존

 - 간단하게 Key, Value 형태의 파일로 저장되므로 앱이 종료되어도 기억

 - 불러오려는 Key값이 없는 경우 공백문자열을 return.


1. 데이터 얻기

 - getPreferences(int mode)

하나의 액티비티에서만 사용하는 SharedPreferences를 생성

생성되는 SharedPreferences 파일은 해당 액티비티이름으로 생성

하나의 액티비티에서만 사용할 수 있지만 getSharedPreferences()를 사용하면 다른 액티비티에서도 사용가능


 - getSharedPreferences(String name, int mode)

특정 이름을 가진 SharedPreferences를 생성

주로 애플리케이션 전체에서 사용


2. 데이터 저장

먼저 데이터를 기록하기 위해 SharedPreferences.Editor 인스턴스를 얻어야 함

1
2
3
4
5
6
7
8
9
SharedPreferences test = getSharedPreferences("test", MODE_PRIVATE);
 
SharedPreferences.Editor editor = test.edit();
 
editor.putString("ID", Strid);
 
editor.putString("Password", Strpw);
 
editor.commit(); //완료한다.
cs


저장 가능한 데이터 타입

Boolean / String / Int / Float / Long



※ MODE  설정파일을 불러올때의 모드


- MODE_PRIVATE : 자기 app 내에서 사용할때, 기본값


- MODE_WORLD_READABLE : 다른 app에서 읽기 가능


- MODE_WORLD_WRITEABLE : 다른 app에서 쓰기 가능



3. 데이터 불러오기

데이터를 불러오기 위해서 getInt()나 getString() 메서드를 사용

getInt(KEY, VALUE)

첫번째 인자는 데이터의 키, 두번째 인자는 해당값이 없을경우 반환할 값을 넣어준다.

1
2
3
SharedPreferences test = getSharedPreferences("test", MODE_PRIVATE);
 
int firstData = test.getInt("ID", 0);
cs


4. 데이터 삭제

1) 특정 데이터 삭제

1
2
3
4
5
6
7
SharedPreferences test = getSharedPreferences("test", MODE_PRIVATE);
 
SharedPreferences.Editor editor = test.edit();
 
editor.remove("test");
 
editor.commit();
cs

2) 모든 데이터 삭제

1
2
3
4
5
6
7
SharedPreferences test = getSharedPreferences("test", MODE_PRIVATE);
 
SharedPreferences.Editor editor = test.edit();
 
editor.clear();
 
editor.commit();
cs

5. Context와 함께 사용


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 선언
public class PreferencesUtil{
 
    public static void setPreferences(Context context, String key, String value) {
        SharedPreferences pref = context.getSharedPreferences("pref", context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key, value);
        editor.commit();
    }
 
    public static String getPreferences(Context context, String key) {
        SharedPreferences pref = context.getSharedPreferences("pref", context.MODE_PRIVATE);
        pref = context.getSharedPreferences("pref", context.MODE_PRIVATE);
        return pref.getString(key, "");
    }
}
 
 
//저장
PreferencesUtil.setPreferences(context, "ID", Strid);
PreferencesUtil.setPreferences(context, "PW", StrPw);
 
//불러오기
String ID= PreferencesUtil.getPreferences(context, "ID");
String Pw= PreferencesUtil.getPreferences(context, "Pw");
 
Log.d("PreferencesUtil""ID: " + ID);
Log.d("PreferencesUtil""Pw: " + Pw);
cs


'Programming > Android' 카테고리의 다른 글

ProgressDialog 와 Toast  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25
Context  (0) 2016.08.24
Activity 생명주기  (0) 2016.08.24
Fragment  (0) 2016.08.24

+ Recent posts