Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将.csv文件导入Android中的Sqlite_Android_Database_Sqlite_Csv_Import - Fatal编程技术网

将.csv文件导入Android中的Sqlite

将.csv文件导入Android中的Sqlite,android,database,sqlite,csv,import,Android,Database,Sqlite,Csv,Import,我有一个.csv文件,我想将该文件导入android中的数据库 例如,.csv文件: | id | name | dt1 | dt2 | dt3 | | 1 | Paul | 21 | 98 | 91 | | 2 | John | 22 | 44 | 11 | | 3 | George| 21 | 31 | 22 | | 4 | Ringo | 20 | 10 | 15 | 对于这样的事情: Cursor cursor = getWritableDat

我有一个.csv文件,我想将该文件导入android中的数据库

例如,.csv文件:

| id | name  | dt1 | dt2 | dt3 | 
| 1  | Paul  | 21  | 98  | 91  |
| 2  | John  | 22  | 44  | 11  |
| 3  | George| 21  | 31  | 22  |
| 4  | Ringo | 20  | 10  | 15  | 
对于这样的事情:

Cursor cursor = getWritableDatabase().
rawQuery("Insert into table1(_id, name, dt1, dt2, dt3)
values ( 1, Paul, 21, 98, 91)
values ( 2, John, 22, 44, 11)
values ( 3, George, 21,31,22)
values ( 4, Ringo, 20, 10,15);");
那么,我该怎么做呢

试试下面的代码

FileReader file = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(file);
String line = "";
String tableName ="TABLE_NAME";
String columns = "_id, name, dt1, dt2, dt3";
String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
String str2 = ");";

db.beginTransaction();
while ((line = buffer.readLine()) != null) {
    StringBuilder sb = new StringBuilder(str1);
    String[] str = line.split(",");
    sb.append("'" + str[0] + "',");
    sb.append(str[1] + "',");
    sb.append(str[2] + "',");
    sb.append(str[3] + "'");
    sb.append(str[4] + "'");
    sb.append(str2);
    db.execSQL(sb.toString());
}
db.setTransactionSuccessful();
db.endTransaction();

我建议使用ContentValues插入记录。它更容易,将转义引号,并且不太冗长

这样,(它也会跳过错误的行):

dbCol0等是数据库的列名,例如
\u id、name、dt1、dt2、dt3

db是您从中获取的数据库 公共SQLiteDatabase getReadableDatabase()位于

如何读取CSV文件 将file.csv复制到assets文件夹中,并按如下方式读取:

String mCSVfile = "file.csv";
AssetManager manager = context.getAssets();
InputStream inStream = null;
try {
     inStream = manager.open(mCSVfile);
    } catch (IOException e) {
     e.printStackTrace();
    }

 BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
...

我使用这些类添加了一些类,您可以轻松导入和导出文件或db

对于这些操作,您必须将这两个jar文件导入到您的项目中

(1)opencsv-1.7.jar
(2)poi-3.8-20120326.jar 然后导入所有这四个类,并根据需要使用…

ExportFileModule`

public class ExportDatabaseToCSV extends AsyncTask<Void, Boolean, Boolean>{

Context context;
ProgressDialog dialog;
public ExportDatabaseToCSV(Context context)
{
    this.context=context;   
}

@Override
protected void onPreExecute() {
    dialog=new ProgressDialog(context);
    dialog.setTitle("Exporting SecureIt Data to CSV file");
    dialog.setMessage("Please wait...");
    dialog.setCancelable(false);
    dialog.setIcon(android.R.drawable.ic_dialog_info);
    dialog.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    CredentialDb db = new CredentialDb(context);//here CredentialDb is my database. you can create your db object.
       File exportDir = new File(Environment.getExternalStorageDirectory(), "");        

       if (!exportDir.exists()) 
          {
              exportDir.mkdirs();
          }

      File file = new File(exportDir, "SecureItExportedFile.csv");

      try 
      {
          file.createNewFile();                
          CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
          SQLiteDatabase sql_db = db.getReadableDatabase();//returning sql
          Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
          csvWrite.writeNext(curCSV.getColumnNames());

          while(curCSV.moveToNext())
              {
                 //Which column you want to export you can add over here...
                  String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2),curCSV.getString(3),curCSV.getString(4),curCSV.getString(5)};
                  csvWrite.writeNext(arrStr);
              }

          csvWrite.close();
          curCSV.close();
          return true;
      }
      catch(Exception sqlEx)
      {
          Log.e("Error:", sqlEx.getMessage(), sqlEx);
      }
      return false;
}   

@Override
protected void onPostExecute(Boolean result) {
    if (dialog.isShowing())
    {
        dialog.dismiss();
    }

    if(result)
        Toast.makeText(context, "SqLite Data has been Exported!", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context, "SqLite Data has not Exported", Toast.LENGTH_LONG).show();  
}
}


导入java.io.File;
导入java.io.FilenameFilter;
导入java.util.ArrayList;
导入java.util.List;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.Dialog;
导入android.content.DialogInterface;
导入android.content.DialogInterface.OnClickListener;
导入android.os.Environment;
导入android.util.Log;
导入com.export.importmodule.ListenerList.FireHandler;
公共类文件对话框{
私有静态最终字符串PARENT_DIR=“…”;
私有最终字符串标记=getClass().getName();
私有字符串[]文件列表;
私有文件路径;
公共接口文件SelectedListener{
选择的无效文件(文件);
}
公共接口目录SelectedListener{
已选择无效目录(文件目录);
}
私有ListenerList fileListenerList=新建ListenerList();
私有ListenerList dirListenerList=新建ListenerList();
私人最终活动;
私有布尔selectDirectoryOption;
私有字符串fileEndsWith;
/**
*@param活动
*@param initialPath
*/
公共文件对话框(活动、文件路径){
这个。活动=活动;
如果(!path.exists())path=Environment.getExternalStorageDirectory();
加载文件列表(路径);
}
/**
*@返回文件对话框
*/
公共对话框createFileDialog(){
Dialog=null;
AlertDialog.Builder=新建AlertDialog.Builder(活动);
setTitle(currentPath.getPath());
如果(选择目录选项){
setPositiveButton(“选择目录”,新建OnClickListener()){
public void onClick(DialogInterface dialog,int which){
Log.d(标记,currentPath.getPath());
fireDirectorySelectedEvent(当前路径);
}
});
}
setItems(文件列表,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
字符串fileselected=fileList[which];
File chosenFile=getChosenFile(fileselected);
if(chosenFile.isDirectory()){
loadFileList(chosenFile);
dialog.cancel();
dialog.dismise();
showDialog();
}else fireFileSelectedEvent(chosenFile);
}
});
dialog=builder.show();
返回对话框;
}
public void addFileListener(FileSelectedListener侦听器){
添加(监听器);
}
public void removeFileListener(FileSelectedListener侦听器){
fileListenerList.remove(侦听器);
}
public void setSelectDirectoryOption(布尔selectDirectoryOption){
this.selectDirectoryOption=selectDirectoryOption;
}
public void addDirectoryListener(DirectorySelectedListener侦听器){
添加(监听器);
}
public void removedDirectoryListener(DirectorySelectedListener侦听器){
删除(监听器);
}
/**
*显示文件对话框
*/
公共对话框(){
createFileDialog().show();
}
私有void fireFileSelectedEvent(最终文件){
fireEvent(新的FireHandler(){
public void fireEvent(FileSelectedListener侦听器){
fileSelected(文件);
}
});
}
私有void fireDirectorySelectedEvent(最终文件目录){
fireEvent(新的FireHandler()){
public void fireEvent(DirectorySelectedListener侦听器){
listener.directorySelected(目录);
}
});
}
私有void加载文件列表(文件路径){
this.currentPath=path;
列表r=新的ArrayList();
if(path.exists()){
if(path.getParentFile()!=null)r.add(PARENT_DIR);
FilenameFilter筛选器=新建FilenameFilter(){
公共布尔接受(文件目录,字符串文件名){
文件选择=新文件(目录,文件名);
如果(!sel.canRead())返回false;
如果(selectDirectoryOption)返回sel.isDirectory();
否则{
布尔值endsWith=fileEndsWith!=null?filename.toLowerCase().endsWith(fileEndsWith):true;
返回endsWith | | sel.isDirectory();
}
}
};
字符串[]fileList1=path.list(过滤器);
for(字符串文件:fileList1){
r、 添加(文件);
}
}
fileList=(字符串[])r.toArray(新字符串[]{});
}
私有文件getChosenFile(选择字符串文件){
if(fileselected.equals(PARENT_DIR))返回currentPath.getParentFile();
否则返回新文件(currentPath,FileSelected);
}
//--------------------------------------------------------------
公共void setFileEndsWith(字符串fileEndsWith){
this.fileEndsWith=fileEndsWith!=null?fileEndsWith.toLowerCase():fileEndsWith;
}
}
类侦听器列表{
私有列表listenerList=新的ArrayList();
公共接口FireHandler{
美国之音
public class ExportDatabaseToCSV extends AsyncTask<Void, Boolean, Boolean>{

Context context;
ProgressDialog dialog;
public ExportDatabaseToCSV(Context context)
{
    this.context=context;   
}

@Override
protected void onPreExecute() {
    dialog=new ProgressDialog(context);
    dialog.setTitle("Exporting SecureIt Data to CSV file");
    dialog.setMessage("Please wait...");
    dialog.setCancelable(false);
    dialog.setIcon(android.R.drawable.ic_dialog_info);
    dialog.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    CredentialDb db = new CredentialDb(context);//here CredentialDb is my database. you can create your db object.
       File exportDir = new File(Environment.getExternalStorageDirectory(), "");        

       if (!exportDir.exists()) 
          {
              exportDir.mkdirs();
          }

      File file = new File(exportDir, "SecureItExportedFile.csv");

      try 
      {
          file.createNewFile();                
          CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
          SQLiteDatabase sql_db = db.getReadableDatabase();//returning sql
          Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
          csvWrite.writeNext(curCSV.getColumnNames());

          while(curCSV.moveToNext())
              {
                 //Which column you want to export you can add over here...
                  String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2),curCSV.getString(3),curCSV.getString(4),curCSV.getString(5)};
                  csvWrite.writeNext(arrStr);
              }

          csvWrite.close();
          curCSV.close();
          return true;
      }
      catch(Exception sqlEx)
      {
          Log.e("Error:", sqlEx.getMessage(), sqlEx);
      }
      return false;
}   

@Override
protected void onPostExecute(Boolean result) {
    if (dialog.isShowing())
    {
        dialog.dismiss();
    }

    if(result)
        Toast.makeText(context, "SqLite Data has been Exported!", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context, "SqLite Data has not Exported", Toast.LENGTH_LONG).show();  
}
}
import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;

public class MyCSVFileReader {

public static void openDialogToReadCSV(final Activity activity,final Context context)
{
    File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
    FileDialog fileDialog = new FileDialog(activity, mPath);
    fileDialog.setFileEndsWith(".txt");
    fileDialog.addFileListener(new FileDialog.FileSelectedListener() {

        @Override
        public void fileSelected(File file) {
            new ImportCVSToSQLiteDataBase(context,activity,file).execute(); //execute asyncTask to import data into database from selected file.            
        }
    });
    fileDialog.showDialog();
}

}
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Environment;
import android.util.Log;

import com.export.importmodule.ListenerList.FireHandler;

public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;

public interface FileSelectedListener {
    void fileSelected(File file);
}
public interface DirectorySelectedListener {
    void directorySelected(File directory);
}
private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
private final Activity activity;
private boolean selectDirectoryOption;
private String fileEndsWith;    

/**
 * @param activity 
 * @param initialPath
 */
public FileDialog(Activity activity, File path) {
    this.activity = activity;
    if (!path.exists()) path = Environment.getExternalStorageDirectory();
    loadFileList(path);
}

/**
 * @return file dialog
 */
public Dialog createFileDialog() {
    Dialog dialog = null;
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);

    builder.setTitle(currentPath.getPath());
    if (selectDirectoryOption) {
        builder.setPositiveButton("Select directory", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, currentPath.getPath());
                fireDirectorySelectedEvent(currentPath);
            }
        });
    }

    builder.setItems(fileList, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            String fileChosen = fileList[which];
            File chosenFile = getChosenFile(fileChosen);
            if (chosenFile.isDirectory()) {
                loadFileList(chosenFile);
                dialog.cancel();
                dialog.dismiss();
                showDialog();
            } else fireFileSelectedEvent(chosenFile);
        }
    });

    dialog = builder.show();
    return dialog;
}


public void addFileListener(FileSelectedListener listener) {
    fileListenerList.add(listener);
}

public void removeFileListener(FileSelectedListener listener) {
    fileListenerList.remove(listener);
}

public void setSelectDirectoryOption(boolean selectDirectoryOption) {
    this.selectDirectoryOption = selectDirectoryOption;
}

public void addDirectoryListener(DirectorySelectedListener listener) {
    dirListenerList.add(listener);
}

public void removeDirectoryListener(DirectorySelectedListener listener) {
    dirListenerList.remove(listener);
}

/**
 * Show file dialog
 */
public void showDialog() {
    createFileDialog().show();
}

private void fireFileSelectedEvent(final File file) {
    fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
        public void fireEvent(FileSelectedListener listener) {
            listener.fileSelected(file);
        }
    });
}

private void fireDirectorySelectedEvent(final File directory) {
    dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
        public void fireEvent(DirectorySelectedListener listener) {
            listener.directorySelected(directory);
        }
    });
}

private void loadFileList(File path) {
    this.currentPath = path;
    List<String> r = new ArrayList<String>();
    if (path.exists()) {
        if (path.getParentFile() != null) r.add(PARENT_DIR);
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                if (!sel.canRead()) return false;
                if (selectDirectoryOption) return sel.isDirectory();
                else {
                    boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                    return endsWith || sel.isDirectory();
                }
            }
        };
        String[] fileList1 = path.list(filter);
        for (String file : fileList1) {
            r.add(file);
        }
    }
    fileList = (String[]) r.toArray(new String[]{});
}

private File getChosenFile(String fileChosen) {
    if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
    else return new File(currentPath, fileChosen);


   }
//--------------------------------------------------------------
    public void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
        }
     }

class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();

public interface FireHandler<L> {
    void fireEvent(L listener);
}

public void add(L listener) {
    listenerList.add(listener);
}

public void fireEvent(FireHandler<L> fireHandler) {
    List<L> copy = new ArrayList<L>(listenerList);
    for (L l : copy) {
        fireHandler.fireEvent(l);
    }
}

public void remove(L listener) {
    listenerList.remove(listener);
}

public List<L> getListenerList() {
    return listenerList;
}
}
import java.io.File;
import java.io.FileReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import au.com.bytecode.opencsv.CSVReader;

public class ImportCVSToSQLiteDataBase extends AsyncTask<String, String, String> {

    Activity activity;
    Context context;
    File file=null;
    private ProgressDialog dialog;

    public ImportCVSToSQLiteDataBase(Context context, Activity activity,File file) {
        this.context=context;
        this.activity=activity;
        this.file=file;
    }

    @Override
    protected void onPreExecute()
    {
        dialog=new ProgressDialog(context);
        dialog.setTitle("Importing Data into SecureIt DataBase");
        dialog.setMessage("Please wait...");
        dialog.setCancelable(false);
        dialog.setIcon(android.R.drawable.ic_dialog_info);
        dialog.show();
    }

@Override
protected String doInBackground(String... params) {

            String data="";
            Log.d(getClass().getName(), file.toString());

           try{
                 CSVReader reader = new CSVReader(new FileReader(file));
                   String [] nextLine;

                  //here I am just displaying the CSV file contents, and you can store your file content into db from while loop...

                    while ((nextLine = reader.readNext()) != null) {

                        // nextLine[] is an array of values from the line

                        String accId=nextLine[0];
                        String acc_name=nextLine[1];

                        data=data+"AccId:"+accId  +"  Account_name:"+acc_name+"\n";

                      }
                   return data;

            } catch (Exception e) {
                Log.e("Error", "Error for importing file");
            }
        return data="";

  }

protected void onPostExecute(String data)
  {

    if (dialog.isShowing())
    {
        dialog.dismiss();
    }

    if (data.length()!=0)
    {
        Toast.makeText(context, "File is built Successfully!"+"\n"+data, Toast.LENGTH_LONG).show();
    }else{
            Toast.makeText(context, "File fail to build", Toast.LENGTH_SHORT).show();
         }
   }


}
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />