'분류 전체보기'에 해당되는 글 256건

ProgressDialog

android 2020. 2. 10. 16:11
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("로딩중!");
progressDialog.show();

progressDialog.dismiss(); // 창닫기

'android' 카테고리의 다른 글

Fragment에서 Intent 호출시  (0) 2020.02.12
GestureDetector Swipe  (0) 2020.02.12
연락처 가져오기  (0) 2020.02.05
갤러리 이미지 가져오기  (0) 2020.02.05
SQLite 사용법  (0) 2020.02.05
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

연락처 가져오기

android 2020. 2. 5. 13:40

* MainActivity.java

public class MainActivity extends AppCompatActivity implements AutoPermissionsListener {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectContacts();
            }
        });

        AutoPermissions.Companion.loadAllPermissions(this, 101);
    }

    public void selectContacts() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 101) {
            if (resultCode == RESULT_OK) {
                Uri contactsUri = data.getData();
                String id = contactsUri.getLastPathSegment();

                getContacts(id);
            }
        }
    }

    public void getContacts(String id) {
        Cursor cursor = null;
        String name = "";

        try {
            cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                    null,
                    ContactsContract.Data.CONTACT_ID + "=?",
                    new String[] {id},
                    null);
            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                println("Name : " + name);

                String columns[] = cursor.getColumnNames();
                for (String column : columns) {
                    int index = cursor.getColumnIndex(column);
                    String columnOutput = "#" + index + " -> [" + column + "] " + cursor.getString(index);
                    println(columnOutput);
                }

                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void println(String data) {
        textView.append(data + "\n");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        AutoPermissions.Companion.parsePermissions(this, requestCode, permissions, this);
    }

    @Override
    public void onDenied(int requestCode, String[] permissions) {
        Toast.makeText(this, "permissions denied : " + permissions.length, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGranted(int requestCode, String[] permissions) {
        Toast.makeText(this, "permissions granted : " + permissions.length, Toast.LENGTH_LONG).show();
    }
}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="연락처 가져오기" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFE57F">

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

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
        
    </ScrollView>
    
</LinearLayout>

* AndroidManifest.xml

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

* Gradle

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
}

'android' 카테고리의 다른 글

GestureDetector Swipe  (0) 2020.02.12
ProgressDialog  (0) 2020.02.10
갤러리 이미지 가져오기  (0) 2020.02.05
SQLite 사용법  (0) 2020.02.05
gson 사용법  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

* MainActivity.java

public class MainActivity extends AppCompatActivity implements AutoPermissionsListener {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

        AutoPermissions.Companion.loadAllPermissions(this, 101);
    }

    public void openGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 101) {
            if (resultCode == RESULT_OK) {
                Uri fileUri = data.getData();

                ContentResolver resolver = getContentResolver();

                try {
                    InputStream inputStream = resolver.openInputStream(fileUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                    imageView.setImageBitmap(bitmap);

                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        AutoPermissions.Companion.parsePermissions(this, requestCode, permissions, this);
    }

    @Override
    public void onDenied(int requestCode, String[] permissions) {
        Toast.makeText(this, "permissions denied : " + permissions.length, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGranted(int requestCode, String[] permissions) {
        Toast.makeText(this, "permissions granted : " + permissions.length, Toast.LENGTH_LONG).show();
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지 선택" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@mipmap/ic_launcher" />

</LinearLayout>

* AndroidManifest.xml

<!-- 외장 SD 카드 권한 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

* Gradle

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.pedroSG94:AutoPermissions:1.0.3'
}

'android' 카테고리의 다른 글

ProgressDialog  (0) 2020.02.10
연락처 가져오기  (0) 2020.02.05
SQLite 사용법  (0) 2020.02.05
gson 사용법  (0) 2020.02.04
Volley 사용법  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

SQLite 사용법

android 2020. 2. 5. 11:35

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText editText;
    EditText editText2;
    TextView textView;

    SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        editText2 = findViewById(R.id.editText2);
        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String databaseName = editText.getText().toString();
                createDatabase(databaseName);
            }
        });

        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tableName = editText2.getText().toString();
                createTable(tableName);
            }
        });

        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertRecord();
            }
        });

        Button button4 = findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                excuteQuery();
            }
        });
    }

    public void createDatabase(String databaseName) {
        println("createDatabase 호출됨");

        try {
            database = openOrCreateDatabase(databaseName + ".db", MODE_PRIVATE, null);
            println("데이터베이스 생성됨 : " + databaseName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createTable(String tableName) {
        println("createTable 호출됨");

        try {
            if (database == null) {
                println("데이터베이스를 먼저 열어주세요.");
                return;
            }

            String sql = "create table if not exists " + tableName + "(_id integer PRIMARY KEY autoincrement, name text, age integer, mobile text)";
            database.execSQL(sql);
            println("테이블 생성됨 : " + tableName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertRecord() {
        println("insertRecord 호출됨");

        try {
            if (database == null) {
                println("데이터베이스를 먼저 열어주세요.");
                return;
            }

            String tableName = editText2.getText().toString();
            if (tableName == null) {
                println("테이블 이름을 입력하세요.");
                return;
            }

            String sql = "insert into " + tableName + "(name, age, mobile) values ('홍길동', '20', '010-1000-1000')";
            database.execSQL(sql);
            println("레코드 추가함");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void excuteQuery() {
        println("excuteQuery 호출됨");

        if (database == null) {
            println("테이터베이스를 먼저 열어주세요.");
        }

        String tableName = editText2.getText().toString();
        if (tableName == null) {
            println("테이블 이름을 입력하세요.");
        }

        try {
            String sql = "select _id, name, age, mobile from " + tableName;
            Cursor cursor = database.rawQuery(sql, null);

            int i = 1;
            while (cursor.moveToNext()) {


                int id = cursor.getInt(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                String mobile = cursor.getString(3);

                println("레코드 #" + i + " : " + id + ", " + name + ", " + age + ", " + mobile);
                i++;
            }

            cursor.close();
        } catch (Exception e ) {
            e.printStackTrace();
        }
    }

    public void println(String data) {
        textView.append(data + "\n");
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="데이터베이스 만들기" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="테이블 만들기" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="레코드 추가" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="레코드 조회" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </ScrollView>

</LinearLayout>

* SQLite 다운로드

https://sqlitebrowser.org/dl/

'android' 카테고리의 다른 글

연락처 가져오기  (0) 2020.02.05
갤러리 이미지 가져오기  (0) 2020.02.05
gson 사용법  (0) 2020.02.04
Volley 사용법  (0) 2020.02.04
HttpURLConnection 사용법  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

gson 사용법

android 2020. 2. 4. 23:32

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Student student = new Student(1, "김하나", 90, 90, 90);

        // object > json
        Gson gson = new Gson();
        String gsonObject = gson.toJson(student);
        println("gson Object : " + gsonObject);

        HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
        hashmap.put(1, "김하나");
        hashmap.put(2, "김두나");
        hashmap.put(3, "김세나");

        // hashmap > json
        Gson gson2 = new Gson();
        String gsonHashmap = gson2.toJson(hashmap);
        println("gson Hashmap : " + gsonHashmap);

        // json > Object
        Gson gson3 = new Gson();
        Student gsonJson = gson3.fromJson(gsonObject, Student.class);
        println("번호 : " + gsonJson.getNum() + ", 이름 : " + gsonJson .getName());
    }

    public void println(String data) {
        Log.d("MainActivity", data);
    }

}

* Gradle

dependencies {
    implementation 'com.google.code.gson:gson:2.8.5'
}

'android' 카테고리의 다른 글

갤러리 이미지 가져오기  (0) 2020.02.05
SQLite 사용법  (0) 2020.02.05
Volley 사용법  (0) 2020.02.04
HttpURLConnection 사용법  (0) 2020.02.04
Socket 통신(Thread 필수)  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

Volley 사용법

android 2020. 2. 4. 19:34

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;

    static RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String urlStr = editText.getText().toString();
                request(urlStr);
            }
        });

        requestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    public void request(String urlStr) {
        StringRequest request = new StringRequest(
                Request.Method.GET,
                urlStr,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        println("응답 :" + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        println("에러 : " + error.toString());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }
        };

        request.setShouldCache(false);
        requestQueue.add(request);
        println("요청 보냄");
    }

    public void println(String data) {
        textView.append(data + "\n");
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="http://www.google.com" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="요청" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/textView"
                android:textSize="20dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </ScrollView>

</LinearLayout>

* Gradle

dependencies {
    implementation 'com.android.volley:volley:1.1.0'
}

* AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<application android:usesCleartextTraffic="true" />

'android' 카테고리의 다른 글

SQLite 사용법  (0) 2020.02.05
gson 사용법  (0) 2020.02.04
HttpURLConnection 사용법  (0) 2020.02.04
Socket 통신(Thread 필수)  (0) 2020.02.04
AsyncTask 사용법  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,