你好,我正在为学生创建一个安卓应用程序,以便轻松找到住宿房间,作为学校项目,我在更新方面遇到了一些麻烦。我用000webhost.com创建了一个网络服务。我已经知道put和Delete是付费的,但我的老师告诉我们,我们可以将其嵌入到POST中并使其工作。
通过这种方式,我已经能够使我的DELETE工作。然而,我有麻烦的更新。当我尝试更新,所有的数据改变我想改变它,但在同一时间我的OnFailure方法被调用,它给了我这个错误:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:预期的BEGIN_OBJECT,但在第2行第2列路径$
我觉得很奇怪,因为在我的活动中,我使用类似的代码到我的POST(工作完美),尽管有错误,我的数据被更新,但我想摆脱错误,因为它不允许我按预期改变活动。
这是我的webService PUT嵌入POST(使用slim 4和NOTORM的webService)
//Put anuncios
$app->post('/api/editar_anuncios/{id}', function( $request, $response){
require_once('db/dbconnection.php');
$id = $request->getAttribute('id');
$users_id = $request->getParsedBody()["users_id"];
$morada = $request->getParsedBody()["morada"];
$n_quartos = $request->getParsedBody()["n_quartos"];
$latitude = $request->getParsedBody()["latitude"];
$longitude = $request->getParsedBody()["longitude"];
$fotografia = $request->getParsedBody()["fotografia"];
$preco = $request->getParsedBody()["preco"];
$ncasas_banho = $request->getParsedBody()["ncasas_banho"];
$telemovel = $request->getParsedBody()["telemovel"];
$mobilado= $request->getParsedBody()["mobilado"];
$outros_atributos = $request->getParsedBody()["outros_atributos"];
$qrcode = $request->getParsedBody()["qrcode"];
$data = array(
"users_id"=> $users_id,
"morada" => $morada,
"n_quartos" => $n_quartos,
"latitude" => $latitude,
"longitude" => $longitude,
"fotografia"=> $fotografia,
"preco" => $preco,
"ncasas_banho" => $ncasas_banho,
"telemovel" => $telemovel,
"mobilado" => $mobilado,
"outros_atributos" => $outros_atributos,
"qrcode" => $qrcode
);
if(isset($db->anuncios[$id])){
$result = $db->anuncios[$id]->update($data);
if($result){
echo json_encode('O anuncio foi atualizado com sucesso', JSON_UNESCAPED_UNICODE);
return $response;
} else
echo json_encode('A atualização falhou', JSON_UNESCAPED_UNICODE);
return $response;
} else
echo json_encode('O anuncio não existe', JSON_UNESCAPED_UNICODE);
return $response;
});
我的端点@FormUrlEncoded
@POST("editar_anuncios/{id}")
fun editar(@Path("id") id: Int?,
@Field("users_id") users_id: Int?,
@Field("morada") morada: String?,
@Field("n_quartos") n_quartos: Int?,
@Field("latitude") latitude: Double?,
@Field("longitude") longitude: Double?,
@Field("fotografia") fotografia: String?,
@Field("preco") preco: Double?,
@Field("ncasas_banho") ncasas_banho: Int?,
@Field("telemovel") telemovel: String?,
@Field("mobilado") mobilado: String?,
@Field("outros_atributos") outros_atributos: String?,
@Field("qrcode") qrcode: String?): Call<OutputEditar>
我ServiceBuilder
object ServiceBuilder {
private val client = OkHttpClient.Builder().build()
private val retrofit = Retrofit.Builder()
.baseUrl("https://tneveda.000webhostapp.com/RoomForStudents/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun<T> buildService(service: Class<T>): T {
return retrofit.create(service)
}
}
我OutputEditar
data class OutputEditar(
val users_id: Int,
val morada: String,
val n_quartos: Int,
val latitude: Double,
val longitude: Double,
val fotografia: String,
val preco: Double,
val ncasas_banho: Int,
val telemovel: String,
val mobilado: String,
val outros_atributos: String,
val qrcode: String,
val status: String,
val MSG: String
)
我的Activity for Update的最重要的代码。在OnCreate上,我调用web服务将预期的数据放在我的视图上,它工作得很完美。就在这里,来展示我是如何获取变量来使用我的update
方法的private lateinit var editMoradaView: EditText
private lateinit var editNQuartosView: EditText
private lateinit var shared_preferences: SharedPreferences
private lateinit var latitude : EditText
private lateinit var longitude : EditText
private lateinit var imageView: ImageView
private lateinit var button: Button
private val pickImage = 100
private var imageUri: Uri? = null
private var base64:String? =null
private var fotografia:String? =null
private lateinit var decodedByte: Bitmap
private var isBitMap:Boolean= false
private var ID:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_editar_menu)
imageView = findViewById(R.id.preview)
button = findViewById(R.id.upload)
editMoradaView = findViewById(R.id.morada)
editNQuartosView = findViewById(R.id.nquartos)
latitude = findViewById(R.id.latitude)
longitude = findViewById(R.id.longitude)
button.setOnClickListener {
val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
startActivityForResult(gallery, pickImage)
}
shared_preferences = getSharedPreferences("shared_preferences", Context.MODE_PRIVATE)
val isLogin = shared_preferences.getBoolean("login",false )
setTitle(R.string.edit)
var id = intent.getStringExtra(DetalhesActivity.PARAM_ID)
val request = ServiceBuilder.buildService(EndPoints::class.java)
val call : Call<List<Anuncio>> = request.getAnunciosById2(id)
call.enqueue(object : Callback<List<Anuncio>> {
override fun onResponse(call: Call<List<Anuncio>>, response: Response<List<Anuncio>>) {
if (response.isSuccessful) {
anuncios = response.body()!!
for (anuncio in anuncios) {
editMoradaView.setText(anuncio.morada)
editNQuartosView.setText(anuncio.n_quartos.toString())
latitude.setText(anuncio.latitude.toString())
longitude.setText(anuncio.longitude.toString())
ID = anuncio.id
val decodedString: ByteArray = Base64.decode(anuncio.fotografia, Base64.DEFAULT)
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
imageView.setImageBitmap(decodedByte)
isBitMap= true
}
}
}
override fun onFailure(call: Call<List<Anuncio>>, t: Throwable) {
Toast.makeText(this@EditarAnuncio,"${t.message}", Toast.LENGTH_LONG).show()
}
})
}
我的更新方法,我检查文件是否为位图,因为当我从我的手机选择一张图片时,我将其更改为位图,然后更改为base64字符串,我在数据库中以这种方式插入它。但是当我从数据库中获得图片以在我的ImageView上显示它时,我将其从base64更改为仅位图,并以该格式在屏幕上显示它。所以我必须检查我的文件是哪一种格式,以正确地更新它(它正在按我的意图工作,因为如果我试图改变它,图片就会更新)。我尝试更改默认值来测试是否所有内容都更新了,并且所有内容都应该更新。然而,它仍然从onFailure方法传递错误,我不明白为什么会发生这种情况,我能做些什么来使错误消失。谢谢你
fun editar(view: View) {
val request = ServiceBuilder.buildService(EndPoints::class.java)
val latitude = latitude.text.toString().toDouble()
val longitude = longitude.text.toString().toDouble()
val morada= editMoradaView.text.toString()
val n_quartos = editNQuartosView.text.toString().toInt()
val utilizador_id = shared_preferences.getInt("id", 0)
if(isBitMap){
val base = getBase64String(decodedByte)
fotografia = base
}
else{
fotografia = base64
}
val call = request.editar(
id = ID,
users_id = utilizador_id,
morada = morada,
n_quartos = n_quartos,
latitude = latitude.toString().toDouble(),
longitude = longitude.toString().toDouble(),
fotografia = fotografia,
preco = 21.0,
ncasas_banho = 4,
telemovel= "teste3",
mobilado = "teste3",
outros_atributos = "2",
qrcode = "teste3")
call.enqueue(object : Callback<OutputEditar> {
override fun onResponse(call: Call<OutputEditar>, response: Response<OutputEditar>){
if (response.isSuccessful){
val c: OutputEditar = response.body()!!
Toast.makeText(this@EditarAnuncio, c.MSG, Toast.LENGTH_LONG).show()
val intent = Intent(this@EditarAnuncio, MapsActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onFailure(call: Call<OutputEditar>, t: Throwable){
Toast.makeText(this@EditarAnuncio,"${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
编辑:
我试着测试我的更新在邮差通过把Json像这样,它在邮差工作。然而,在我的应用程序,它仍然不工作。我不明白我在我的应用程序中没有得到这种格式(似乎是这样)
但是当我尝试在我的数据库中插入数据(与我的代码类似于更新)它的工作没有任何错误。在我的更新,它工作,但不是100%,因为它仍然给我的错误
{
"users_id": 1,
"n_quartos": 2,
"latitude": 20.0,
"longitude": 2.0,
"morada": "teste",
"fotografia": "teste",
"preco": 240,
"ncasas_banho": 4,
"telemovel": 9242424242,
"mobilado": "teste",
"outros_atributos": "teste",
"qrcode": "teste"
}
终于解决了我的问题,问题是我的部分缺乏关注。由于我的数据正在更新,这意味着我正在从我的web服务得到响应,但在某些时候它会导致该错误,所以我猜也许我在应用程序上的代码都是正确的,问题是在web服务内部,Bingo
因为我把变量MSG和状态放在我的OutputEditar中,它期望在我的web服务上找到它们。我在我所有的帖子和我的删除中定义了它们,但我忘了在我的放上添加它们,所以我在我的端点结束时像这样添加它们,现在它正在正常工作,因为我想要它。
$app->post('/api/editar_anuncios/{id}', function( $request, $response){
require_once('db/dbconnection.php');
$id = $request->getAttribute('id');
$users_id = $request->getParsedBody()["users_id"];
$morada = $request->getParsedBody()["morada"];
$n_quartos = $request->getParsedBody()["n_quartos"];
$latitude = $request->getParsedBody()["latitude"];
$longitude = $request->getParsedBody()["longitude"];
$fotografia = $request->getParsedBody()["fotografia"];
$preco = $request->getParsedBody()["preco"];
$ncasas_banho = $request->getParsedBody()["ncasas_banho"];
$telemovel = $request->getParsedBody()["telemovel"];
$mobilado= $request->getParsedBody()["mobilado"];
$outros_atributos = $request->getParsedBody()["outros_atributos"];
$qrcode = $request->getParsedBody()["qrcode"];
$data = array(
"users_id"=> $users_id,
"morada" => $morada,
"n_quartos" => $n_quartos,
"latitude" => $latitude,
"longitude" => $longitude,
"fotografia"=> $fotografia,
"preco" => $preco,
"ncasas_banho" => $ncasas_banho,
"telemovel" => $telemovel,
"mobilado" => $mobilado,
"outros_atributos" => $outros_atributos,
"qrcode" => $qrcode
);
if(isset($db->anuncios[$id])){
$result = $db->anuncios[$id]->update($data);
if($result){
$result = ['status' => true, 'MSG' => "Anúncio atualizado!"];
echo json_encode($result, JSON_UNESCAPED_UNICODE);
return $response;
} else
$result = ['status' => false, 'MSG' => "Erro na atualizacao do anúncio!"];
echo json_encode($result, JSON_UNESCAPED_UNICODE);
return $response;
} else
$result = ['status' => false, 'MSG' => "O Anúncio nao existe!"];
echo json_encode($result, JSON_UNESCAPED_UNICODE);
return $response;
});