我在以入队方法显示吐司消息时遇到问题。将值插入数据库时,toast消息不会出现在android屏幕上。 我认为无法使用入队方法。
我该如何解决。
private void addValueToDatabase(final String name,final String surname) {
Log.i(LOG,"addValueToDatabase method is working");
result = new Result();
Call<Result> x = Manager.getInstance().addUser(name,surname);
x.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()){
result = response.body();
Toast.makeText(getApplicationContext(), result.getResult(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Log.i(LOG,"addValueToDatabase error........................");
}
});
}
其余插入过程
@FormUrlEncoded
@POST("/insert.php")
Call<Result> addUser(@Field("ad") String ad ,@Field("soyad") String soyad);
insert.php
<?php
//Getting post data
$name = $_POST["ad"];
$username = $_POST["soyad"];
//If the values are not blank
//Connecting to our database by calling dbConnect script
include('connection.php');
//If username is not already exist
//Creating insert query
$sql = "INSERT INTO kullanici (ad,soyad) VALUES('$name','$username')";
//Trying to insert the values to db
if(mysqli_query($conn,$sql)){
//If inserted successfully
$x = (array('Result' => "Ekleme Başarılıdır..."));
echo json_encode($x);
}else{
//In case any error occured
echo 'oops! Please try again!';
}
//Closing the database connection
mysqli_close($conn);
?>
答案 0 :(得分:0)
您最有可能从后台线程调用数据库代码(以防止冻结前端UI),但是随后您试图从非UI线程显示UI元素(敬酒通知)。要显示Toast消息,请尝试通过UI线程进行操作:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), result.getResult(), Toast.LENGTH_LONG).show();
}
});