2015-04-21 1 views
0

Итак, мое приложение, по сути, представляет собой приложение для поиска рецептов. У меня есть база данных, в которой хранятся все рецепты. Но сначала мне нужно большое количество рецептов, чтобы показать все функции. Итак, можно ли вытащить рецепты с веб-сайта и как-то вставить их в мою базу данных?Возможно ли получить данные с веб-сайта для заполнения базы данных?

+0

Вы можете попробовать [Jsoup] (HTTP: // jsoup .org /) для извлечения данных с веб-сайта или использования [API] (https://www.google.ie/search?q=recipe+database+api) или где-то найти загружаемую текстовую базу данных. – JonasCz

ответ

4

Возможно. Вы можете получить данные с помощью веб-службы и вставить в свою базу данных sqlite, которую использует ваше приложение. Вот пример Sqlite Db. Вот пример игровой игры с реляционной 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; 
    } 
} 

И here're statments:

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);"; 

    } 
} 
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 + "');"); 
    } 
} 
Смежные вопросы