반응형

lottie

lottie 애니메이션은 카테고리 옆 이미지, 로딩 다이얼로그 등  화면을 보다 동적으로 보여주기에 목적에 따라 다양하게 활용 될 수 있습니다.

build.gradle

// lottie
    implementation 'com.airbnb.android:lottie:5.0.2'

raw 파일 생성

res 우클릭 - New - Android Resource Directory

Android Resource Deirectory
raw파일 생성


lottie 홈페이지

https://lottiefiles.com/

 

LottieFiles: Download Free lightweight animations for website & apps.

Effortlessly bring the smallest, free, ready-to-use motion graphics for the web, app, social, and designs. Create, edit, test, collaborate, and ship Lottie animations in no time!

lottiefiles.com

원하는 이미지의 JSON파일을 선택해 줍니다.

 

JSON 파일 다운로드

 

다운로드한 파일을 raw에 추가

car.json


xml

<com.airbnb.lottie.LottieAnimationView
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_gravity="center"
    app:lottie_rawRes="@raw/car"
    app:lottie_autoPlay="true"
    app:lottie_loop="true" />

app:lottie_rawRes="@raw/car" 원하는 lottie json파일을 연결 시켜 줍니다.


결과

lottie 애니메이션

반응형
반응형

Retrofit2 라이브러리를 사용하여 서버와 데이터를 주고 받는 작업을 진행하겠습니다.

Retrofit2

Retrofit2 은 서버와의 RestAPI 통신을 가능하게 도와주는 라이브러리 입니다. 

 retrofit 외에 통신을 가능하게 하는 라이브러리가 있지만, 속도 뿐만 아니라 많은 장점을 보유하고 있기에 Retrofit을 많이 선호 한다고 합니다.


build.gradle

// retrofit2
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// Gson 변환기
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

retrofit, gson 라이브러리를 추가해 줍니다.

 

ApiClient.java 클래스 생성

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {

    private static final String BASE_URL = "http://IPv4주소:서버포트/";
    // "http://192.168.xxx.xxx:80/"

    public static RetrofitAPI getApiService(){
        return getInstance().create(RetrofitAPI.class);
    }

    private static Retrofit getInstance(){
        Gson gson = new GsonBuilder().setLenient().create();
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
}

 


다음은 BASE_URL 부분에 입력할 IPv4 주소와 서버포트를 확인하는 방법 입니다.

IPv4 주소 확인

cmd - ipconfig 입력

 

IPv4 주소

 

서버포트 확인

sts4 실행 -> src/main/resources -> application.properties

 

서버 포트


RetrofitAPI.java 인터페이스 생성

import java.util.List;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;

public interface RetrofitAPI {

    @GET("api/sample")
    Call<List<Data>> getPost();

    @POST("api/communitytest")
    Call<String> createPost(@Body Data data);

    @PUT("api/communitytest/{textid}")
    Call<String> putPost(@Path("textid") String id, @Body Data data);

    @DELETE("api/communitytest/{textid}")
    Call<String> deletePost(@Path("textid") String id);
}

@GET/POST/PUT/DELETE ("서버 controller에서 처리한 url 주소")

 

서버 controller

 

 

GET 요청 예시

브라우저에서 http://192.168.xxx.xxx:80/api/sample 을 검색하게 되면 미리 입력한 데이터를 확인 할 수 있습니다.

 

GET요청


Data.java 클래스 생성

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Data {

    public Data(String id, String title, String name, String major, String time, String boarding, String destination, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
        this.name = name;
        this.major = major;
        this.time = time;
        this.boarding = boarding;
        this.destination = destination;
    }

    @SerializedName("id")
    @Expose
    private String id;

    @SerializedName("title")
    @Expose
    private String title;

    @SerializedName("content")
    @Expose
    private String content;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("major")
    @Expose
    private String major;

    @SerializedName("time")
    @Expose
    private String time;

    @SerializedName("boarding")
    @Expose
    private String boarding;

    @SerializedName("destination")
    @Expose
    private String destination;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getBoarding() {
        return boarding;
    }

    public void setBoarding(String boarding) {
        this.boarding = boarding;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    @Override
    public String toString() {
        return "Data{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", name='" + name + '\'' +
                ", major='" + major + '\'' +
                ", time='" + time + '\'' +
                ", boarding='" + boarding + '\'' +
                ", destination='" + destination + '\'' +
                '}';
    }
}

생성자, Getter, Setter, toString(Log 확인용) 를 추가 해줍니다.

  • 생성자 추가 후 빈공간 우클릭 - Generate - Getter and Setter
  • 해당 생성자는 서버의 VO와 일치하게 작성.

서버 VO 파일


Activity

List<Data> dataList;

...

// Get
        Call<List<Data>> call = ApiClient.getApiService().getPost();
        call.enqueue(new Callback<List<Data>>() {
            @Override
            public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {
            	// 서버와의 통신이 성공했을 때 처리하는 부분
                dataList = response.body(); // 서버에서 return값으로 넘겨주는 값
                Log.i("sample", response.body()+""); // 로그 확인 시 입력된 값을 받아오는것을 확인

            }

            @Override
            public void onFailure(Call<List<Data>> call, Throwable t) {
            	// 서버와의 통신이 실패했을 때 처리하는 부분 
                Log.i("sample", "GET 실패"+t.getMessage());

            }
        });

주의사항

  • 테스트하는 서버와 모바일 핸드폰의 와이파이를 동일하게 설정 해주어야 통신이 가능합니다.
  • localhost 대신 IPv4 주소를 입력해 주어야 합니다.

 

새로고침

https://a070415.tistory.com/entry/Android-%EC%83%88%EB%A1%9C%EA%B3%A0%EC%B9%A8-%EA%B5%AC%ED%98%84-swipe-refresh

 

[Android] 새로고침 구현 - swipe refresh

swipe refresh 데이터를 받아오는 작업을 하거나, 새로고침이 필요한 경우 해당 라이브러리를 사용하여 간단한게 구현할 수 있습니다. build.gradle // swipe refresh implementation "androidx.swiperefreshlayout:swiperef

junn97.com

 

반응형
반응형

build.gradle

// slide animation
    implementation 'com.ncorti:slidetoact:0.3.0'

xml

<com.ncorti.slidetoact.SlideToActView
                    android:id="@+id/slide"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:outer_color="#3F51B5"
                    android:elevation="10dp"
                    app:text="슬라이드 버튼" />

Activity

 SlideToActView slide;
 
 ...

slide = findViewById(R.id.slide);

slide.setOnSlideCompleteListener(new SlideToActView.OnSlideCompleteListener() {
            @Override
            public void onSlideComplete(@NonNull SlideToActView slideToActView) {
                
                // 이벤트 발생 시키는 부분

                slide_driver.resetSlider();
            }
        });

결과

slidetoact 결과

반응형
반응형

크롤링(crawling)

 - 크롤링은 웹페이지의 내용을 그대로 가져와 데이터를 추출하는 행위 입니다.

 

서울날씨

위 사진은 현재 서울기준 네이버 날씨이며, 포커싱 된 부분의 글자를 추출하여 기기 화면으로 가져오는 코드를 Jsoup 라이브러리를 통하여 작성해보겠습니다.


build.gradle

// jsoup
    implementation 'org.jsoup:jsoup:1.13.1'

 

xml

<TextView
        android:id="@+id/tv_temper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="온도"
        android:gravity="center"
        android:textSize="15sp"/>

MainActivity

// 날씨 크롤링
    TextView tv_temper;
    String tem;
    private String URL = "https://m.search.naver.com/search.naver?sm=mtp_sly.hst&where=m&query=%EC%84%9C%EC%9A%B8+%EB%82%A0%EC%94%A8&acr=1";
    
    ...
    
     tv_temper = findViewById(R.id.tv_temper);
        final Bundle bundle = new Bundle();

        new Thread() {
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.connect(URL).get();
                    Elements temper = doc.select(".temperature_text");
                    tem = temper.get(0).text().substring(5);
                    bundle.putString("temperature", tem);

                    Message msg = handler.obtainMessage();
                    msg.setData(bundle);
                    handler.sendMessage(msg);


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        
        ...
        
         // 날씨 handler
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();
            tv_temper.setText("" + bundle.getString("temperature") + "도");
        }
    };
반응형
반응형

build.gradle

// cardview
    implementation 'androidx.cardview:cardview:1.0.0'

XML

    <androidx.cardview.widget.CardView
        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="200dp"
        app:cardCornerRadius="26dp"
        android:layout_margin="20dp"
        android:backgroundTint="#FBEB58"
        app:cardElevation="8dp">
        
        // 내용
        
    </androidx.cardview.widget.CardView>

결과

Cardview

내용 추가 시 Cardview 내부에 Layout 을 추가한 후에 사용 하시면 됩니다.

반응형
반응형

Android JNI 관련 설정 후 빌드과정에서 발생한 에러

 

Android.mk 파일에서 아래 코드 추가 

LOCAL_PATH := $(call my-dir)
반응형

+ Recent posts