是否可以从网站获取数据以填充数据库?

时间:2015-04-21 19:17:03

标签: android database sqlite jsoup recipe

所以,我的应用程序本质上是一个食谱搜索应用程序。我有一个包含所有食谱的数据库。但是,我最初需要大量的食谱才能显示所有功能。那么,是否有可能从网站上提取食谱并以某种方式将它们插入我的数据库?

2 个答案:

答案 0 :(得分:4)

这是可能的。您可以使用Web服务获取数据并插入应用程序使用的sqlite数据库。这是Sqlite Db的一个例子。这是一个具有关系数据库模型的文字游戏的例子。我希望这对你有所帮助。

SQLiteHelper:

public class SQLiteHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "RotatingCards.db";


    public static final String SQL_DELETE_ENTRIES = "";

    public SQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // CREATE STATEMENTS
        db.execSQL(EntryContract.ExamsEntry.CREATE_STATEMENT);
        db.execSQL(EntryContract.SubjectsEntry.CREATE_STATEMENT);
        db.execSQL(EntryContract.WordsEntry.CREATE_STATEMENT);
        db.execSQL(EntryContract.WordsToExamEntry.CREATE_STATEMENT);

        // POPULATE STATEMENTS
        db.execSQL(EntryContract.ExamsEntry.POPULATE_STATEMENT);
        db.execSQL(EntryContract.SubjectsEntry.POPULATE_STATEMENT);
        db.execSQL(EntryContract.WordsEntry.POPULATE_STATEMENT);
        db.execSQL(EntryContract.WordsToExamEntry.POPULATE_STATEMENT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}

您的自定义SQLiteHelper

public class MySQLiteHelper extends SQLiteHelper {

    public MySQLiteHelper(Context context) {
        super(context);
    }

    public List<Exam> getAllExams() {
        List<Exam> exams = new ArrayList<>();
        try {
            SQLiteDatabase db = getReadableDatabase();
            String query = "SELECT * FROM " + EntryContract.ExamsEntry.TABLE_NAME;
            Cursor cursor = db.rawQuery(query, null);
            if (cursor.moveToFirst()) {
                do {
                    exams.add(new Exam(Integer.parseInt(cursor.getString(0)),
                            cursor.getString(1),
                            cursor.getString(2),
                            cursor.getString(3)));
                }
                while (cursor.moveToNext());
                cursor.close();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return exams;
    }

    public List<Subject> getSubjectsByExam(int examId) {
        List<Subject> subjects = new ArrayList<>();
        try {
            SQLiteDatabase db = getReadableDatabase();
            String query = "SELECT DISTINCT se." + EntryContract._ID + ", se." + EntryContract.SubjectsEntry.COLUMN_NAME + ", se." + EntryContract.SubjectsEntry.COLUMN_DESC +
                    " FROM " + EntryContract.SubjectsEntry.TABLE_NAME + " AS se INNER JOIN " + EntryContract.WordsToExamEntry.TABLE_NAME
                    + " AS wte WHERE se." + EntryContract._ID + "= wte." + EntryContract.WordsToExamEntry.COLUMN_SUBJECT
                    + " AND wte." + EntryContract.WordsToExamEntry.COLUMN_EXAM_ID + "=" + examId;
            Cursor cursor = db.rawQuery(query, null);
            if (cursor.moveToFirst()) {
                do {
                    subjects.add(new Subject(Integer.parseInt(cursor.getString(0)),
                            cursor.getString(1),
                            cursor.getString(2)));
                } while (cursor.moveToNext());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return subjects;
    }
}

以下是声明:

public final class EntryContract {
    public EntryContract() {
    }

    public static final String _ID = "_id";

    public static abstract class ExamsEntry implements BaseColumns {

        public static final String TABLE_NAME = "exam_details";
        public static final String COLUMN_TITLE = "exam_title";
        public static final String COLUMN_SHORT_TITLE = "short_title";
        public static final String COLUMN_DESC = "desc";

        public static final String CREATE_STATEMENT =
                "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (\"" + _ID + "\" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , \""
                        + COLUMN_TITLE + "\" TEXT NOT NULL  UNIQUE," +
                        " \"" + COLUMN_SHORT_TITLE + "\" TEXT NOT NULL  UNIQUE, \"" + COLUMN_DESC + "\" TEXT); ";

        public static final String POPULATE_STATEMENT = "INSERT INTO " + TABLE_NAME + " VALUES" +
                "(0,'TOEFL','toefl','Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta feugiat magna, non venenatis orci blandit ac. Proin non condimentum lectus. Morbi ultricies urna sit amet nunc consectetur dignissim. Sed accumsan, dolor non vulputate vestibulum, risus augue viverra justo, vitae feugiat mauris elit quis felis. Nunc tristique et erat at fringilla. Pellentesque pulvinar odio vel nisl ultricies consequat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vehicula urna id quam convallis, vitae egestas odio vehicula. Nam rhoncus diam ipsum.')," +
                "(1,'YDS','yds','Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta feugiat magna, non venenatis orci blandit ac. Proin non condimentum lectus. Morbi ultricies urna sit amet nunc consectetur dignissim. Sed accumsan, dolor non vulputate vestibulum, risus augue viverra justo, vitae feugiat mauris elit quis felis. Nunc tristique et erat at fringilla. Pellentesque pulvinar odio vel nisl ultricies consequat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vehicula urna id quam convallis, vitae egestas odio vehicula. Nam rhoncus diam ipsum.')," +
                "(2,'GRE','gre','Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta feugiat magna, non venenatis orci blandit ac. Proin non condimentum lectus. Morbi ultricies urna sit amet nunc consectetur dignissim. Sed accumsan, dolor non vulputate vestibulum, risus augue viverra justo, vitae feugiat mauris elit quis felis. Nunc tristique et erat at fringilla. Pellentesque pulvinar odio vel nisl ultricies consequat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vehicula urna id quam convallis, vitae egestas odio vehicula. Nam rhoncus diam ipsum. ')," +
                "(3,'Kids','kids','Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta feugiat magna, non venenatis orci blandit ac. Proin non condimentum lectus. Morbi ultricies urna sit amet nunc consectetur dignissim. Sed accumsan, dolor non vulputate vestibulum, risus augue viverra justo, vitae feugiat mauris elit quis felis. Nunc tristique et erat at fringilla. Pellentesque pulvinar odio vel nisl ultricies consequat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vehicula urna id quam convallis, vitae egestas odio vehicula. Nam rhoncus diam ipsum. ')," +
                "(4,'Benim Kelimelerim','benim-kelimelerim','Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta feugiat magna, non venenatis orci blandit ac. Proin non condimentum lectus. Morbi ultricies urna sit amet nunc consectetur dignissim. Sed accumsan, dolor non vulputate vestibulum, risus augue viverra justo, vitae feugiat mauris elit quis felis. Nunc tristique et erat at fringilla. Pellentesque pulvinar odio vel nisl ultricies consequat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vehicula urna id quam convallis, vitae egestas odio vehicula. Nam rhoncus diam ipsum. ');";
    }

    public static abstract class SubjectsEntry implements BaseColumns {
        public static final String TABLE_NAME = "subject_details";
        public static final String COLUMN_NAME = "subject_name";
        public static final String COLUMN_DESC = "desc";

        public static final String CREATE_STATEMENT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (\"" + _ID + "\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , \""
                + COLUMN_NAME + "\" TEXT NOT NULL UNIQUE,"
                + " \"" + COLUMN_DESC + "\" TEXT); ";

        public static final String POPULATE_STATEMENT = "INSERT INTO " + TABLE_NAME + " VALUES" +
                "(0,'Sıfatlar','Sıfatları içerir')," +
                "(1,'Zarflar','Zarfları içerir')," +
                "(2,'Bağlaçlar','Bağlaçları içerir')," +
                "(3,'İsimler','İsimleri içerir');" +
                "(4,'Phrasel Verbs','Phrasel Verbs içerir');";

    }

    public static abstract class WordsEntry implements BaseColumns {
        public static final String TABLE_NAME = "words";
        public static final String COLUMN_EN = "word_en";
        public static final String COLUMN_TR = "word_tr";
        public static final String COLUMN_EN_DESC = "en_desc";
        public static final String COLUMN_TR_DESC = "tr_desc";
        public static final String COLUMN_FAV = "is_favorited";

        public static final String CREATE_STATEMENT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (\"" + _ID + "\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , \""
                + COLUMN_EN + "\" TEXT NOT NULL UNIQUE, \""
                + COLUMN_TR + "\" TEXT NOT NULL, \""
                + COLUMN_EN_DESC + "\" TEXT NOT NULL, \""
                + COLUMN_TR_DESC + "\" TEXT NOT NULL, \""
                + COLUMN_FAV + "\" INTEGER NOT NULL);";

        public static final String POPULATE_STATEMENT = "INSERT INTO " + TABLE_NAME + " VALUES" +
                "(0,'And','Ve', 'And','Ve bağlacı','0');";
    }

    public static abstract class WordsToExamEntry implements BaseColumns {
        public static final String TABLE_NAME = "words_to_subject";
        public static final String COLUMN_EXAM_ID = "exam_id";
        public static final String COLUMN_WORD_ID = "word_id";
        public static final String COLUMN_DIFFICULTY = "dif_level";
        public static final String COLUMN_SUBJECT = "subject_id";

        public static final String CREATE_STATEMENT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (\"" + _ID + "\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , \""
                + COLUMN_EXAM_ID + "\" INTEGER NOT NULL, \""
                + COLUMN_WORD_ID + "\" INTEGER NOT NULL, \""
                + COLUMN_DIFFICULTY + "\" INTEGER NOT NULL, \""
                + COLUMN_SUBJECT + "\" INTEGER NOT NULL);";

        public static final String POPULATE_STATEMENT = "INSERT INTO " + TABLE_NAME + " VALUES" +
                "(0,0,0,1,2);";

    }
}

答案 1 :(得分:0)

在您的活动中添加此内容

  class updateMed extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage(getString(R.string.connexEnCours));
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    protected String doInBackground(String... args) {



        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("param1","value1"));
        params.add(new BasicNameValuePair("param2","value2"));
        json = jsonParser.makeHttpRequest(your url,
                "POST", params);


        try {
            System.out.println(String.valueOf(json));
            if(json != null && !json.isNull("success")){
            int success = json.getInt("success");

            if (success == 1) {
                if (json.getString("type").equals("update")) {
                    JSONArray ja = json.getJSONArray("med");
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject c = ja.getJSONObject(i);
                        Integer Cle = c.getInt("Cle");
                        String Nom = c.getString("Nom");
                        String Prenom = c.getString("Prenom");
                        String Adresse = c.getString("Adresse");
                        String Numero = c.getString("Numero");
                        String Lat = c.getString("Lat");
                        String Lng = c.getString("Lng");
                        String Specialite = c.getString("Specialite");
                        Specialite = avoirSpe(Specialite);
                        String Email = c.getString("Email");
                        db.ajouterMed(Cle, Nom, Prenom, Adresse, Numero, Lat, Lng, Specialite, Email);
                        //inserting values in database
                    }

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

        return null;

    }

    protected void onPostExecute(String file_url) {
        pDialog.dismiss();

    }
}

像这样称呼它

new updateMed().execute();

php页面

    <?php
include('connect.php');
$response = array(); 

if (isset($_POST['param1']) && isset($_POST['param2']) ){ 
 $Cle=$_POST['Param1']; // ... add here your params and there values

if ($result = $db->query("SELECT * FROM `med` where `Cle`>'$Cle'")) {


if (mysqli_num_rows($result) > 0) { 
    $response["med"] = array();

    while ($row = mysqli_fetch_array($result)) {
        // temp user array
        $med = array();
        $med["Cle"] = intval($row["Cle"]);
        $med["Nom"] = $row["Nom"];
        $med["Prenom"] = $row["Prenom"];
        $med["Adresse"] = $row["Adresse"];
        $med["Numero"] = $row["Numero"];
        $med["Lat"] = $row["Lat"];
        $med["Lng"] = $row["Lng"];
        $med["Specialite"] = $row["Specialite"];
        $med["Email"] = $row["Email"]; 
        // push single record into final response array

        array_push($response["med"], $med);
    }
    // success
    $response["success"] = 1; 
    $response["message"] ="Mise à jour telechargée"; 
    $response["type"] ="update";  

    // echoing JSON response
    echo json_encode($response);
} else {
    // no record found
    $response["success"] = 0;
    $response["message"] = "La BD est à jour";
    $response["type"] ="update";  
    // echo no record JSON
    echo json_encode($response);
}
}}else{
    $response["success"] = 0;
    $response["message"] = "Erreur cle manquée";
    echo json_encode($response);
}
?>

这是我在数据库中插入的功能

 public void ajouterMed(Integer Cle,String Nom,String Prenom,String Adresse,String Numero,String Lat,String Lng,String Specialite,String Email) {
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = lireMedecin();
    if (c.getCount() == 0) {
        db.execSQL("Insert Into Med values('" + 0 + "','" + Nom + "','" + Prenom + "','" + Adresse + "','" + Numero + "','" + Lat + "','" + Lng + "','" + Specialite + "','" + Email + "','" + Cle + "');");
    } else {
        c.moveToLast();
        Integer i = Integer.parseInt(c.getString(0));
        String s = Integer.toString(i + 1);
        db.execSQL("Insert Into Med values('" + s + "','" + Nom + "','" + Prenom + "','" + Adresse + "','" + Numero + "','" + Lat + "','" + Lng + "','" + Specialite + "','" + Email + "','" + Cle + "');");
    }
}