I want to use the retrofit interface like this.
public interface ApiInterface {
@GET("test.php")
Call<Person> getPerson(@Query("name") String keyword);
}
I have this error because I have squeezed and executed php like this.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I want to use Call<Person>
, I don't want to use Call<List<Person>>
Here's the php I made.
<?php
require_once 'conn.php';
if(isset($_GET['name'])) {
$name = $_GET['name'];
$query = "SELECT `NAME`, AGE, `ADDRESS` FROM test WHERE `NAME` = '$name'";
$result = mysqli_query($conn, $query);
$response = array();
while($row = mysqli_fetch_assoc($result)) {
array_push(
$response, array(
'name'=>$row['NAME'],
'age'=>$row['AGE'],
'address'=>$row['ADDRESS'])
);
}
echo json_encode($response);
}
mysqli_close($conn);
?>
This is Person POJO.
public class Person {
@SerializedName("name") private String name;
@SerializedName("age") private int age;
@SerializedName("address") private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
I finally want to use it in MainActivity like this.
public class MainActivity extends AppCompatActivity {
SearchView searchView;
ApiInterface apiInterface;
TextView nameText, ageText, addressText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameText = findViewById(R.id.nameText);
ageText = findViewById(R.id.ageText);
addressText = findViewById(R.id.addressText);
searchView = findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
personList(s);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
public void personList(String key) {
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<Person> call = apiInterface.getPerson(key);
call.enqueue(new Callback<Person>() {
@Override
public void onResponse(Call<Person> call, Response<Person> response) {
Person person = response.body();
nameText.setText(person.getName());
System.out.println("Name : " + person.getName());
}
@Override
public void onFailure(Call<Person> call, Throwable t) {
Log.e("onFailure", t.toString());
}
});
}
}
I don't know how to modify it, not the arrangement.
>`. Note you will need to make changes to your main activity to reflect this
>`. What I'm making now is, when I search for a name, I get his name, age, and address and put it in each TextView. Sorry...
– luhai Sep 14 '20 at 06:43