I am developing an android app that’s recommends recipes based on the ingredients received from the user. I wrote a python ml model for that and i created an API with flask. This API works fine when i try it on postman but when i try to connect from android studio it doesnt work, actually i dont get any error message but when i run the response doesn’t show on the screen. I used AsyncTask to HTTP connect and get response. Here is mine Python-Flask, MainActivity and AsyncTask codes can someone check and help if there is any fault? (I added Internet permission on AndroidManifest)
from flask import Flask,request,jsonify
import pickle
import numpy as np
import pickle
import sys
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
app = Flask(__name__)
# Veri setini yükle
data = pd.read_csv(r"C:UsersomerpDesktopyemekler_yeni.csv") # Veri setinin dosya adını ve yolunu güncellemelisiniz
dataset = data.fillna('aa')
def important_features(dataset):
data=dataset.copy()
for i in range(0,dataset.shape[0]):
data["imp"]=data["U1"]+' '+data["U2"]+' '+data["U3"]+' '+data["U4"]+' '+data["U5"]+' '+data["U6"]+' '+data["U7"]+' '+data["U8"]+' '+data["U9"]+' '+data["U10"]+' '+data["U11"]
return data
data=important_features(dataset)
vectorizer = CountVectorizer()
malzeme_matrisi = vectorizer.fit_transform(data["imp"])
@app.route('/oneri-yemekler', methods=['POST'])
def yemek_oner():
# Malzemeleri al
kullanici_malzemeleri = request.json.get('malzemeler', [])
kullanici_malzemeleri_string = ' '.join(kullanici_malzemeleri)
benzerlik_skorlari = cosine_similarity(vectorizer.transform([kullanici_malzemeleri_string]), malzeme_matrisi)
en_yuksek_benzerlik_indeksleri = benzerlik_skorlari.argsort()[0][-5:][::-1]
onerilen_yemekler = data.iloc[en_yuksek_benzerlik_indeksleri]["Tercih"].tolist()
return jsonify({"onerilen_yemekler": onerilen_yemekler})
if __name__ == '__main__':
app.run(debug=True)
“kaydetBut1” is the button for the API request and response
package com.example.bugunneyesem.activities
import YourAsyncTaskk
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.bugunneyesem.MalzemeDialog
import com.example.bugunneyesem.databinding.ActivityNePisirsemBinding
import com.example.bugunneyesem.models.ModelMalzeme
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import kotlinx.android.synthetic.main.activity_ne_pisirsem.sonucTV
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
class NePisirsem : AppCompatActivity() {
private lateinit var binding: ActivityNePisirsemBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var malzemelerArrayList: ArrayList<ModelMalzeme>
private val API_URL = "http://127.0.0.1:5000/oneri-yemekler"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityNePisirsemBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
loadMalzemeler()
binding.backBtn.setOnClickListener {
onBackPressed()
}
binding.malzemelerTv.setOnClickListener {
malzemePickDialog()
}
binding.kaydetBut1.setOnClickListener {
val fetchYemeklerTask = YourAsyncTaskk(sonucTV)
val url = "http://my-ip:5000/oneri-yemekler"
val malzemeler = listOf("soğan", "kıyma", "sarımsak")
fetchYemeklerTask.execute(url, malzemeler.joinToString())
}
}
import android.os.AsyncTask
import android.widget.TextView
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
class YourAsyncTaskk(private val textView: TextView) : AsyncTask<String, Void, String>() {
private lateinit var binding: YourAsyncTaskk
override fun doInBackground(vararg params: String?): String {
var result = ""
var connection: HttpURLConnection? = null
try {
val url = URL(params[0])
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json")
val malzemelerJson = JSONObject()
malzemelerJson.put("malzemeler", params[1])
val outputBytes = malzemelerJson.toString().toByteArray(Charsets.UTF_8)
connection.outputStream.write(outputBytes)
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
val reader = BufferedReader(InputStreamReader(connection.inputStream))
val response = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
response.append(line)
}
reader.close()
result = response.toString()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
return result
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
// Response olarak gelen JSON verisini parse edip TextView içine yazdırma
try {
val jsonObject = JSONObject(result)
val yemeklerArray = jsonObject.getJSONArray("onerilen_yemekler")
val yemeklerList = mutableListOf<String>()
for (i in 0 until yemeklerArray.length()) {
yemeklerList.add(yemeklerArray.getString(i))
}
textView.text = yemeklerList.joinToString("n")
} catch (e: Exception) {
e.printStackTrace()
}
}
}
build.gradle depenciesyour text
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
android {
namespace 'com.example.bugunneyesem'
compileSdk 34
defaultConfig {
applicationId "com.example.bugunneyesem"
minSdk 23
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled 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
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.3.1'
}
packaging {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
def lottieVersion = '6.2.0'
dependencies {
implementation 'androidx.core:core-ktx:1.12.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4' //2.1.4
implementation 'androidx.navigation:navigation-fragment-ktx:2.7.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.7.5'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.2'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2'
implementation 'com.google.firebase:firebase-storage:20.3.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.7.0'
implementation 'androidx.activity:activity-compose:1.7.0'
implementation platform('androidx.compose:compose-bom:2023.03.00')
implementation 'androidx.compose.ui:ui'
implementation 'androidx.compose.ui:ui-graphics'
implementation 'androidx.compose.ui:ui-tooling-preview'
implementation 'androidx.compose.material3:material3'
//implementation 'com.google.firebase:firebase-auth:21.2.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
implementation "com.airbnb.android:lottie:$lottieVersion"
//11.8.0 dan 21.2.0 yap?yorum
implementation 'com.google.firebase:firebase-firestore:24.10.0'
implementation 'com.google.firebase:firebase-database:20.3.0'
implementation 'com.google.firebase:firebase-core:21.1.1'
implementation 'com.google.firebase:firebase-auth:20.0.0'
//
implementation 'androidx.work:work-runtime-ktx:2.9.0' //2.7.1
//implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
implementation 'com.squareup.picasso:picasso:2.8'
implementation 'com.github.bumptech.glide:glide:4.12.0'
androidTestImplementation platform('androidx.compose:compose-bom:2023.03.00')
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
debugImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'
implementation "com.squareup.okhttp3:okhttp:4.9.1"
}
I tried to use Kotlin HTTP connect