搜索远程数据库Android应用

时间:2015-02-15 16:13:56

标签: java android json android-activity android-search

我想创建一个Android应用程序作为可以

的搜索引擎
  • 从服务器搜索我的远程数据库,如MAMP,
  • 列出搜索结果和
  • 选择其中一个结果以查看详细信息。

我已经设置了数据库。

Search.java - 仅显示搜索栏的启动页面,允许用户搜索:

        public class Search extends Activity implements OnClickListener{

        private EditText searchterm;
        private Button mSubmit;
        private SharedPreferences preferences;
        private String preFileName="searchrequest";     //this is the Preference file Name
        private String prefKey="searchterm";          //Key to store the User Name

        // Progress Dialog
        private ProgressDialog pDialog;

        // JSON parser class
        JSONParser jsonParser = new JSONParser();

        //php login script

        //localhost :
        private static final String SEARCH_URL = "http://xxx.xxx.x.xxx:8888/searchdb/search.php";

        //ids
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.search);

            searchterm = (EditText)findViewById(R.id.searchterm);

            mSubmit = (Button)findViewById(R.id.searchnow);
            mSubmit.setOnClickListener(this);

            preferences=getSharedPreferences(preFileName, MODE_PRIVATE);
            if(!preferences.getString(prefKey, "not_set").equals("not_set")){
                prefKey.setText(preferences.getString(preFileName, "not_set"));

            }
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            switch (v.getId()) {

                case R.id.searchnow:
                    new SearchQuery().execute();
                    break;

                default:
                    break;
            }

        }

        public class SearchQuery extends AsyncTask<String,String,String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(Search.this);
                pDialog.setMessage("Checking for records...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            @Override
            protected String doInBackground(String... args) {
                // TODO Auto-generated method stub
                // Check for success tag
                int success;
                String searchquery = searchterm.getText().toString();
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("searchquery", searchquery));

                    Log.d("request!", "starting");

                    //Posting user data to script
                    JSONObject json = jsonParser.makeHttpRequest(
                            SEARCH_URL, "POST", params);

                    // full json response
                    Log.d("Search attempt", json.toString());

                    // json success element
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        Log.d("Successful Search!", json.toString());

//need help on how to save search data 
                        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
                    Editor editor = pref.edit();
                    editor.putString("searchquery", searchquery);
                    editor.apply();
                    Intent i = new Intent(Search.this, Result.class);
                    startActivity(i);
                        return json.getString(TAG_MESSAGE);
                    }else{
                        Log.d("Invalid query. Please try again.", json.getString(TAG_MESSAGE));
                        return json.getString(TAG_MESSAGE);

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

                return null;

            }
            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once product deleted
                pDialog.dismiss();
                if (file_url != null){
                    Toast.makeText(Search.this, file_url, Toast.LENGTH_LONG).show();
                }

            }

        }

    }

的search.php:

<?php

 @ $db = new mysqli('localhost','username','password','db');

  if (mysqli_connect_errno()) {
     echo 'Error: Could not connect to database.  
     Please try again later.';
     exit;
  }

if (!empty($_POST)) {

    $query_params = array(
            $term = $_POST['searchquery']
                );

    $words = explode(" ", trim($term));
    $termArray = array();
    foreach($words as $word){
                if(!empty($word)){
                $termArray[] = "+$word";
                                 }
                             }
    $searchinput = implode(" ", $termArray);

        $query = "SELECT * 
                FROM repairsvc 
                    WHERE MATCH(title,address,cat,brand,company) 
                        AGAINST ('".$searchinput."' IN BOOLEAN MODE)
                            ORDER BY title ASC";

    try {

        $result = $db->query($query);
    }
    catch (PDOException $ex) {
        // For testing, you could use a die and message. 
        //die("Failed to run query: " . $ex->getMessage());

        //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));

    }

    //This will be the variable to determine whether or not the user's information is correct.
    //we initialize it as false.
    $num_results = $result->num_rows;

    if ($num_results == 0)    
        {    
        $search_ok = false;
         }
    else
         {$search_ok = true;}

    if ($search_ok) {

        $response["success"] = 1;
        $response["message"] = "Search Successful!";    

        $response["records"]   = array();

    $records             = array();

    while   ($row = $result->fetch_assoc()) {
        $records[] = array('title'=>$row["title"], 'address'=>$row["address"], 
        'company'=>$row["company"], 'id'=>$row["id"], 'brand'=>$row["brand"]); // push into the array
                                            }
    var_dump($records); 
   // foreach ($records as $row) {
    //   echo "Outlet: ", $row['title'], "; Address: ", $row['address'];
    //   }

  //update our repsonse JSON data
    array_push($response["records"], $records);

        // echoing JSON response
        echo json_encode($response);      

    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid Search! Please try again.";
        die(json_encode($response));
    }
} else {
?>
        <h1>Search</h1> 
        <form name="form1" action="search.php" method="post"> 
            Enter Search:<br /> 
            <input type="text" name="searchquery" id="searchquery" placeholder="Search a repair service"/> 
            <br /><br /> 
            <input type="submit" value="Search Now" name="completedsearch"  /> 
        </form> 
    <?php
}

?> 

问题:

  1. 如何从Search.java保存搜索结果并让其他活动Result.java列出结果?
  2. 在第一项活动中将其保存在php中:

    while   ($row = $result->fetch_assoc()) {
            $records[] = array('title'=>$row["title"], 'address'=>$row["address"], 
            'company'=>$row["company"], 'id'=>$row["id"], 'brand'=>$row["brand"]);      // push into the array
                                                }
    
      //update our repsonse JSON data
        array_push($response["records"], $records);
            echo json_encode($response); 
    

    并将listview作为第二个活动(Result.java)??

    1. Result.java - &gt;在列表视图中选择一个结果,如何通过发布项目的ID来搜索数据库来获取详细信息?

1 个答案:

答案 0 :(得分:0)

我通过将其放在Search.java中来测试是否可以搜索:

,从而解决了我的问题
 @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String searchquery = searchterm.getText().toString();

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("searchquery", searchquery));

            Log.d("request!", "starting");

            //Posting user data to script
            JSONObject json = jsonParser.makeHttpRequest(
                    SEARCH_URL, "POST", params);

            // full json response
            Log.d("Search attempt", json.toString());

            // json success element
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Successful Search!", json.toString());
                //save search data


                mCommentList = new ArrayList<HashMap<String, String>>();

                mComments = json.getJSONArray(TAG_POSTS);

               // JSONArray mComments = new JSONArray(TAG_POSTS);

                    // looping through all posts according to the json object returned
                for (int i = 0; i < mComments.length(); i++) {
                    JSONArray innerArray = mComments.optJSONArray(i);
                    for (int j = 0; j < innerArray.length(); j++) {
                        JSONObject c = innerArray.getJSONObject(j);
                        //gets the content of each tag
                        String title = c.getString(TAG_TITLE);
                        String address = c.getString(TAG_ADDRESS);
                        String brand = c.getString(TAG_BRAND);
                        String company = c.getString(TAG_COMPANY);
                        String id = c.getString(TAG_ID);
                        //so our JSON data is up to date same with our array list

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_TITLE, title);
                        map.put(TAG_ADDRESS, address);
                        map.put(TAG_BRAND, brand);
                        map.put(TAG_COMPANY, company);
                        map.put(TAG_ID, id);

                        mCommentList.add(map);
                    }
                }
                Intent r = new Intent(Search.this, Results.class);
                //either
                //r.putExtra("arraylist", mCommentList);
                // startActivityForResult(r, 5000);
               //or
                r.putExtra("searchquery", searchquery);
                startActivity(r);

                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Invalid Search!", json.toString());

                return json.getString(TAG_MESSAGE);

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

        return null;

    }

然后在Results.java中:

public void updateJSONdata() {
        Bundle b = getIntent().getExtras();
        String searchquery = b.getString("searchquery");

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("searchquery", searchquery));

        Log.d("request!", "starting");

        //Posting user data to script
        JSONObject json = jsonParser.makeHttpRequest(
                SEARCH_URL, "POST", params);

        // full json response
        Log.d("Search attempt", json.toString());

        try {

            mResultList = new ArrayList<HashMap<String, String>>();

            mResults = json.getJSONArray(TAG_POSTS);

            // JSONArray mComments = new JSONArray(TAG_POSTS);

            // looping through all posts according to the json object returned
            for (int i = 0; i < mResults.length(); i++) {
                JSONArray innerArray = mResults.optJSONArray(i);
                for (int j = 0; j < innerArray.length(); j++) {
                    JSONObject c = innerArray.getJSONObject(j);
                    //gets the content of each tag
                    String title = c.getString(TAG_TITLE);
                    String address = c.getString(TAG_ADDRESS);
                    String brand = c.getString(TAG_BRAND);
                    String company = c.getString(TAG_COMPANY);
                    String id = c.getString(TAG_ID);
                    //so our JSON data is up to date same with our array list

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_TITLE, title);
                    map.put(TAG_ADDRESS, address);
                    map.put(TAG_BRAND, brand);
                    map.put(TAG_COMPANY, company);
                    map.put(TAG_ID, id);

                    mResultList.add(map);
                }
            }

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

    /**
     * Inserts the parsed data into our listview
     */

    private void updateList() {
         //if you choose the other method
        // final ArrayList<HashMap<String, String>> mResultList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
        // System.out.println("...serialized data.."+mResultList);

        Bundle b = getIntent().getExtras();
        final String searchquery = b.getString("searchquery");

        ListAdapter adapter = new SimpleAdapter(this, mResultList,
                R.layout.single_result, new String[]{TAG_TITLE, TAG_ADDRESS, TAG_BRAND,
                TAG_COMPANY, TAG_ID}, new int[]{R.id.outlet, R.id.address, R.id.brand,
                R.id.company});
        setListAdapter(adapter);

        listView.setSelector(R.drawable.listselector);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                            @Override
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                // ListView Clicked item value
                                                Map<String, String> map = (Map<String, String>) mResultList.get(position);
                                                String record_id = map.get(TAG_ID);
                                                Intent r = new Intent(Results.this, Record.class);
                                                r.putExtra("key", record_id);
                                                r.putExtra("searchquery", searchquery);
                                                startActivity(r);
                                            }

                                        }
        );
    }