I am trying to learn retrofit, though it was fairly easy to retrieve texts from the database. I am kinda having trouble when submitting data to the database.
The data I am submitting goes to the database but it shows this error everytime I submit the data.The toast says - Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $
This is my RegisterAPI activity:
public interface RegisterAPI {
@FormUrlEncoded
@POST("/insertText.php")
Call<Result> createUser(
@Field("name") String name,
@Field("age") String age);
}
This is my Person class:
public class Person {
@SerializedName("name")
private String name;
@SerializedName("age")
private String age;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
This is my insertActivity:
public static String ROOT_URL = "https://MYURL/";
public void insertUser(){
String name = editTextName.getText().toString().trim();
String age = editTextAge.getText().toString().trim();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RegisterAPI api = retrofit.create(RegisterAPI.class);
Person user = new Person(name, age);
Call<Person> call = api.createUser(user.getName(),user.getAge());
call.enqueue(new Callback<Person>() {
@Override
public void onResponse(Call<Person> call, Response<Person> response) {
Toast.makeText(insertActivity.this, "SUCCESS", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<Person> call, Throwable t) {
Toast.makeText(insertActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
RetrieveText
[{"name":"Gionne","age":"12"},
{"name":"Harley","age":"25"},
{"name":"Gamboa","age":"30"},
{"name":"Lapuz","age":"35"}]
ANSWER TO QUESTION BELOW
Well I want to answer my own question but I am unable to answer it below cause I was marked as DUPLICATE. Anyways the issue were two things, my PHP insertText.php file and my Objects class.
This is my insertText.php file:
<?php
require_once('dbConnect.php');
$name = $_POST['name'];
$age = $_POST['age'];
$sql = "INSERT INTO javaScriptTesting
(name,age)
VALUES
('$name','$age')";
if(mysqli_query($con,$sql)) {
//ADDED THIS LINE
$response["message"] = "DATA INSERTED";
echo json_encode($response);
} else {
//ADDED THIS LINE
$response["message"] = "UNSUCCESSFUL";
echo json_encode($response);
}
mysqli_close($con);
and then this is my Objects class:
public class Person {
@SerializedName("name")
private String name;
@SerializedName("age")
private String age;
//ADDED THIS LINE
private String message;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
//ADDED THIS LINE
public String getMessage() {
return message;
}
> call` and change your method according this.
– Ved Nov 01 '17 at 08:45