繁体   English   中英

将SQLiteDatabase导出到CSV Android Studio

[英]Export SQLiteDatabase to CSV Android Studio

已经使用此代码几天了。 我没有Java方面的丰富经验,但是我可以将在网上找到的代码拼凑起来,并从中学到东西。 我一直将此网站用作当前活动的模板。 Android导出Sqlite数据库我对提供的代码进行了许多更改,但这是一个接一个的错误。 现在用我拥有的代码,我正在sqldb (第211行左右...) 无法解析symbol 我只是不认为我正确地声明了sqldb是我的总体问题。 您可能也会在网上其他地方注意到代码的其他部分。 只是尝试学习然后将代码更改为完成后需要的代码。 这是一些文件。 谢谢你的帮助! (如果您看到其他任何很棒的更改,因为我一直在使用Android Studio建议)。 不知道您需要查看哪些文件,但是这里有一些。 MyActivity是我的主要任务。 如果在MyActivity.java中选择了“ send ”,则应导出csv文件。

MyActivity.java

package com.nate.nash.howtoloveme;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;


public class MyActivity extends ListActivity implements AppCompatCallback {
private DBHelper dbHelper;


@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Closing Activity")
            .setMessage("Are you sure you want to close this activity?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }

            })
            .setNegativeButton("No", null)
            .show();
}
private AppCompatDelegate delegate;
TextView student_Id;

@Override
protected void onCreate(Bundle savedInstanceState) {

    // TODO remove comment code
    // TODO change wording from student to feeling
    // TODO change when list is removed or added, spinner changes
    // TODO start new activity after MainActivity.java

    //let's create the delegate, passing the activity at both arguments (Activity, AppCompatCallback)
    delegate = AppCompatDelegate.create(this, this);

    //we need to call the onCreate() of the AppCompatDelegate
    delegate.onCreate(savedInstanceState);

    //we use the delegate to inflate the layout
    delegate.setContentView(R.layout.activity_my);

    //TODO custom added

    //Finally, let's add the Toolbar
    Toolbar toolbar= (Toolbar) findViewById(R.id.my_awesome_toolbar);
    delegate.setSupportActionBar(toolbar);
    super.onCreate(savedInstanceState);

    StudentRepo repo = new StudentRepo(this);
    ArrayList<HashMap<String, String>> studentList = repo.getStudentList();
    if (studentList.size() != 0) {
        repo = new StudentRepo(this);

        studentList = repo.getStudentList();
        if(studentList.size()!=0) {
            ListView lv = getListView();
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                    student_Id = (TextView) view.findViewById(R.id.student_Id);
                    String studentId = student_Id.getText().toString();
                    Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);
                    objIndent.putExtra("student_Id", Integer.parseInt( studentId));
                    startActivity(objIndent);
                }
            });
            ListAdapter adapter = new SimpleAdapter( MyActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name});
            setListAdapter(adapter);
        }else{
            Toast.makeText(this, "No student!", Toast.LENGTH_SHORT).show();
        }

    } else {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_null);
        Button button = (Button) findViewById(R.id.angry_btn);
    }
    String versionName = "";
    try {
        versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    TextView versionname = (TextView) findViewById(R.id.versionName);

}

public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_my, menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {


    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent intent = new Intent(MyActivity.this, SettingsActivity.class);
        startActivity(intent);
        //finish();
        return true;
    }

    if (id == R.id.action_add) {
        Intent intent = new Intent(MyActivity.this, MainActivity.class);
        startActivity(intent);
        return true;
    }

    if (id == R.id.test) {
        Intent intent = new Intent(MyActivity.this, HelloGridView.class);
        startActivity(intent);
        return true;
    }

    if (id == R.id.send) {

        //main code begins here
        try {
            SQLiteDatabase sqldb = dbHelper.getReadableDatabase();
            Cursor c = null;
            c = sqldb.rawQuery("select * from crud.db", null);
            int rowcount = 0;
            int colcount = 0;
            File sdCardDir = Environment.getExternalStorageDirectory();
            String filename = "MyBackUp.csv";
            // the name of the file to export with
            File saveFile = new File(sdCardDir, filename);
            FileWriter fw = new FileWriter(saveFile);
            BufferedWriter bw = new BufferedWriter(fw);
            rowcount = c.getCount();
            colcount = c.getColumnCount();
            if (rowcount > 0) {
                c.moveToFirst();
                for (int i = 0; i < colcount; i++) {
                    if (i != colcount - 1) {
                        bw.write(c.getColumnName(i) + ",");
                    } else {
                        bw.write(c.getColumnName(i));
                    }
                }
                bw.newLine();
                for (int i = 0; i < rowcount; i++) {
                    c.moveToPosition(i);
                    for (int j = 0; j < colcount; j++) {
                        if (j != colcount - 1)
                            bw.write(c.getString(j) + ",");
                        else
                            bw.write(c.getString(j));
                    }
                    bw.newLine();
                }
                bw.flush();
                Toast.makeText(this, "Exported Successfully.", Toast.LENGTH_SHORT).show();
                //infotext.setText("Exported Successfully.");
            }
        } catch (Exception ex) {
            if (sqldb.isOpen()) {
                try {
                    sqldb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(this, ex.getMessage().toString(), Toast.LENGTH_SHORT).show();
                //infotext.setText(ex.getMessage().toString());
            }
        } finally {
        }



        return true;
    }

    if (id == R.id.array_add) {
        Intent intent = new Intent(MyActivity.this, ArraySave.class);
        startActivity(intent);
        return true;
    }

    if (id == R.id.action_quit) {
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Closing Activity")
                    .setMessage("Are you sure you want to close this activity?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }

                    })
                    .setNegativeButton("No", null)
                    .show();

    }

    switch(item.getItemId())
    {
        case R.id.preferences:
        {
            Intent intent = new Intent();
            intent.setClassName(this, "MyPreferenceActivity");
            startActivity(intent);
            return true;
        }
    }

    return super.onOptionsItemSelected(item);
}



public void ButtonOnClick(View v) {
    switch (v.getId() /*to get clicked view id**/) {
        case R.id.angry_btn:
            Intent intent = new Intent(MyActivity.this, MainActivity.class);
            startActivity(intent);
            break;
        default:
            break;
    }
}


@Override
public void onSupportActionModeStarted(ActionMode mode) {

}

@Override
public void onSupportActionModeFinished(ActionMode mode) {

}

@Nullable
@Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
    return null;
}
}

DBHelper.java

package com.nate.nash.howtoloveme;

/**
* Created by Nash on 1/13/2016.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper  extends SQLiteOpenHelper {
//version number to upgrade database version
//each time if you Add, Edit table, you need to change the
//version number.
private static final int DATABASE_VERSION = 4;

// Database Name
private static final String DATABASE_NAME = "crud.db";

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

@Override
public void onCreate(SQLiteDatabase db) {
    //All necessary tables you like to create will create here

    String CREATE_TABLE_STUDENT = "CREATE TABLE " + Student.TABLE  + "("
            + Student.KEY_ID  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + Student.KEY_name + " TEXT, "
           // + Student.KEY_age + " INTEGER, "
            + Student.KEY_info + " TEXT )";
           // + Student.KEY_email + " TEXT )";

    db.execSQL(CREATE_TABLE_STUDENT);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed, all data will be gone!!!
    db.execSQL("DROP TABLE IF EXISTS " + Student.TABLE);

    // Create tables again
    onCreate(db);

}

}

MainActivity.java

package com.nate.nash.howtoloveme;

/**
 * Created by Nash on 1/13/2016.
 */
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends ListActivity  implements android.view.View.OnClickListener{

    Button btnAdd,btnGetAll;
    TextView student_Id;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Intent intent = new Intent(MainActivity.this, MyActivity.class);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        if (view== findViewById(R.id.btnAdd)){

            Intent intent = new Intent(this,StudentDetail.class);
            intent.putExtra("student_Id",0);
            startActivity(intent);

        }else {

            StudentRepo repo = new StudentRepo(this);

            ArrayList<HashMap<String, String>> studentList =  repo.getStudentList();
            if(studentList.size()!=0) {
                ListView lv = getListView();
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                        student_Id = (TextView) view.findViewById(R.id.student_Id);
                        String studentId = student_Id.getText().toString();
                        Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);
                        objIndent.putExtra("student_Id", Integer.parseInt( studentId));
                        startActivity(objIndent);
                    }
                });
                ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name});
                setListAdapter(adapter);
            }else{
                Toast.makeText(this,"No student!",Toast.LENGTH_SHORT).show();
            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StudentRepo repo = new StudentRepo(this);

        ArrayList<HashMap<String, String>> studentList =  repo.getStudentList();
        if(studentList.size()!=0) {
            ListView lv = getListView();
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                    student_Id = (TextView) view.findViewById(R.id.student_Id);
                    String studentId = student_Id.getText().toString();
                    Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);
                    objIndent.putExtra("student_Id", Integer.parseInt( studentId));
                    startActivity(objIndent);
                }
            });
            ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name});
            setListAdapter(adapter);
        }else{
            Toast.makeText(this,"No student!",Toast.LENGTH_SHORT).show();
        }

        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(this);

        btnGetAll = (Button) findViewById(R.id.btnGetAll);
        btnGetAll.setOnClickListener(this);

    }


}

尝试使用此功能

private void exportDB() {

    File dbFile=getDatabasePath("MyDBName.db");
    DBHelper dbhelper = new DBHelper(getApplicationContext());
    File exportDir = new File(Environment.getExternalStorageDirectory(), "");
    if (!exportDir.exists())
    {
        exportDir.mkdirs();
    }

    File file = new File(exportDir, "csvname.csv");
    try
    {
        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        SQLiteDatabase db = dbhelper.getReadableDatabase();
        Cursor curCSV = db.rawQuery("SELECT * FROM contacts",null);
        csvWrite.writeNext(curCSV.getColumnNames());
        while(curCSV.moveToNext())
        {
            //Which column you want to exprort
            String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
            csvWrite.writeNext(arrStr);
        }
        csvWrite.close();
        curCSV.close();
    }
    catch(Exception sqlEx)
    {
        Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
    }
}

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM