-1

There are values in DB, and I'm creating a search function.

<?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_array($result)) {
        array_push(
            $response, array(
                'name'=>$row['NAME'],
                'age'=>$row['AGE'],
                'address'=>$row['ADDRESS'])
            );
    }

    if(count($response) == 0) {
        $res = 'Empty Result';
        echo $res;
    } else {
        echo json_encode($response);
    }
}

mysqli_close($conn);

?>

If there is no result when I search, and the length of the array is 0, I want to show the Empty Result in View and bring the value to android.

And Android wants to float layout_none_search if the imported value is Empty Result.

public class MainActivity extends AppCompatActivity {

    SearchView searchView;
    ApiInterface apiInterface;
    TextView nameText, ageText, addressText;

    LinearLayout layout_search, layout_none_search;

    @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);

        layout_search = findViewById(R.id.layout_search);
        layout_none_search = findViewById(R.id.layout_none_search);

        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<List<Person>> call = apiInterface.getPerson(key);
        call.enqueue(new Callback<List<Person>>() {
            @Override
            public void onResponse(Call<List<Person>> call, Response<List<Person>> response) {
                if(!response.body().isEmpty()) {
                    layout_search.setVisibility(View.VISIBLE);
                    layout_none_search.setVisibility(View.GONE);

                    Person person = response.body().get(0);
                    nameText.setText(person.getName());
                    ageText.setText(String.valueOf(person.getAge()));
                    addressText.setText(person.getAddress());
                } else if(response.body().equals("Empty Result")) {
                    layout_search.setVisibility(View.GONE);
                    layout_none_search.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<List<Person>> call, Throwable t) {
                Log.e("onFailure", t.toString());
            }
        });
    }
}

But if I run the code now, com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ pops up.

How can I get the Empty Result in Android?

++ Add My 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;
    }
}
luhai
  • 59
  • 6
  • can you try `echo json_encode($res);` – aryanknp Sep 15 '20 at 08:37
  • Thank you. But there's an error. `java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $` I will upload POJO additionally. – luhai Sep 15 '20 at 08:41
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Sep 15 '20 at 12:52

1 Answers1

0

Its because the value can't be parsed as JSON. You can use uniform return format of json.

if(count($response) == 0) {

    echo json_encode([
           "result" => "Empty Result",
            "data" => $response
         ]);
} else {
    echo json_encode([
           "result" => "Has rows",
            "data" => $response
         ]);
}

and in your android parse response.body() in JSON format.

Bevin NIno
  • 75
  • 7
  • Thank you, but there's an error. `java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $` Do I have to change POJO to apply this? – luhai Sep 15 '20 at 09:18