Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

项目升级及修正 #31

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,9 @@
学习更多的Android技术知识,请关注我的微信公众号:

<img src="https://raw.githubusercontent.com/guolindev/booksource/master/qrcode.jpg" width="250" />

# 主要修改
1.升级各种组件的版本,修正编译错误、编译警告
2.修正一些过时的写法,如ViewModel的初始化、Fragment的onActivityCreated
3.去掉过时的kotlin-android-extensions插件,直接使用DataBinding获取控件
4.替换android.preference.PreferenceManager为androidx.preference.PreferenceManager
43 changes: 20 additions & 23 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
compileSdkVersion 28
compileSdk 33
defaultConfig {
applicationId "com.coolweather.coolweatherjetpack"
minSdkVersion 15
targetSdkVersion 28
minSdk 15
//noinspection EditedTargetSdkVersion
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
Expand All @@ -25,25 +22,25 @@ android {
dataBinding {
enabled true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
namespace "com.coolweather.coolweatherjetpack"
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-alpha03"
implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'org.litepal.android:kotlin:3.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'androidx.appcompat:appcompat:1.6.1'//已包括Lifecycle
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation 'org.litepal.guolindev:core:3.2.3' //这个需要jcenter
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
def lifecycle_version = "2.0.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation 'com.github.bumptech.glide:glide:4.16.0'
implementation 'androidx.preference:preference-ktx:1.2.0'
}
17 changes: 10 additions & 7 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.coolweather.coolweatherjetpack">
xmlns:tools="http://schemas.android.com/tools"
package="com.coolweather.coolweatherjetpack">

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

<application
android:name=".CoolWeatherApplication"
android:allowBackup="false"
android:icon="@mipmap/logo"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config"
tools:ignore="GoogleAppIndexingWarning,UnusedAttribute">
<activity android:name=".ui.MainActivity">
<activity
android:name=".ui.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity android:name=".ui.weather.WeatherActivity"/>
<activity android:name=".ui.weather.WeatherActivity" />
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@ class PlaceDao {
fun getCountyList(cityId: Int): MutableList<County> = LitePal.where("cityId = ?", cityId.toString()).find(County::class.java)

fun saveProvinceList(provinceList: List<Province>?) {
if (provinceList != null && provinceList.isNotEmpty()) {
if (!provinceList.isNullOrEmpty()) {
LitePal.saveAll(provinceList)
}
}

fun saveCityList(cityList: List<City>?) {
if (cityList != null && cityList.isNotEmpty()) {
if (!cityList.isNullOrEmpty()) {
LitePal.saveAll(cityList)
}
}

fun saveCountyList(countyList: List<County>?) {
if (countyList != null && countyList.isNotEmpty()) {
if (!countyList.isNullOrEmpty()) {
LitePal.saveAll(countyList)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.coolweather.coolweatherjetpack.data.db

import android.content.SharedPreferences
import android.preference.PreferenceManager
import androidx.preference.PreferenceManager
import com.coolweather.coolweatherjetpack.CoolWeatherApplication
import com.coolweather.coolweatherjetpack.data.model.weather.Weather
import com.google.gson.Gson
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
package com.coolweather.coolweatherjetpack.ui

import androidx.lifecycle.ViewModelProviders
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.coolweather.coolweatherjetpack.R
import com.coolweather.coolweatherjetpack.util.InjectorUtil
import com.coolweather.coolweatherjetpack.ui.weather.WeatherActivity
import android.content.Intent
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import com.coolweather.coolweatherjetpack.ui.area.ChooseAreaFragment

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewModel = ViewModelProviders.of(this, InjectorUtil.getMainModelFactory()).get(MainViewModel::class.java)
val viewModel = ViewModelProvider(viewModelStore, InjectorUtil.getMainModelFactory()).get(MainViewModel::class.java)
if (viewModel.isWeatherCached()) {
val intent = Intent(this, WeatherActivity::class.java)
startActivity(intent)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import com.coolweather.coolweatherjetpack.data.WeatherRepository
class MainModelFactory(private val repository: WeatherRepository) : ViewModelProvider.NewInstanceFactory() {

@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MainViewModel(repository) as T
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.coolweather.coolweatherjetpack.ui.area

import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
Expand All @@ -9,63 +10,70 @@ import android.view.ViewGroup
import android.widget.*
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import com.coolweather.coolweatherjetpack.R
import com.coolweather.coolweatherjetpack.databinding.ChooseAreaBindingImpl
import com.coolweather.coolweatherjetpack.databinding.ChooseAreaBinding
import com.coolweather.coolweatherjetpack.ui.MainActivity
import com.coolweather.coolweatherjetpack.ui.weather.WeatherActivity
import com.coolweather.coolweatherjetpack.util.InjectorUtil
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.choose_area.*

class ChooseAreaFragment : Fragment() {

private val viewModel by lazy { ViewModelProviders.of(this, InjectorUtil.getChooseAreaModelFactory()).get(ChooseAreaViewModel::class.java) }
private val viewModel by lazy { ViewModelProvider(this, InjectorUtil.getChooseAreaModelFactory()).get(ChooseAreaViewModel::class.java) }
private var progressDialog: ProgressDialog? = null
private var binding: ChooseAreaBinding? = null
private lateinit var adapter: ArrayAdapter<String>

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.choose_area, container, false)
val binding = DataBindingUtil.bind<ChooseAreaBindingImpl>(view)
binding = DataBindingUtil.bind(view)
binding?.viewModel = viewModel
adapter = ChooseAreaAdapter(requireContext(), R.layout.simple_item, viewModel.dataList)
binding?.listView?.adapter = adapter
return view
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
adapter = ChooseAreaAdapter(context!!, R.layout.simple_item, viewModel.dataList)
listView.adapter = adapter
observe()
override fun onAttach(context: Context) {
super.onAttach(context)

requireActivity().lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
observe()

owner.lifecycle.removeObserver(this)
}
})
}

private fun observe() {
viewModel.currentLevel.observe(this, Observer { level ->
viewModel.currentLevel.observe(this) { level ->
when (level) {
LEVEL_PROVINCE -> {
titleText.text = "中国"
backButton.visibility = View.GONE
binding?.titleText?.text = "中国"
binding?.backButton?.visibility = View.GONE
}
LEVEL_CITY -> {
titleText.text = viewModel.selectedProvince?.provinceName
backButton.visibility = View.VISIBLE
binding?.titleText?.text = viewModel.selectedProvince?.provinceName
binding?.backButton?.visibility = View.VISIBLE
}
LEVEL_COUNTY -> {
titleText.text = viewModel.selectedCity?.cityName
backButton.visibility = View.VISIBLE
binding?.titleText?.text = viewModel.selectedCity?.cityName
binding?.backButton?.visibility = View.VISIBLE
}
}
})
viewModel.dataChanged.observe(this, Observer {
}
viewModel.dataChanged.observe(this) {
adapter.notifyDataSetChanged()
listView.setSelection(0)
binding?.listView?.setSelection(0)
closeProgressDialog()
})
viewModel.isLoading.observe(this, Observer { isLoading ->
}
viewModel.isLoading.observe(this) { isLoading ->
if (isLoading) showProgressDialog()
else closeProgressDialog()
})
viewModel.areaSelected.observe(this, Observer { selected ->
}
viewModel.areaSelected.observe(this) { selected ->
if (selected && viewModel.selectedCounty != null) {
if (activity is MainActivity) {
val intent = Intent(activity, WeatherActivity::class.java)
Expand All @@ -74,13 +82,13 @@ class ChooseAreaFragment : Fragment() {
activity?.finish()
} else if (activity is WeatherActivity) {
val weatherActivity = activity as WeatherActivity
weatherActivity.drawerLayout.closeDrawers()
weatherActivity.binding.drawerLayout.closeDrawers()
weatherActivity.viewModel.weatherId = viewModel.selectedCounty!!.weatherId
weatherActivity.viewModel.refreshWeather()
}
viewModel.areaSelected.value = false
}
})
}
if (viewModel.dataList.isEmpty()) {
viewModel.getProvinces()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import com.coolweather.coolweatherjetpack.data.PlaceRepository
class ChooseAreaModelFactory(private val repository: PlaceRepository) : ViewModelProvider.NewInstanceFactory() {

@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ChooseAreaViewModel(repository) as T
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,16 @@ import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.ViewModelProvider
import com.coolweather.coolweatherjetpack.R
import com.coolweather.coolweatherjetpack.databinding.ActivityWeatherBinding
import com.coolweather.coolweatherjetpack.util.InjectorUtil
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.title.*

class WeatherActivity : AppCompatActivity() {

val viewModel by lazy { ViewModelProviders.of(this, InjectorUtil.getWeatherModelFactory()).get(WeatherViewModel::class.java) }
val viewModel by lazy { ViewModelProvider(viewModelStore, InjectorUtil.getWeatherModelFactory()).get(WeatherViewModel::class.java) }

private val binding by lazy { DataBindingUtil.setContentView<ActivityWeatherBinding>(this, R.layout.activity_weather) }
val binding: ActivityWeatherBinding by lazy { DataBindingUtil.setContentView(this, R.layout.activity_weather) }

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -33,12 +31,12 @@ class WeatherActivity : AppCompatActivity() {
viewModel.weatherId = if (viewModel.isWeatherCached()) {
viewModel.getCachedWeather().basic.weatherId
} else {
intent.getStringExtra("weather_id")
intent.getStringExtra("weather_id")!!
}
navButton.setOnClickListener {
drawerLayout.openDrawer(GravityCompat.START)
binding.title.navButton.setOnClickListener {
binding.drawerLayout.openDrawer(GravityCompat.START)
}
viewModel.getWeather()
viewModel.getWeatherFromRepository()
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import com.coolweather.coolweatherjetpack.data.WeatherRepository
class WeatherModelFactory(private val repository: WeatherRepository) : ViewModelProvider.NewInstanceFactory() {

@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return WeatherViewModel(repository) as T
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class WeatherViewModel(private val repository: WeatherRepository) : ViewModel()

var weatherId = ""

fun getWeather() {
fun getWeatherFromRepository() {
launch ({
weather.value = repository.getWeather(weatherId)
weatherInitialized.value = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import com.coolweather.coolweatherjetpack.R
import com.coolweather.coolweatherjetpack.data.model.weather.Weather
import com.coolweather.coolweatherjetpack.databinding.ForecastItemBinding

@BindingAdapter("bind:loadBingPic")
@BindingAdapter("loadBingPic")
fun ImageView.loadBingPic(url: String?) {
if (url != null) Glide.with(context).load(url).into(this)
}

@BindingAdapter("bind:colorSchemeResources")
@BindingAdapter("colorSchemeResources")
fun SwipeRefreshLayout.colorSchemeResources(resId: Int) {
setColorSchemeResources(resId)
}

@BindingAdapter("bind:showForecast")
@BindingAdapter("showForecast")
fun LinearLayout.showForecast(weather: Weather?) = weather?.let {
removeAllViews()
for (forecast in it.forecastList) {
Expand Down
Loading