android中的搜索引擎与数据库

时间:2014-10-20 01:11:24

标签: java android mysql eclipse android-activity

请帮助大家,这是我们的论文,我希望有一个搜索引擎将其变量放入数据库。

这是我们的代码:

all_books.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"


     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical"
   >
    <!-- Main ListView 
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/allbooks"
        android:cacheColorHint="@android:color/transparent"/>

</LinearLayout>

和java文件和php代码:

AllBooksActivity.java

public class AllBooksActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_get_all_books = "http://192.168.0.190/android_connect/get_all_books.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_ADD_BOOK_RECORDS_COPY = "add_book_records_copy";
    private static final String TAG_PID = "pid";
    private static final String TAG_TITLE = "title";

    // products JSONArray
    JSONArray add_book_records_copy = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_books);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllBooks().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditBooksActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllBooks extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllBooksActivity.this);
            pDialog.setMessage("Loading books. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All books from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_get_all_books, "GET",
                    params);

            // Check your log cat for JSON reponse
            Log.d("All Books: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Books
                    add_book_records_copy = json
                            .getJSONArray(TAG_ADD_BOOK_RECORDS_COPY);

                    // looping through All Books
                    for (int i = 0; i < add_book_records_copy.length(); i++) {
                        JSONObject c = add_book_records_copy.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String title = c.getString(TAG_TITLE);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_TITLE, title);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewBooksActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllBooksActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_TITLE }, new int[] { R.id.pid,
                                    R.id.title });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

get_all_books.php

<?php

/*
 * Following code will list all the products
 */

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


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

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT * FROM add_book_records_copy") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["add_book_records_copy"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $add_book_records_copy = array();
        $add_book_records_copy["pid"] = $row["pid"];
        $add_book_records_copy["title"] = $row["title"];
        $add_book_records_copy["authors"] = $row["authors"];
        $add_book_records_copy["subject"] = $row["subject"];
        $add_book_records_copy["created_at"] = $row["created_at"];
        $add_book_records_copy["updated_at"] = $row["updated_at"];



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

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

    // echo no users JSON
    echo json_encode($response);
}
?>

db_config.php

<?php

/*
 * All database connection variables
 */

define('DB_USER', "root"); // db user
define('DB_PASSWORD', "admin1"); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "192.168.0.164"); // db server
?>

db_connect.php

<?php

/**
 * A class file to connect to database
 */
class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?>

请尝试建议一个基于数据库的搜索引擎,如果你知道如何放置它并在其上制作代码。提前谢谢!

1 个答案:

答案 0 :(得分:0)

我目前正在撰写与你类似的论文。基本上,它是一样的。 文档搜索引擎。

我不建议在关系数据库上进行搜索。这是因为它不会有效并且会产生太多的误报。此外,它不支持上下文短语,而且它与数据的结构相结合。

以下是我目前在论文中使用的方法:

  • 我将有两个数据库。一个是关系(SQL),另一个是 面向文档 (NoSQL)
  • 每个数据库将由两个不同的 Web服务
  • 访问和操作
  • 我将所有数据存储在关系数据库中,并且每隔一段时间就将我的&#34; 搜索&#34;数据到文档中。
  • 每当我想检索信息时,我都会使用关系数据库的Web服务。每当我想搜索信息时,我都会使用非关系型数据库的网络服务。

请注意,非关系型数据库仅包含您实际想要搜索的文档(或数据)。其他持久性信息应该在关系数据库中。

总之,关系数据库在检索,插入和删除信息方面非常有效,而非关系数据库在搜索信息方面非常有用。

请查看以下文本搜索引擎。它们是用Java编写的,但可能存在您的语言包装:

  • Apache Lucene
  • Apache Solr(它是Apache Lucene的友好版本,附带预先构建的Web服务以及示例文档。推荐!)