自动完成搜索

时间:2014-12-18 03:04:57

标签: java android autocomplete

我想创建一个自动完成功能,我尝试了自动完成功能,我发现自动完成效果不佳..有人帮我解决这个问题。希望有人可以分享或者给出建议,以便我可以修复我的代码并使其工作。代码原本不是我的,我修改了从互联网资源中获取的代码。

Below is completesearch.java code

package com.trial.completesearch;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AutoCompleteTextView;


public class CompleteSearch extends Activity {

      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_complete_search);
            AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete);
            acTextView.setAdapter(new SuggestionAdapter(this,acTextView.getText().toString()));
        }
    }

SuggestGetSet.java

package com.trial.completesearch;

public class SuggestGetSet {

    String ID,fullname;
    public SuggestGetSet(String ID, String fullname){
        this.setId(ID);
        this.setName(fullname);
    }
    public String getId() {
        return ID;
    }

    public void setId(String id) {
        this.ID = id;
    }

    public String getName() {
        return fullname;
    }

    public void setName(String fullname) {
        this.fullname = fullname;
    }

}

JsonParse.java

package com.trial.completesearch;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


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

public class JsonParse {
     double current_latitude,current_longitude;
     public JsonParse(){}
     public JsonParse(double current_latitude,double current_longitude){
         this.current_latitude=current_latitude;
         this.current_longitude=current_longitude;
     }
     public List<SuggestGetSet> getParseJsonWCF(String sName)
        {
         List<SuggestGetSet> ListData = new ArrayList<SuggestGetSet>();
         try {
            String temp=sName.replace(" ", "%20");
            URL js = new URL("http://192.168.0.20/communityRide/searchKeyRider.php?name="+temp);
            URLConnection jc = js.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
            String line = reader.readLine();
            JSONObject jsonResponse = new JSONObject(line);
            JSONArray jsonArray = jsonResponse.getJSONArray("results");
            for(int i = 0; i < jsonArray.length(); i++){
                JSONObject r = jsonArray.getJSONObject(i);
                ListData.add(new SuggestGetSet(r.getString("ID"),r.getString("fullname")));
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         return ListData;

        }

}

SuggestionAdapter.java

package com.trial.completesearch;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.Filter;

public class SuggestionAdapter extends ArrayAdapter<String> {

    protected static final String TAG = "SuggestionAdapter";
    private List<String> suggestions;
    public SuggestionAdapter(Activity context, String nameFilter) {
        super(context, android.R.layout.simple_dropdown_item_1line);
        suggestions = new ArrayList<String>();
    }

    @Override
    public int getCount() {
        return suggestions.size();
    }

    @Override
    public String getItem(int index) {
        return suggestions.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter myFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                JsonParse jp=new JsonParse();
                if (constraint != null) {
                    // A class that queries a web API, parses the data and
                    // returns an ArrayList<GoEuroGetSet>
                    List<SuggestGetSet> new_suggestions =jp.getParseJsonWCF(constraint.toString());
                    suggestions.clear();
                    for (int i=0;i<new_suggestions.size();i++) {
                        suggestions.add(new_suggestions.get(i).getName());
                    }

                    // Now assign the values and count to the FilterResults
                    // object
                    filterResults.values = suggestions;
                    filterResults.count = suggestions.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence contraint,
                    FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return myFilter;
    }

}

这是我的searchKeyRider.php

<?php

    //array for JSON response
    $response = array();

/*  //include db_connect php file
    require once '/db_connect.php'; */

        // include db connect class
    //require_once __DIR__ . '/db_connect.php'; 
    require_once '/db_connect.php';

    //get connect to db
    $db = new DB_CONNECT();
    $keyword=$_GET["keyword"];
    //$fullname =$_GET["fullname"];

    //get all rides from table rides
    $result = mysql_query("SELECT ID,fullname FROM rider WHERE fullname LIKE '%$keyword%' LIMIT 0, 20") 
or die(mysql_error());
    //check for empty result
    if(mysql_num_rows($result) > 0) {
        //loop all result and put into array rides
        $response["rider"] = array();

        while ($row = mysql_fetch_array($result)) {
            //temp array
            $rider = array();
            $rider["riderID"] = $row["ID"];
            $rider["riderName"] = $row["fullname"];

            //push single ride into final response array
            array_push($response["rider"], $rider);
        }
        //success
        $response["success"] = 1;

        //print JSON response
        echo json_encode($response);
    } else {
        //no rides found
        $response["success"] = 0;
        $response["message"] = "No riders found";

        //print JSON response
        echo json_encode($response);
    }

?>

2 个答案:

答案 0 :(得分:0)

http://manishkpr.webheavens.com/android-autocompletetextview-example-json/

按照以上链接关注。它会正常工作。 然后在androidmanifest.xml中添加Internet权限:

<uses-permission android:name="android.permission.INTERNET" />

希望这会对你有所帮助。

答案 1 :(得分:0)

这是manishkpr示例的php文件

<?php

    //array for JSON response
    $response = array();


    include_once("conn.php");

   $name=$_GET["name"];

$query="SELECT DrugName FROM drugtable WHERE DrugName LIKE '%$name%' LIMIT 0, 20";
$result=mysqli_query($conn,$query);
    //check for empty result
    if(mysqli_num_rows($result) > 0) {
        //loop all result and put into array rides
        $response["results"] = array();

        while ($row = mysqli_fetch_array($result)) {
            //temp array
            $drugtable = array();
            $drugtable["name"] = $row["DrugName"];
            //$drugtable["riderName"] = $row["fullname"];

            //push single ride into final response array
            array_push($response["results"], $drugtable);
        }
        //success
       // $response["success"] = 1;

        //print JSON response
        echo json_encode($response);
    } else {
        //no rides found
        $response["success"] = 0;
        $response["message"] = "No riders found";

        //print JSON response
        echo json_encode($response);
    }

?>

JsonParse.java

public class JsonParse {
     double current_latitude,current_longitude;
     public JsonParse(){}
     public JsonParse(double current_latitude,double current_longitude){
         this.current_latitude=current_latitude;
         this.current_longitude=current_longitude;
     }
     public List<SuggestGetSet> getParseJsonWCF(String sName)
        {
         List<SuggestGetSet> ListData = new ArrayList<SuggestGetSet>();
         try {
            String temp=sName.replace(" ", "%20");
            URL js = new URL("http://192.168.1.21/patientSystem/fetch-all-fish.php"+"?"+"name="+temp);
            URLConnection jc = js.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
            String line = reader.readLine();
            JSONObject jsonResponse = new JSONObject(line);
            JSONArray jsonArray = jsonResponse.getJSONArray("results");
            for(int i = 0; i < jsonArray.length(); i++){
                JSONObject r = jsonArray.getJSONObject(i);
                ListData.add(new SuggestGetSet(r.getString("name")));
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         return ListData;

        }

}