프로그래밍

코린이 ㅅㅂ 뭐가 문젠지 모르겠어요

 

fragment_map.xml

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ui.MapFragment">
 
    <data>
        <variable
            name="homeViewModel"
            type="com.비밀.myworkdiary.viewmodel.HomeViewModel" />
    </data>
 
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/cl_base"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <LinearLayout
            android:id="@+id/llHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="end"
            android:layout_margin="10dp"
            app:layout_constraintTop_toTopOf="@id/cl_base"
            app:layout_constraintStart_toStartOf="@id/cl_base"
            app:layout_constraintEnd_toEndOf="@id/cl_base">
 
            <ImageButton
                android:id="@+id/ib_history"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_history_30"
                android:background="@android:color/transparent"
                android:padding="2dp"
                android:scaleType="center"
                android:transitionName="slide_right_enter"
                />
 
        </LinearLayout>
 
        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/GoogleMaps"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="10dp"
            app:layout_constraintTop_toBottomOf="@id/llHeader"
            app:layout_constraintBottom_toTopOf="@id/tvLocation"
 
            />
 
        <TextView
            android:id="@+id/tvLocation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            app:layout_constraintTop_toBottomOf="@id/GoogleMaps"
            app:layout_constraintBottom_toTopOf="@id/tv_send"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:text="@{homeViewModel.nowAddress}"
            tools:text="Curreont Location"
            android:textSize="17sp"
            android:textColor="@color/black"
            android:fontFamily="@font/gmarket_sans_ttf_medium"
            android:background="@drawable/ic_button_square_corner"
            android:layout_margin="10dp"/>
 
 
        <TextView
            android:id="@+id/tv_send"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/ic_button_square_corner"
            tools:text="테스트 버튼"
            android:textSize="50sp"
            android:textColor="@color/black"
            android:fontFamily="@font/gmarket_sans_ttf_medium"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_margin="10dp" />
 
    </androidx.constraintlayout.widget.ConstraintLayout>
 
 
 
</layout>
cs

 

 

MapFragment.kt

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
class MapFragment : Fragment(), OnMapReadyCallback {
    private lateinit var binding: FragmentMapBinding
 
    // fragment가 처음 생성될 때 뷰모델을 생성하고 다시 생성되면 처음 생성된 것과
    // 동일한 인스턴스를 받는다.
    private val viewmodel: HomeViewModel by viewModels()
 
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_map, container, false)
        return binding.root
    }
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
 
        // 뷰모델 설정 (오류)
        binding.homeViewModel = viewmodel
        // fragment view를 바인딩의 수명 주기 소유자로 지정
        binding.lifecycleOwner = viewLifecycleOwner
        
        // 권한 확인
        LocationResultLauncher.launch(
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.INTERNET)
        )
        
        viewmodel.fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())
 
        binding.tvSend.setOnClickListener{ onSend() }
        binding.ibHistory.setOnClickListener{ onHistory() }
    }
}
cs

 

MainActivity에 MapFragment가 포함되어 있고, MapFragment에서 HomeViewModel과 DataBinding을 해 놓은 상태인데

위 코드에서 MapFragment.kt에 onViewCreated에서 viewmodel을 사용하려고만 하면 오류가 나면서 꺼집니다.

(java.lang.RuntimeException: java.lang.reflect.InvocationTargetException)

정확히는 그냥 어디서든 viewmodel을 쓰려고만 하면 오류가 발생합니다.

 

 

혹시 HomeViewModel 코드나 MainActivity 코드도 필요하다면 댓글 달아주세요. 올리겠습니다.

 

 

build.gradle.kt

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.jetbrainsKotlinAndroid)
    id("kotlin-kapt")
    id("com.google.devtools.ksp") version "1.9.21-1.0.16"
}
 
android {
    namespace = "비밀"
    compileSdk = 34
 
    defaultConfig {
        applicationId = "비밀"
        minSdk = 29
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"
 
        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }
 
    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
 
    buildFeatures{
        viewBinding = true
        dataBinding = true
    }
}
 
dependencies {
    implementation(libs.androidx.room.runtime)
    annotationProcessor(libs.androidx.room.room.compiler)
 
    // To use Kotlin annotation processing tool (kapt)
    // To use Kotlin Symbol Processing (KSP)
    ksp(libs.androidx.room.room.compiler)
 
    // optional - Kotlin Extensions and Coroutines support for Room
    implementation(libs.androidx.room.ktx)
 
    // optional - RxJava2 support for Room
    implementation(libs.androidx.room.rxjava2)
 
    // optional - RxJava3 support for Room
    implementation(libs.androidx.room.rxjava3)
 
    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation(libs.androidx.room.guava)
 
    // optional - Test helpers
    testImplementation(libs.androidx.room.testing)
 
    // optional - Paging 3 Integration
    implementation(libs.androidx.room.paging)
 
    // NTP 서버 시간 가져오기 라이브러리
    val kronosLatestVersion = "0.0.1-alpha11"
    implementation(libs.kronos.android)
 
    // Excel API
    implementation("org.apache.poi:poi:5.2.5")
    implementation(libs.poi.ooxml)
 
    // logging framework
    implementation("log4j:log4j:1.2+")
    implementation(libs.android.logging.log4j)
 
    implementation(libs.androidx.core.ktx.v1130)
 
    // sqlite
    implementation(libs.androidx.sqlite.ktx)
 
    // 구글 map
    implementation(libs.play.services.maps)
    implementation(libs.android.maps.utils)
    implementation(libs.places)
    implementation(libs.play.services.location)
 
    // LiveData
    implementation(libs.androidx.lifecycle.livedata.ktx)
    // ViewModel
    implementation(libs.androidx.lifecycle.viewmodel.ktx)
 
    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.appcompat)
    implementation(libs.material)
    implementation(libs.androidx.activity)
    implementation(libs.androidx.constraintlayout)
    implementation(libs.androidx.fragment.ktx)
    implementation(libs.androidx.databinding.runtime)
 
 
    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.androidx.espresso.core)
}
cs

 

 

 

 

 

9개의 댓글

11 일 전

adb로 로그나 뽑아서 분석하셈

0
11 일 전
@iillillill

잘 몰라서 그러는데 adb로 로그 보는거랑 디버깅으로 직접 보는거랑 다를게 있음?

0
11 일 전

코드에 문제는 없는 것 같고, 메인쪽 코드를 봐야 알 것 같음

일단 뷰모델을 Fragment 외부에서 생성해서 넘겨줘도 똑같은지 확인해보는게 좋을듯?

0
11 일 전
@힝거루

지금 해결해서 해결 방법 공유하려고 댓글 달러 왔는데 ㅋㅋㅋㅋㅋㅋㅋ

아 진짜 이거 ㅈㄴ 어처구니가 없네 ㅋㅋ

private val viewmodel: HomeViewModel by viewModels() 에서 private 빼서

val viewmodel: HomeViewModel by viewModels() 하니까 됨;;

 

이게 대체 뭐지???

0
11 일 전
@집에가게해줘

빌드 문제일수도 있을 것 같은데, 클린 해보고 다시 private 붙여서 해봐도 똑같은지 봐바

0
11 일 전
@힝거루

클린하니까 잘 됨.. 어휴 이걸 몇시간이나 헤맨거여;;

0
5 일 전
@집에가게해줘

빌드할 때 캐시 때문에 문제 생기는 경우가 종종 있음

나도 예전에 API만들다가 캐시 때문에 반나절동안 개삽질했음ㅋㅋㅋㅋ

이거 때문에 일정은 다가오고 정신 팔려서 버스도 한 정거장 지나쳐서 내리고 개빡쳤던 기억이 나네

0
11 일 전

저 같은 경우 싱크 -> 클린 -> 빌드

이걸로 안되면 캐시 지우고 이 과정 거치고

이걸로 안되면 log / debug 따보네용.

0
7 일 전

데이터 바인딩 쓰지 마셔용

0
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
180611 [잡담] 키보드 사진 두 개 리밍 1 35 분 전 35
180610 [컴퓨터] 13년된 컴을 보내주려 합니다. 던파 원활히 돌아가는 견적 7 긍정축재 1 14 시간 전 310
180609 [잡담] 스피커 고민 개붕이 이어서.. 12 배프고다배파고 0 14 시간 전 184
180608 [잡담] 트랙패드 편하냐?? 4 fhana 0 14 시간 전 152
180607 [컴퓨터] 7800x3d로 롤 돌리는 사람 있음? 3 보거 0 15 시간 전 246
180606 [컴퓨터] 윈도우 부팅오류 도움!ㅠㅠ 3 qop 0 17 시간 전 81
180605 [컴퓨터] 윈10 인터넷 순간 끊김 문제 해결법 좀 5 해물잠봉 0 19 시간 전 127
180604 [컴퓨터] 요새 그래픽카드 어디꺼가 좋음? 9 trader2 0 20 시간 전 270
180603 [잡담] 님들 보통 마우스 얼마나 오래 씀 ?? 16 말릭스 0 20 시간 전 211
180602 [컴퓨터] 윈도우10 노트북 화면 밝기가 자꾸 변하는데 해결 방법 좀 알... 4 두번하세요 0 21 시간 전 71
180601 [프로그래밍] 공통코드테이블은 대체 왜 만드냐 9 잠적자 0 23 시간 전 298
180600 [잡담] PC방에선 무선이어폰 못쓰나? 2 급병신미 0 1 일 전 199
180599 [컴퓨터] 모니터 이거 괜찮나여? 6 햄보칼쑤가없엉! 0 1 일 전 188
180598 [프로그래밍] 토이프로젝트 주제 선정 2 개드립눈팅1세대 0 1 일 전 162
180597 [모바일] 운동할때 쓸 무선이어폰 구합니다 7 물타다대주주 0 1 일 전 133
180596 [컴퓨터] 다크플래시 df5000에 3rsys팬 껴도 되나요? 3 함박눈 0 1 일 전 76
180595 [잡담] 아니 유선 무선 음질 차이 이정도였던거임? 1 와신상담 1 1 일 전 142
180594 [컴퓨터] 윈도우 부팅 납치 해석 4 닉으로드립치고싶냐 0 1 일 전 208
180593 [컴퓨터] 노트북 키보드 수리 맡기고 왔더니 팬이 엄청 돈당 4 신요조 0 1 일 전 117
180592 [모바일] iptime wan 포트 연결안됨 해법 있을까요.. 2 비밀변호486 0 1 일 전 61