Android - org.json.JSONException:字符0的输入结束

时间:2017-07-31 14:44:59

标签: java php android mysql json

我有一个Android应用程序,用于比较MySQL数据库中数据的用户输入,如果匹配则显示它。我使用WAMP作为本地服务器和PHP文件从数据库中获取数据并将结果作为JSON回显。

问题在于我只能搜索和查找数据库中的某些数据,并且由于某些原因并非全部。当我尝试从Android应用程序获取数据时,这只是一个问题。如果我直接在DBMS中编写查询,我能够获得所需的所有数据。因此,解析数据时一定存在问题,但我无法弄清楚它是什么。

Fx的。如果我写下面的查询,我能够获取数据:

$search_query='messi';
      $sql = 'SELECT Name, Club_position from spillere_fuld2 where MATCH(Name, Club_position) AGAINST(:search_query)';

但是,如果我只是将名称更改为“罗纳尔多”,那么它就不起作用了:

$search_query='ronaldo';
      $sql = 'SELECT Name, Club_position from spillere_fuld2 where MATCH(Name, Club_position) AGAINST(:search_query)';

当我这样做时,我的logcat说明如下: enter image description here

这就是我的完整PHP文件的样子:

<?php
 include 'config.inc.php';

 if(isset($_POST['searchQuery']))
 {
      //require_once('config.inc.php');
      $search_query=$_POST['searchQuery'];
      $search_query='messi';
      $sql = 'SELECT Name, Club_position from spillere_fuld2 where MATCH(Name, Club_position) AGAINST(:search_query)';


      $statement = $conn->prepare($sql);
  $statement->bindParam(':search_query', $search_query, PDO::PARAM_STR);
      $statement->execute();
      if($statement->rowCount())
      {
    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
    header('Content-type: application/json');
    echo json_encode($row_all);
      }  
      elseif(!$statement->rowCount())
      {
    echo "no rows";
      }
 }    
 ?>

这是我的类,我使用AsyncTask建立与数据库的连接,并将数据从JSON解析为Java对象:

    public class PlayerSearchActivity extends AppCompatActivity {

   // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
   public static final int CONNECTION_TIMEOUT = 10000;
   public static final int READ_TIMEOUT = 15000;
   private RecyclerView mRVFish;
   private SearchAdapter mAdapter;


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

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    //Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.position_array, android.R.layout.simple_spinner_item);
   //Specify the layout to use when the list of choices appears
 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);

 }

//Get string from EditText and create object of class AsyncFetch with the string.
//Need to use SearchView instead of EditText!
public void searchButton(View view){
    EditText playerName = (EditText) findViewById(R.id.playerSearch);
    String query = String.valueOf(playerName.getText());
    new AsyncFetch(query).execute();
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(PlayerSearchActivity.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery) {
        this.searchQuery = searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.87.100/DUFT/playersearch.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                //Pass data to onPostExecute method
                return (result.toString());

            } else {
                return ("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<PlayerData> data = new ArrayList<>();

        pdLoading.dismiss();
        if (result.equals("no rows")) {
            Toast.makeText(PlayerSearchActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        } else {

            try {
                Log.i("tagconvertstr", "["+result+"]");
                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);

                    PlayerData playerData = new PlayerData();
                    playerData.fornavn = json_data.getString("Name");
                    playerData.placering = json_data.getString("Club_position");
                    data.add(playerData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new SearchAdapter(PlayerSearchActivity.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(PlayerSearchActivity.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                //Toast.makeText(PlayerSearchActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
                Toast.makeText(PlayerSearchActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}
}

为什么我能从数据库中获取一些名称但不是全部?

希望有人可以帮助我!谢谢

0 个答案:

没有答案