2014-04-15 3 views
0

SQLite 데이터베이스를 sdcard로 내보낼 수있게되었습니다. 누군가가 Sqlite 데이터베이스를 장치로 가져 오는 데 도움이된다면 감사하겠습니다.프로그래밍 방식으로 장치에 Sqlite 데이터베이스 가져 오기

나는 newbi in android 나는 성공적으로 많이 시도했다.

수정 ... 사전에

public class MainActivity extends Activity implements OnClickListener { 

private static final String SAMPLE_DB_NAME = "TrekBook"; 
private static final String SAMPLE_TABLE_NAME = "Info"; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    findViewById(R.id.button1).setOnClickListener(this); 
    findViewById(R.id.button2).setOnClickListener(this); 
    findViewById(R.id.button3).setOnClickListener(this); 
    findViewById(R.id.button4).setOnClickListener(this); 

} 
@Override 
public void onClick(View v) { 
    switch(v.getId()) { 
    case R.id.button1: 
     deleteDB(); 
     break; 
    case R.id.button2: 
     exportDB(); 
     break; 
    case R.id.button3: 
     createDB(); 
     break; 
    case R.id.button4: 
     importDB(); 
     break; 
    } 
} 

private void deleteDB(){ 
    boolean result = this.deleteDatabase(SAMPLE_DB_NAME); 
    if (result==true) { 
     Toast.makeText(this, "DB Deleted!", Toast.LENGTH_LONG).show(); 
    } 
} 

private void exportDB(){ 
    File sd = Environment.getExternalStorageDirectory(); 
    File data = Environment.getDataDirectory(); 
    FileChannel source=null; 
    FileChannel destination=null; 
    String currentDBPath = "/data/"+ "com.authorwjf.sqliteexport" +"/databases/"+SAMPLE_DB_NAME; 
    String backupDBPath = SAMPLE_DB_NAME; 
    File currentDB = new File(data, currentDBPath); 
    File backupDB = new File(sd, backupDBPath); 
    try { 
     source = new FileInputStream(currentDB).getChannel(); 
     destination = new FileOutputStream(backupDB).getChannel(); 
     destination.transferFrom(source, 0, source.size()); 
     source.close(); 
     destination.close(); 
     Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show(); 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } 
} 

private void createDB() { 
    SQLiteDatabase sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null); 
    sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + 
      SAMPLE_TABLE_NAME + 
      " (LastName VARCHAR, FirstName VARCHAR," + 
      " Rank VARCHAR);"); 
    sampleDB.execSQL("INSERT INTO " + 
      SAMPLE_TABLE_NAME + 
      " Values ('Kirk','James, T','Captain');"); 
    sampleDB.close(); 
    sampleDB.getPath(); 
    Toast.makeText(this, "DB Created @ "+sampleDB.getPath(), Toast.LENGTH_LONG).show(); 
} 

private void importDB(){ 
    File f=new File("/data/data/com.authorwjf.sqliteexport/databases/TrekBook"); 
    FileInputStream fis=null; 
    FileOutputStream fos=null; 

    try 
    { 
     fis=new FileInputStream(f); 
     fos=new FileOutputStream("/mnt/sdcard/DB/TrekBook"); 
     while(true) 
     { 
     int i=fis.read(); 
     if(i!=-1) 
     {fos.write(i);} 
     else 
     {break;} 
     } 
     fos.flush(); 
     Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
     Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show(); 
    } 
    finally 
    { 
     try 
     { 
     fos.close(); 
     fis.close(); 
     } 
     catch(Exception ioe) 
     {} 
    } 
} 

} 

activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_gravity="center" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="SQLite DB to SD Demo"/> 

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Delete" /> 
<Button 
    android:id="@+id/button2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Export" /> 
<Button 
    android:id="@+id/button3" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Create" /> 
<Button 
    android:id="@+id/button4" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Import" /> 

</LinearLayout> 

감사합니다 ....

답변

0

이 방법을 시도해보십시오

File f=new File("/data/data/com.example.sql/databases/DBNAME"); 
        FileInputStream fis=null; 
        FileOutputStream fos=null; 

        try 
        { 
         fis=new FileInputStream(f); 
         fos=new FileOutputStream("/mnt/sdcard/DB/database"); 
         while(true) 
         { 
         int i=fis.read(); 
         if(i!=-1) 
         {fos.write(i);} 
         else 
         {break;} 
         } 
         fos.flush(); 
         Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show(); 
        } 
        catch(Exception e) 
        { 
         e.printStackTrace(); 
         Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show(); 
        } 
        finally 
        { 
         try 
         { 
         fos.close(); 
         fis.close(); 
         } 
         catch(Exception ioe) 
         {} 
        } 

장치로 manifest.xml에

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+0

덕분에 간단한 계획을 도와, 미안, 그것은 말한다 .. 나 지금 시도 DB 덤프를 – user1710911

+0

하자 ... 멀리 내 컴퓨터에서이었다 오류 – user1710911

+0

왜 ?? 당신은 신중하게 그것을 교차 확인 PATH을 변경합니다. –

0

가져 오기 SQLite 데이터베이스를 권한을 추가하는 것을 잊지 마세요 -

try { 
      backupDatabase(); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 


public static void backupDatabase() throws IOException { 
     //Open your local db as the input stream 
     String inFileName = "/data/data/com.myapp.main/databases/Content"; 
     File dbFile = new File(inFileName); 
     FileInputStream fis = new FileInputStream(dbFile); 

     String outFileName = Environment.getExternalStorageDirectory()+"/Content"; 
     //Open the empty db as the output stream 
     OutputStream output = new FileOutputStream(outFileName); 
     //transfer bytes from the inputfile to the outputfile 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = fis.read(buffer))>0){ 
      output.write(buffer, 0, length); 
     } 
     //Close the streams 
     output.flush(); 
     output.close(); 
     fis.close(); 
    } 

확인하려면 이 데이터베이스는 콘솔의 응용 프로그램 경로에서 명령을 제공해야합니다. 같은 -

adb pull mnt/sdcard/Content 

,

내용은 위의 inFileName로 제공하는 것이다.

Offcourse Offscourse는 응용 프로그램과 내 보낸 위치, 장치에서 가져올 위치를 적절히 변경해야합니다 (inFileNameoutFileName).

+0

Ved Prakash, 죄송합니다. 내 컴퓨터에서 멀리 떨어져있었습니다. 나는 당신의 코드를 테스트하지 않았습니다. secressful – user1710911

0

기기가 루팅 된 경우이 악의적 인 방법으로 시도해보세요. 그렇지 않으면 당신은 SD 카드에 휴대 전화에서 DB를 당길 수 없습니다

public void copyDbToSdcard() 
{ 
    try 
    { 
     String comando = "cp -r /data/data/com.package.name/Databases/DB_File.db /sdcard/Your_Custom_Folder/"; 
     Process suProcess = Runtime.getRuntime().exec("su"); 
     DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); 
     os.writeBytes(comando + "\n"); 
     os.flush(); 
     os.writeBytes("exit\n"); 
     os.flush(); 
     try 
     { 
      int suProcessRetval = suProcess.waitFor(); 
      if(255 != suProcessRetval) 
      { 
       Log.e("SU", "If Part"); 
      } 
      else 
      { 
       Log.e("SU", "Else Part"); 
      } 
     } 
     catch (Exception ex) 
     { 
      Log.e("ERROR-->", ex.toString()); 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

즐겨보세요 :)

+0

감사의 말 노미, 나는 이미 exportDb를 완료했다. importDB가 필요하다. – user1710911

관련 문제