2013-06-14 7 views
0

데이터를 저장하기 위해 sqlite를 사용하여 미리 정의 된 질문과 답변을 저장해야하는 Android 애플리케이션을 만들어야합니다. 우리가 응용 프로그램을 실행할 때마다 값이 삽입되는 자습서를 찾았지만 이러한 질문과 대답을 프로그램에 삽입하여 데이터베이스를 만들어야합니다. 누군가가 테이블에 값을 삽입하는 방법을 설명하는 자습서를 제안 할 수 있습니까?sqlite에 기록 할 데이터 삽입

+0

알려주세요 그럼 혼란을 부탁합니다 – user2326414

답변

1

우선 sqlite 브라우저를 다운로드하고 이상적으로 자산 폴더에 있어야하는 .db 파일을 열고 각 테이블의 모든 레코드를 수동 또는 쿼리로 삽입하십시오.

그런 다음 db 파일을 저장하고 해당 파일을 프로젝트의 assets 폴더에 복사하십시오.

그런 다음 databasehelper 클래스를 만들고 SQLiteOpenHelper를 확장하고 데이터베이스 및 모든 함수를 정의하여 거기에 데이터를 가져옵니다.

이 더 의심 :)

download sqlite browser

이있는 경우 내가 내 자신을 명확하게 수없는 경우 나 DatabaseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper { 

// The Android's default system path of your application database. 
private static String DB_PATH = "/data/data/com.example.tutionimage/databases/"; 
private static String DB_NAME = "master_subject.db"; 
private SQLiteDatabase myDatabase; 
private final Context myContext; 
private boolean add2; 

/** 
* Constructor Takes and keeps a reference of the passed context in order to 
* access to the application assets and resources. 
* 
* @param context 
*/ 
public DataBaseHelper(Context context) { 
    super(context, DB_NAME, null, 1); 
    this.myContext = context; 
} 

/** 
* Creates a empty database on the system and rewrites it with your own 
* database. 
* */ 
public void createDataBase() throws IOException { 
    boolean dbExist = checkDataBase(); 
    if (dbExist) { 
     // do nothing - database already exist 
    } else { 

     // By calling this method and empty database will be created into 
     // the default system path 
     // of your application so we are gonna be able to overwrite that 
     // database with our database. 
     this.getReadableDatabase(); 
     try { 
      copyDataBase(); 
     } catch (IOException e) { 
      throw new Error("Error copying database"); 
     } 
    } 
} 

/** 
* Check if the database already exist to avoid re-copying the file each 
* time you open the application. 
* 
* @return true if it exists, false if it doesn't 
*/ 
private boolean checkDataBase() { 
    SQLiteDatabase checkDB = null; 
    try { 
     String myPath = DB_PATH + DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READONLY); 
    } catch (SQLiteException e) { 
     // database does't exist yet. 
    } 
    if (checkDB != null) { 
     checkDB.close(); 
    } 
    return checkDB != null ? true : false; 
} 

/** 
* Copies your database from your local assets-folder to the just created 
* empty database in the system folder, from where it can be accessed and 
* handled. This is done by transfering bytestream. 
* */ 
private void copyDataBase() throws IOException { 
    // Open your local db as the input stream 
    InputStream myInput = myContext.getAssets().open(DB_NAME); 
    // Path to the just created empty db 
    String outFileName = DB_PATH + DB_NAME; 
    // Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 
    // transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer)) > 0) { 
     myOutput.write(buffer, 0, length); 
    } 
    // Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

    // Toast.makeText(myContext, "Copy Done", 300).show(); 
} 

public void openDataBase() throws SQLException { 
    // Open the database 
    String myPath = DB_PATH + DB_NAME; 
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, 
      SQLiteDatabase.OPEN_READWRITE); 

} 

@Override 
public synchronized void close() { 
    if (myDatabase != null) 
     myDatabase.close(); 
    super.close(); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 

} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // Add your public helper methods to access and get content from the 
    // database. 
    // You could return cursors by doing "return myDatabase.query(....)" so 
    // it'd be easy 
    // to you to create adapters for your views. 
} 

//Insert Title into database 
public long insertTitle(String sem, String subject,String jee, String chp, String marks, String time) { 

    ContentValues initialValues = new ContentValues(); 

    initialValues.put("sem", sem); 
    initialValues.put("subject", subject); 
    initialValues.put("jee_flag", jee); 
    initialValues.put("chapter", chp); 
    initialValues.put("marks", marks); 
    initialValues.put("time", time); 

    return myDatabase.insert("testdata", null, initialValues); 
} 

//Fetching data from the database 
public Cursor getTestData() throws SQLException{ 

    Cursor cursor = null; 
    String queryString = ""; 


     if(NewStartPanel.queryString.split("-")[2].equalsIgnoreCase("n")){ 

      queryString = "select * from testdata where jee_flag='n' order by id desc"; 

     } 

     else if(NewStartPanel.queryString.split("-")[2].equalsIgnoreCase("y")){ 

      queryString = "select * from testdata where jee_flag='y' order by id desc"; 
     } 

     System.out.println("Query String:................ "+queryString); 
     cursor = myDatabase.rawQuery(queryString, null); 

    // cursor.moveToFirst(); 

     System.out.println("cursor count of testdata is:"+cursor.getCount()); 


    return cursor; 

} 

TestOrReport.java

public class TestOrReport extends Activity implements OnClickListener { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.test_or_report); 

    // set resources 

    //Interacting with database 

    DataBaseHelper dataBaseHelper =new DataBaseHelper(this); 
    System.out.println("Before open db"); 
    dataBaseHelper.openDataBase(); 

    System.out.println("After open db"); 
    Cursor mCursor = dataBaseHelper.getTestData(); 

    System.out.println("@@ total rows :"+mCursor.getCount()); 


    // Then you can iterate through cursor and get those data in arraylist or whatever collection you want to 
    } 

    } 
+0

나는 데이터베이스를 만들지 만 h는 모른다. 아쉽게 내 안드로이드 응용 프로그램과 함께 사용하면 튜토리얼을 제안 해줍니다. – user2326414

+0

내 수정 된 답변보기 – nidhi

2

질문과 대답을 sqlite 데이터베이스에 미리로드하려는 것으로 알고 있습니다. 다음 튜토리얼은

Using your own SQLite database in Android applications

은 또한 동일한에 대한 github에서 많은 프로젝트를 찾을 수 ... sqlite 데이터베이스를 미리로드와 함께 당신을 도울 것입니다. 하나는 Android Survey App입니다.

희망이 도움이됩니다.