package com.takilab.aroundhokkaido;
import androidx.appcompat.app.AppCompatActivity;
public class SingletonActivity {
private static AppCompatActivity _activity;
public static void SetActivity(AppCompatActivity activity) {
_activity = activity;
}
public static AppCompatActivity GetActivity(){
return _activity;
}
}
JavaとKotlinは混在できるんですね。
実際の開発現場では、どのようにMainActivityを扱っているんですかね?
このMainActivityを使ってJsonの読み出し。
package com.takilab.aroundhokkaido
class City(city: String, distance: Double) {
val city: String = city
val distance: Double = distance
}
package com.takilab.aroundhokkaido
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
class CityList {
val cityList: ArrayList<City> = ArrayList()
init{
val activity: MainActivity = SingletonActivity.GetActivity() as MainActivity
val assetManager = activity.resources.assets //アセット呼び出し
val inputStream = assetManager.open("AroundHokkaido.json") //Jsonファイル
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
val str: String = bufferedReader.readText() //データ
try {
val jsonObject = JSONObject(str)
val jsonArray = jsonObject.getJSONArray("list")
for (i in 0 until jsonArray.length()) {
val jsonData = jsonArray.getJSONObject(i)
val city: City = City(jsonData.getString("city"), jsonData.getDouble("distance"))
cityList.add(city)
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
SingletonActivity.SetActivity(this);
val cityList = CityList()
for (city in cityList.cityList) {
Log.d("Check", "${city.city} : ${city.distance}")
}