Android Studio Java veya Kotlin ile Veri Çekme
Android Studio Java veya Kotlin ile Veri Çekme
Kotlin’de veya Java’da bir web sitesinden veri çekmek için genellikle aşağıdaki yöntemlerden birini kullanabilirsin:
1. Jsoup ile HTML Parse Etmek
Web sayfasındaki belirli bir veriyi almak için Jsoup
kütüphanesini kullanabilirsin. Bu yöntem genellikle HTML yapısındaki veriyi ayıklamak için kullanılır.
Adımlar:
- Jsoup Kütüphanesini Projeye Ekle:
build.gradle
dosyanıza aşağıdaki bağımlılığı ekleyin:
implementation ‘org.jsoup:jsoup:1.15.4’
Kodu Yaz: Doviz web sitesinden “ALTIN” verisini çekmek için bir örnek:
private fun fetchGoldDataWithJsoup() { Thread { try { val url = "https://altin.doviz.com/" val document = Jsoup.connect(url).get() // Gram altının alış fiyatı val buyPrice = document.select("td[data-socket-key=gram-altin][data-socket-attr=bid]").text() // Gram altının satış fiyatı val sellPrice = document.select("td[data-socket-key=gram-altin][data-socket-attr=ask]").text() // Fiyatları ekrana yazdır val result = "Alış: $buyPrice\nSatış: $sellPrice" // UI'ye sonucu yazdır runOnUiThread { tvResult.text = "Jsoup Sonuç:\n$result" } } catch (e: Exception) { e.printStackTrace() runOnUiThread { tvResult.text = "Jsoup ile hata: ${e.message}" } } }.start() }
Dikkat Edilmesi Gerekenler:
- HTML yapısını incele: İlgili elementin HTML yapısını bulmak için web sayfasını aç ve “İncele” (Inspect) aracını kullanarak doğru
CSS Selector
bul. - Thread kullanımı: Ağ işlemleri için ayrı bir thread veya Kotlin Coroutines kullan.
2.Retrofit Bağımlılığı ile veri çekme
Eğer web sitesi bir API sunuyorsa, bu API’den JSON formatında veri çekmek daha güvenli ve kolaydır.
Adımlar:
- Retrofit Bağımlılığı Ekleyin:
implementation ‘com.squareup.retrofit2:retrofit:2.9.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.9.0’
API’yi Tanımlayın:
interface GoldApiService { @GET("api/gold-prices") // Gerçek API endpoint adresini değiştir suspend fun getGoldPrices(): List<GoldPrice> } data class GoldPrice(val name: String, val price: String) private fun fetchGoldPricesWithRetrofit() { val retrofit = Retrofit.Builder() .baseUrl("https://altin.doviz.com/") // Gerçek API URL'sini değiştir .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(GoldApiService::class.java) GlobalScope.launch { try { val goldPrices = service.getGoldPrices() runOnUiThread { tvResult.text = "Retrofit Sonuç: $goldPrices" } } catch (e: Exception) { e.printStackTrace() runOnUiThread { tvResult.text = "Retrofit ile hata: ${e.message}" } } } }
Dikkat Edilmesi Gerekenler:
- Haremaltin.com’da JSON API olup olmadığını kontrol etmelisin. Eğer API varsa kesinlikle bu yöntemi tercih et.
- API’nin kullanım detaylarını öğrenmek için web sitesinin geliştirici belgelerine göz atabilirsin.
3. Web Scraping İçin Alternatif Çözümler
Eğer Jsoup
işe yaramıyorsa ve API yoksa, alternatif olarak OkHttp
veya başka HTTP kütüphanelerle sayfa içeriğini çekip kendin parse edebilirsin. Örnek:
private fun fetchHtmlWithOkHttp() { Thread { try { val client = OkHttpClient() val request = Request.Builder() .url("https://altin.doviz.com/") .build() val response = client.newCall(request).execute() val html = response.body?.string() runOnUiThread { tvResult.text = "OkHttp Sonuç: ${html?.substring(0, 500)}..." } } catch (e: Exception) { e.printStackTrace() runOnUiThread { tvResult.text = "OkHttp ile hata: ${e.message}" } } }.start() }
Tavsiye:
- Eğer sadece “ALTIN” gibi verileri düzenli çekeceksen, önce web sitesinin izinlerini ve API alternatiflerini kontrol et.
- Scraping (veri kazıma) işlemi yaparken web sitesinin kullanım koşullarını ihlal etmemeye özen göster.
Bu 3 farklı yöntemi aslında ayrı ayrı deneyerek hangisinin sitede çalışıp çalışmadığını kontrol edebilirsiniz fakat biz bu 3 yöntemi de bir uygulamada birleştirerek işleri biraz hızlandıracağız ..
Şimdi baştan projeyi anlatacak olursak ;
Android Studio’yu açıp New kısmında Empty Activity tasarımını seçip uygulamanızı başlatın..
Gradle kısmına gelip eklemeniz gerekenleri şöyle ekleyin
implementation libs.androidx.core.ktx implementation libs.androidx.lifecycle.runtime.ktx implementation libs.androidx.activity.compose implementation platform(libs.androidx.compose.bom) implementation libs.androidx.ui implementation libs.androidx.ui.graphics implementation libs.androidx.ui.tooling.preview implementation libs.androidx.material3 implementation libs.jsoup implementation libs.okhttp implementation libs.retrofit implementation libs.converter.gson implementation libs.kotlinx.coroutines.core implementation libs.androidx.appcompat testImplementation libs.junit androidTestImplementation libs.androidx.junit androidTestImplementation libs.androidx.espresso.core androidTestImplementation platform(libs.androidx.compose.bom) androidTestImplementation libs.androidx.ui.test.junit4 debugImplementation libs.androidx.ui.tooling debugImplementation libs.androidx.ui.test.manifest
compileSdk 35 targetSdk 35 değerlerinin bu şekilde olmasına dikkat edin. MainActivity.kt Kodları şu şekilde düzeltin .package com.example.aiocalc import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.example.aiocalc.R import kotlinx.coroutines.* import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.Jsoup import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET class MainActivity : AppCompatActivity() { private lateinit var tvResult: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tvResult = findViewById(R.id.tvResult) findViewById<Button>(R.id.btnJsoup).setOnClickListener { fetchGoldDataWithJsoup() } findViewById<Button>(R.id.btnOkHttp).setOnClickListener { fetchHtmlWithOkHttp() } findViewById<Button>(R.id.btnRetrofit).setOnClickListener { fetchGoldPricesWithRetrofit() } } // Jsoup ile Veri Çekme private fun fetchGoldDataWithJsoup() { Thread { try { val url = "https://altin.doviz.com/" val document = Jsoup.connect(url).get() // Gram altının alış fiyatı val buyPrice = document.select("td[data-socket-key=gram-altin][data-socket-attr=bid]").text() // Gram altının satış fiyatı val sellPrice = document.select("td[data-socket-key=gram-altin][data-socket-attr=ask]").text() // Fiyatları ekrana yazdır val result = "Alış: $buyPrice\nSatış: $sellPrice" // UI'ye sonucu yazdır runOnUiThread { tvResult.text = "Jsoup Sonuç:\n$result" } } catch (e: Exception) { e.printStackTrace() runOnUiThread { tvResult.text = "Jsoup ile hata: ${e.message}" } } }.start() } // OkHttp ile Veri Çekme private fun fetchHtmlWithOkHttp() { Thread { try { val client = OkHttpClient() val request = Request.Builder() .url("https://altin.doviz.com/") .build() val response = client.newCall(request).execute() val html = response.body?.string() runOnUiThread { tvResult.text = "OkHttp Sonuç: ${html?.substring(0, 500)}..." } } catch (e: Exception) { e.printStackTrace() runOnUiThread { tvResult.text = "OkHttp ile hata: ${e.message}" } } }.start() } // Retrofit ile API Kullanımı interface GoldApiService { @GET("api/gold-prices") // Gerçek API endpoint adresini değiştir suspend fun getGoldPrices(): List<GoldPrice> } data class GoldPrice(val name: String, val price: String) private fun fetchGoldPricesWithRetrofit() { val retrofit = Retrofit.Builder() .baseUrl("https://altin.doviz.com/") // Gerçek API URL'sini değiştir .addConverterFactory(GsonConverterFactory.create()) .build() val service = retrofit.create(GoldApiService::class.java) GlobalScope.launch { try { val goldPrices = service.getGoldPrices() runOnUiThread { tvResult.text = "Retrofit Sonuç: $goldPrices" } } catch (e: Exception) { e.printStackTrace() runOnUiThread { tvResult.text = "Retrofit ile hata: ${e.message}" } } } } }
Son olarak activity_main.xml dosyanıza şu kodları ekleyin.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" android:gravity="center"> <!-- Başlık --> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Altın Fiyatlarını Çekme" android:textSize="20sp" android:textStyle="bold" android:layout_marginBottom="16dp" /> <!-- Çıktı İçin TextView --> <TextView android:id="@+id/tvResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Sonuçlar burada görünecek..." android:padding="8dp" android:background="#E0E0E0" android:textColor="#000000" android:layout_marginBottom="16dp" /> <!-- Jsoup ile Veri Çekme Butonu --> <Button android:id="@+id/btnJsoup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Jsoup ile Veri Çek" /> <!-- OkHttp ile Veri Çekme Butonu --> <Button android:id="@+id/btnOkHttp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="OkHttp ile Veri Çek" android:layout_marginTop="8dp" /> <!-- Retrofit ile Veri Çekme Butonu --> <Button android:id="@+id/btnRetrofit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Retrofit ile Veri Çek" android:layout_marginTop="8dp" /> </LinearLayout>
Uygulamınızı çalıştığınızda 1 Adet Textview ve 3 adet Butonunuz bulunacak , hangi yöntem çalışıyorsa o yöntem üzerinden devam edip programınızı geliştirebilirsiniz.
Keyifli Kodlamalar..