Я использую Node.js, express. js и mongodb в качестве бэкэнда. И я использую kotlin в android для внешнего интерфейса. Я строю приложение сканера штрих-кода. Штрих-код содержит электронную почту пользователя. И электронная почта передается на сервер и проверяет (изменить столбец БД) пользователя. LogCat показывает ошибку, как в заголовке выше. Я протестировал js, и проблем нет. Я думаю, что проблема исходит от GSON. Но я не знаю, как ее решить.
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var retrofit: Retrofit
private lateinit var retrofitInterface: RetrofitInterface
private val BASE_URL = "URL"
private lateinit var svBarcode: SurfaceView
private lateinit var tvBarcode: TextView
private lateinit var detector: BarcodeDetector
private lateinit var cameraSource: CameraSource
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var gson = GsonBuilder()
.setLenient()
.create()
retrofit = Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build()
retrofitInterface = retrofit.create(RetrofitInterface::class.java)
svBarcode = findViewById(R.id.sv_barcode)
tvBarcode = findViewById(R.id.tv_barcode)
detector = BarcodeDetector.Builder(this).setBarcodeFormats(ALL_FORMATS).build()
detector.setProcessor(object :Detector.Processor<Barcode> {
override fun release() {}
override fun receiveDetections(detections: Detector.Detections<Barcode>) {
val barcode = detections.detectedItems
if (barcode!!.size() > 0){
var map:HashMap<String, String> = HashMap()
map.put("email",barcode.valueAt(0).displayValue.toString())
var call = retrofitInterface.executeCheckUser(map)
call.enqueue(object: Callback<UserResult> {
override fun onFailure(call: Call<UserResult>, t: Throwable) {
Log.d("Error Callback", t.message.toString())
}
override fun onResponse(
call: Call<UserResult>,
response: Response<UserResult>
) {
if(response.code() == 200) {
Toast.makeText(this@MainActivity, "Participant attendance confirmed", Toast.LENGTH_SHORT).show()
} else if (response.code() == 100) {
Toast.makeText(this@MainActivity, "Already Confirmed", Toast.LENGTH_SHORT).show()
}
if (response.code() == 250) {
val result = response.body()
if (result != null) {
tvBarcode.text ="Nama: " + result.name + "\nEmail: " + result.email + "\nInstitusi" + result.institution + "\nProgram Studi" + result.program
}
}
if(response.code() == 404) {
Toast.makeText(this@MainActivity, "Participant not found", Toast.LENGTH_SHORT).show()
}
}
})
}
}
})
cameraSource = CameraSource.Builder(this,detector).setRequestedPreviewSize(1080,1080)
.setRequestedFps(30f).setAutoFocusEnabled(true).build()
svBarcode.holder.addCallback(object :SurfaceHolder.Callback2{
override fun surfaceRedrawNeeded(p0: SurfaceHolder?) {}
override fun surfaceChanged(p0: SurfaceHolder?, p1: Int, p2: Int, p3: Int) {}
override fun surfaceDestroyed(p0: SurfaceHolder?) {
cameraSource.stop()
}
override fun surfaceCreated(holder: SurfaceHolder?) {
if (ContextCompat.checkSelfPermission(this@MainActivity,
android.Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED)
cameraSource.start(holder)
else ActivityCompat.requestPermissions(this@MainActivity,
arrayOf(android.Manifest.permission.CAMERA),123)
}
})
}
@SuppressLint("MissingPermission")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 123){
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
cameraSource.start(svBarcode.holder)
else Toast.makeText(this,"Camera permission is needed",Toast.LENGTH_SHORT)
.show()
}
}
override fun onDestroy() {
super.onDestroy()
detector.release()
cameraSource.stop()
cameraSource.release()
}
}
RetrofitInterface. java
public interface RetrofitInterface {
@POST("/")
Call<UserResult> executeCheckUser(@Body HashMap<String, String> map);
}
UserResult. java
public class UserResult{
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getInstitution() {
return institution;
}
public String getProgram() {
return program;
}
private String name;
private String email;
private String institution;
private String program;
}
приложение. js
const express = require('express')
const app = express()
const mongoClient = require('mongodb').MongoClient
const url = dbURL
app.use(express.json())
mongoClient.connect(url, (err, db) => {
if (err) {
console.log("Error while connectiong mongo client")
} else {
console.log("Connection success")
const myDb = db.db('myDb')
const collection = myDb.collection('myCollection')
app.post('/', (req, res) => {
const participant = {
email: req.body.email
}
const query = { email: participant.email }
const newvalues = { $set: { hasAttended: true } };
collection.findOne(query, (err, result) => {
console.log("Result " + result)
if (result != null) {
if (result.hasAttended == true) {
console.log("User has attended")
res.status(100).send()
} else {
collection.updateOne(query, newvalues, (err, result) => {
console.log("User attendence updated")
res.status(200).send()
})
}
const objToSend = {
name: result.name,
email: result.email,
institution: result.institution,
program: result.program
}
res.status(250).send(JSON.stringify(objToSend))
console.log(JSON.stringify(objToSend))
} else {
console.log("Can't find user")
res.status(404).send()
}
})
})
}
})