怎样才能从PHP中获取结果?

huangapple go评论79阅读模式
英文:

How do I get the results from the php?

问题

以下是您要的翻译:

PHP 代码部分:

有数据库中的值,我正在创建一个搜索函数。

如果在搜索时没有结果,并且数组的长度为0,则我想在视图中显示 "Empty Result" 并将该值传递到 Android。

```php
<?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);

?>

Android 代码部分:

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());
            }
        });
    }
}

如果我现在运行代码,会弹出 "com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $"。如何在 Android 中获取 "Empty Result"?


++ 添加我的 POJO
```java
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;
}
}
英文:

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

&lt;?php
require_once &#39;conn.php&#39;;
if(isset($_GET[&#39;name&#39;])) {
$name = $_GET[&#39;name&#39;];
$query = &quot;SELECT `NAME`, AGE, `ADDRESS` FROM test WHERE `NAME` = &#39;$name&#39;&quot;;
$result = mysqli_query($conn, $query);
$response = array();
while($row = mysqli_fetch_array($result)) {
array_push(
$response, array(
&#39;name&#39;=&gt;$row[&#39;NAME&#39;],
&#39;age&#39;=&gt;$row[&#39;AGE&#39;],
&#39;address&#39;=&gt;$row[&#39;ADDRESS&#39;])
);
}
if(count($response) == 0) {
$res = &#39;Empty Result&#39;;
echo $res;
} else {
echo json_encode($response);
}
}
mysqli_close($conn);
?&gt;

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&lt;List&lt;Person&gt;&gt; call = apiInterface.getPerson(key);
call.enqueue(new Callback&lt;List&lt;Person&gt;&gt;() {
@Override
public void onResponse(Call&lt;List&lt;Person&gt;&gt; call, Response&lt;List&lt;Person&gt;&gt; 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(&quot;Empty Result&quot;)) {
layout_search.setVisibility(View.GONE);
layout_none_search.setVisibility(View.VISIBLE);
}
}
@Override
public void onFailure(Call&lt;List&lt;Person&gt;&gt; call, Throwable t) {
Log.e(&quot;onFailure&quot;, 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(&quot;name&quot;) private String name;
@SerializedName(&quot;age&quot;) private int age;
@SerializedName(&quot;address&quot;) 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;
}
}

答案1

得分: 0

因为这个值无法被解析为 JSON。
你可以使用统一的 JSON 返回格式。

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

在你的 Android 代码中,以 JSON 格式解析 response.body()

英文:

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([
&quot;result&quot; =&gt; &quot;Empty Result&quot;,
&quot;data&quot; =&gt; $response
]);
} else {
echo json_encode([
&quot;result&quot; =&gt; &quot;Has rows&quot;,
&quot;data&quot; =&gt; $response
]);
}

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

huangapple
  • 本文由 发表于 2020年9月15日 16:25:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63897941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定