【问题标题】:E/Volley: [1376] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.0.109/connectphp/GetRestaurantData.php?restype=cafeE/Volley:[1376] BasicNetwork.performRequest:http://192.168.0.109/connectphp/GetRestaurantData.php?restype=cafe 的意外响应代码 404
【发布时间】:2016-04-29 17:03:29
【问题描述】:

我设法在网络浏览器上显示以从 mySQL 数据库中检索我的数据。但我无法在我的 android studio v2.0 中检索我的数据。

Configuration.java 类

public class configuration {

public static final String DATA_URL = "http://192.168.0.109/connectphp/GetRestaurantData.php?restype=";

    public static final String KEY_ID = "restaurantid";
    public static final String KEY_name = "restaurantname";
    public static final String KEY_address = "restaurantaddress";
    public static final String KEY_type = "restauranttype";
    public static final String KEY_lat = "restaurantlat";
    public static final String KEY_long = "restaurantlong";
    public static final String KEY_hp = "restauranthp";
    public static final String JSON_ARRAY = "result";
}

餐厅页面类

package com.example.teh.fyp_tp028725;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

@SuppressLint("NewApi")
public class RestaurantPage extends ActionBarActivity implements View.OnClickListener{


    private ListView searchresultview;
    private ProgressDialog loading;
    EditText restauranttext;
    Button press;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurant_page);


        searchresultview = (ListView) findViewById(R.id.restaurantlist);
        restauranttext = (EditText)findViewById(R.id.restauranttypetext);
        press = (Button)findViewById(R.id.searchbutton);
        press.setOnClickListener(this);

    }

    public void getData(){

        String  type  = restauranttext.getText().toString().trim();
        if (type.equals("")){
            Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
            return;
        }
        loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

        String url = configuration.DATA_URL+restauranttext.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loading.dismiss();
                showJSON(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(RestaurantPage.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }


    private void showJSON(String response) {

        String name = "";
        String address = "";
        String type = "";
        String latitude = "";
        String longitude = "";
        String hp = "";

        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray(configuration.JSON_ARRAY);
            JSONObject bookData = result.getJSONObject(0);
            name = bookData.getString(configuration.KEY_name);
            address = bookData.getString(configuration.KEY_address);
            type = bookData.getString(configuration.KEY_type);
            hp = bookData.getString(configuration.KEY_hp);
            //latitude = bookData.getString(configuration.KEY_lat);
            //longitude = bookData.getString(configuration.KEY_long);

            ArrayList<HashMap<String, String>> bookList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("restaurantname", "Place Name : " + name);
            map.put("restaurantaddress", "Address : " + address);
            map.put("restauranttype", "Place Type : " + type);
            map.put("restauranthp", "Phone Number : " + hp);
            bookList.add(map);

            SimpleAdapter simpleAdapter = new SimpleAdapter(this, bookList, R.layout.customizelayout, new String[]{"restaurantname", "restaurantaddress", "restauranttype", "restauranthp"}, new int[]{R.id.textViewname, R.id.textViewaddress, R.id.textViewtype, R.id.textViewhp});
            searchresultview.setAdapter(simpleAdapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onClick(View v) {

        getData();
    }
}

餐厅页面xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.teh.fyp_tp028725.RestaurantPage">

    <TextView
        android:id="@+id/logobar"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="Restaurant"
        android:background="#87F6FF"
        android:textColor="#000000"
        android:textSize="30sp"
        android:textStyle="bold"
        />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/restauranttypetext"
        android:hint="Enter type of restaurant here"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:maxLines="2"
        android:layout_below="@+id/logobar"
        android:layout_marginTop="30dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Search"
        android:id="@+id/searchbutton"
        android:layout_below="@+id/restauranttypetext"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp" />

    <ImageView
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:id="@+id/poweredBy"
        android:src="@drawable/powered_by_google_light"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/restaurantlist"
        android:layout_below="@+id/searchbutton"
        android:layout_marginTop="10dp"
        android:layout_above="@+id/poweredBy"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


</RelativeLayout>

GetRestaurantData.php 类

    <?php 

     if($_SERVER['REQUEST_METHOD']=='GET'){

     $restype  = $_GET['restype'];

     require_once('Connection.php');

     $sql = "SELECT * FROM restaurant WHERE restype='".$restype."'";

     $r = mysqli_query($conn,$sql);

     $res = mysqli_fetch_array($r);

     $result = array();

     array_push($result,array(
     "restaurantid"=>$res['resID'],
     "restaurantname"=>$res['resname'],
     "restaurantaddress"=>$res['resaddress'],
     "restauranttype"=>$res['restype'],
     "restaurantlat"=>$res['reslat'],
     "restaurantlong"=>$res['reslong'],
     "restauranthp"=>$res['reshpnumber'],
     )
     );
     echo json_encode(array("result"=>$result));
     mysqli_close($conn);
     }

Connection.php 类

<?php
$servername = "localhost"; //replace it with your database server name
$username = "root";  //replace it with your database username
$password = "";  //replace it with your database password
$dbname = "fyptp028725";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

我在这里做错了什么吗?请帮助大家!

【问题讨论】:

  • 404 表示找不到页面。路径http://192.168.0.109/connectphp/GetRestaurantData.php 正确吗?

标签: php android mysql android-studio


【解决方案1】:

如果您收到 404 响应,它应该进入您设置的任何错误侦听器。您在错误侦听器中获得一个 VolleyError 对象。您可以从此对象获取网络响应,然后从响应正文中获取数据。它以 char 数组的形式提供,因此您需要自己将其转换为其他内容。

 StringRequest request = new StringRequest( Request.Method.GET, "yourURL", new Response.Listener<String>() {
    @Override
    public void onResponse( String s ) {
        //Do whatever
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse( VolleyError volleyError ) {
        try {
            String responseBody = new String( volleyError.networkResponse.data, "utf-8" );
            JSONObject jsonObject = new JSONObject( responseBody );
        } catch ( JSONException e ) {
            //Handle a malformed json response
        } catch (UnsupportedEncodingException error){

        }
    }
}
);

您也可以使用 volly 使用 JsonObjectRequst 和 JsonArrayRequest,我认为它比字符串请求要好得多,因为您将来自 php 服务的数据作为 JsonArray 传递。

【讨论】:

  • 您好,我用您的方法解决了问题,非常感谢,目前我想通过简单地输入一种类型的列值从整个表中检索数据。有什么办法可以改变我的 sql 查询写作? $sql = "SELECT * FROM restaurant WHERE restype='".$restype."'"; $r = mysqli_query($conn,$sql); $res = mysqli_fetch_array($r); $结果 = 数组(); array_push($result,array( "restaurantid"=>$res['resID'], "restaurantname"=>$res['resname'], "restaurantaddress"=>$res['resaddress'], "restauranttype"= >$res['restype'], ) );
  • @MickTeh 如果它解决了你的问题,请批准我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
相关资源
最近更新 更多