Я пытаюсь проанализировать файл JSON и пытаюсь отобразить содержимое JSON в представлении списка. Вот мой контент API.
[
{
"photo": "https://c1.staticflickr.com/1/169/396525383_9140cca7c0.jpg",
"author": "Toby Keller"
},
{
"photo": "https://c1.staticflickr.com/1/62/205125225_65381511a5.jpg",
"author": "Louis Vest"
},
{
"photo": "https://c1.staticflickr.com/5/4090/5171453436_92d3b3f287.jpg",
"author": "Mike Behnken"
},
{
"photo": "https://c1.staticflickr.com/3/2557/3943872114_5bab1ed4ae.jpg",
"author": "Luigi Alesi"
},
{
"photo": "https://c1.staticflickr.com/5/4088/4952370052_62daf4e03e.jpg",
"author": "Eleder Jimenez Hermoso"
}
]
Я могу получить данные из API, но формат изображения не поддерживается. Как я могу отобразить изображение при просмотре изображения?
Вот что я попробовал:
Main Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val url = findViewById<EditText>(R.id.editText).text
var load = findViewById<Button>(R.id.button)
load.setOnClickListener {
AsyncTaskHandler().execute(url.toString())
}
}
inner class AsyncTaskHandler:AsyncTask<String,String,String>() {
override fun onPreExecute() {
super.onPreExecute()
findViewById<ProgressBar>(R.id.loader).visibility = View.VISIBLE
}
override fun doInBackground(vararg p0: String?): String {
return try {
p0.first().let {
val url = URL(it)
val urlConnect = url.openConnection() as HttpURLConnection
urlConnect.connectTimeout = 700
publishProgress(100.toString())
urlConnect.inputStream.bufferedReader().readText()
}
} catch (e: Exception) {
p0.first().let {
val url = URL(it)
val urlConnect = url.openConnection() as HttpURLConnection
urlConnect.disconnect().toString()
}
}
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
findViewById<ProgressBar>(R.id.loader).visibility = View.GONE
jsonResult(result)
Log.d("Fetched Data", result)
}
private fun jsonResult(jsonString: String?){
val jsonArray = JSONArray(jsonString)
val list=ArrayList<MyData>()
var i = 0
while(i<jsonArray.length()){
val jsonObject=jsonArray.getJSONObject(i)
list.add(
MyData(
jsonObject.getString("author"),
jsonObject.getString("photo")
)
)
i++
}
val adapter = ListAdapter(this@MainActivity,list)
val listView = findViewById<ListView>(R.id.listView)
listView.adapter = adapter
}
}
}
List_adapter:
class ListAdapter(val context: Context, val list: ArrayList<MyData>):BaseAdapter() {
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val view:View = LayoutInflater.from(context).inflate(R.layout.list_row,p2,false)
val photo = view.findViewById<ImageView>(R.id.authImage)
val author = view.findViewById<TextView>(R.id.authName)
author.text=list[p0].author
photo.setImageURI(Uri.parse(list[p0].photo))
return view
}
override fun getItem(p0: Int): Any {
return p0
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return list.size
}
}