I am trying to delete files from a list view, I am able to delete the original file but not to delete the name from the list, I think its because I need to delete it from the database, problem is I don't know how, could somebody help?
// the adapter
listAdapter = new ArrayAdapter<String>(RecordsActivity.this, R.layout.support_simple_spinner_dropdown_item, MainActivity.listRecord);
recordList.setAdapter(listAdapter);
//deleting the file (which goes well, the name is not deleted from the database I guess)
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
datadelete(filePath);
listAdapter.remove(recordToPlay);
listAdapter.notifyDataSetChanged();
delete.setVisibility(View.INVISIBLE);
share.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "File deleted successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
// The dataDelete method
public void dataDelete(String inputPath) throws FileNotFoundException {
try {
// delete the original file
new File(inputPath).delete();
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
//Main Activity
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "/Recordings");
directory.mkdirs();
//outPutFile = Environment.getExternalStorageDirectory().toString() + "/recording.3gp";
String dateTime = new SimpleDateFormat("dd.MM.yyyy hh-mm-ss aa", Locale.getDefault()).format(new Date());
//Date date = new Date();
//String dateTime = DateFormat.getDateTimeInstance().format(date);
outPutFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recordings/"+dateTime +".m4a";
final String DIR_DATABASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recordings";
String sqliteQuery = "CREATE TABLE IF NOT EXISTS Recordings (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , fileName VARCHAR)";
database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "db.sqlite", null);
database.execSQL(sqliteQuery);
getNames();
// The getNames method for retrieving the names of the files
public static void getNames(){
Cursor cursor = database.rawQuery("SELECT fileName FROM Recordings", null);
ArrayList<String> fileNames = new ArrayList<>();
while (cursor.moveToNext()) {
String fileName = cursor.getString(0);
fileNames.add(fileName);
}
cursor.close();
database.close();
listRecord.addAll(fileNames);
}
// And this is where I save the files
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
stop.setEnabled(false);
pauseBtn.setEnabled(false);
SQLiteDatabase database = SQLiteDatabase.openDatabase(DIR_DATABASE + "db.sqlite", null, 0);
values = new ContentValues();
values.put("fileName", outPutFile.substring(31));
database.insert("Recordings", "", values);
Toast.makeText(getApplicationContext(), "Audio recorded", Toast.LENGTH_LONG).show();
Activity mActivity = MainActivity.this;
restartActivity(mActivity);
}
});
You should add a delete query to delete data from the database. Change your code in to
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
datadelete(filePath);
database = this.getWritableDatabase();
database.execSQL("DELETE FROM Recordings WHERE fileName = '"+your file name Here+"'");
database.close();
listAdapter.remove(recordToPlay);
listAdapter.notifyDataSetChanged();
delete.setVisibility(View.INVISIBLE);
share.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "File deleted successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
You should write the filename which you want to delete in the sqlite query. Hope this will work.
Related
I'm having a problem with my project.
I'm making an app that must export in CSV and XLS, I have searched for tutorials all over the internet but some I have not understood, I got this library SqliteToExcel, quite useful, it is working ... What happens is that after exporting the file does not appear in windows until I reboot the device, I tried everything, clean the project and rebuild it many times and nothing serves me ... The same thing happened with the CSV but with some lines of code it was resolved but with Excel they don't work.
ExportExcel:
public void exportExcel () {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MultiEntry/Excel");
final String doc = file.toString() + "/" + TABLE_NAME + "-" + currentDateandTime + ".xls";
String filename = TABLE_NAME+"-"+currentDateandTime+".xls";
Log.d(TAG, doc);
if (!file.exists()) {
file.mkdirs();
}
try {
SQLiteToExcel sqliteToExcel = new SQLiteToExcel(context, "MultiEntry.db", file.getPath());
sqliteToExcel.exportSingleTable(TABLE_NAME, filename, new SQLiteToExcel.ExportListener() {
#Override
public void onStart() {
}
#Override
public void onCompleted(String file) {
Toast.makeText(context, "File Excel created successfully", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Exception e) {
}
});
} catch (Exception e)
{System.out.println("Error"+e);}
This is the ExportCSV:
public void exportCSV () {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MultiEntry/CSV");
final String doc = file.toString() + "/" + TABLE_NAME + "-" + currentDateandTime + ".csv";
Log.d(TAG, doc);
if(!file.exists()) {
file.mkdirs();
}
try {
FileWriter fileWriter = new FileWriter(doc, true);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Records", null );
fileWriter.append(COLUMN_ID);
fileWriter.append(",");
fileWriter.append(COLUMN_ONE);
fileWriter.append(",");
fileWriter.append(COLUMN_TWO);
fileWriter.append(",");
fileWriter.append(COLUMN_THREE);
fileWriter.append(",");
fileWriter.append(COLUMN_FOUR);
fileWriter.append("\n");
if(cursor != null && cursor.getCount() != 0 ){
cursor.moveToFirst();
do{
fileWriter.append(cursor.getString(0));
fileWriter.append(",");
fileWriter.append(cursor.getString(1));
fileWriter.append(",");
fileWriter.append(cursor.getString(2));
fileWriter.append(",");
fileWriter.append(cursor.getString(3));
fileWriter.append(",");
fileWriter.append(cursor.getString(4));
fileWriter.append("\n");
} while (cursor.moveToNext());
}else {
Toast.makeText(context, "There's not records on database", Toast.LENGTH_SHORT).show();
}
db.close();
fileWriter.flush();
fileWriter.close();
String[] paths = new String[1];
paths[0] = doc;
MediaScannerConnection.scanFile(context, paths, null, null);
Toast.makeText(context, "File CSV created successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
System.out.println("Error"+e);
}
}
The block of CSV works pretty well, i have not problems, the files appears when i connect the device to the computer, but with the ExcelExport is another history, someone knows a solution?
I am making a video player app and i am adding a rename function but i can't rename the files i have tried many different methods but they are not working.
Here is the code i am using
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.rename_layout);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
final EditText editText = dialog.findViewById(R.id.rename_edit_text);
Button cancel = dialog.findViewById(R.id.cancel_rename_button);
Button rename_btn = dialog.findViewById(R.id.rename_button);
final File file = new File(new File(path).getAbsolutePath());
editText.setText(file.getName());
editText.requestFocus();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
rename_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editText.getText().toString();
boolean renamed = file.renameTo(new File(name));
Log.i("name_i", file.getName());
Toast.makeText(getContext(), String.valueOf(renamed), Toast.LENGTH_SHORT).show();
mAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
mAdapter.notifyDataSetChanged();
dialog.show();
I am getting the file path from an array list from a cursor. The boolean is returning false value and the files name is not changing.
public ArrayList<File> GetVideoFile()
{
mSwipeRefreshLayout.setRefreshing(true);
ContentResolver contentResolver = getContext().getContentResolver();
Uri videoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String sortOrder = MediaStore.Video.Media.DATE_ADDED + " ASC";
Cursor cursor = contentResolver.query(videoUri, null, null, null, sortOrder);
try {
if (cursor != null && cursor.moveToFirst()) {
int videoPath = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
do {
String path = cursor.getString(videoPath);
File file = new File(path);
fileArrayList.add(file);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.i("CursorHandleException", e.getMessage());
mSwipeRefreshLayout.setRefreshing(false);
}
Collections.reverse(fileArrayList);
mSwipeRefreshLayout.setRefreshing(false);
return fileArrayList;
}
So i understood how to do it i am using this code
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.rename_layout);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
final EditText editText = dialog.findViewById(R.id.rename_edit_text);
Button cancel = dialog.findViewById(R.id.cancel_rename_button);
Button rename_btn = dialog.findViewById(R.id.rename_button);
final File file = new File(path);
String nameText = file.getName();
nameText = nameText.substring(0,nameText.lastIndexOf("."));
editText.setText(nameText);
editText.requestFocus();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
rename_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String onlyPath = file.getParentFile().getAbsolutePath();
String ext = file.getAbsolutePath();
ext = ext.substring(ext.lastIndexOf("."));
String newPath = onlyPath+"/"+editText.getText().toString()+ext;
File newFile = new File(newPath);
boolean rename = file.renameTo(newFile);
if(rename)
{
ContentResolver resolver = getActivity().getApplicationContext().getContentResolver();
resolver.delete(
MediaStore.Files.getContentUri("external")
, MediaStore.MediaColumns.DATA + "=?", new String[] { file.getAbsolutePath() });
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(newFile));
getActivity().getApplicationContext().sendBroadcast(intent);
Toast.makeText(getContext(), "SuccessFull!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getContext(), "Oops! rename failed", Toast.LENGTH_SHORT).show();
}
fileArrayList.clear();
GetVideoFile();
mAdapter.notifyDataSetChanged();
mAdapter.notifyItemChanged(adapterPosition);
dialog.dismiss();
}
});
mAdapter.notifyDataSetChanged();
dialog.show();
The accepted answer is outdated. This is what I used
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE is deperecated Callers should migrate to inserting items directly into MediaStore, where they will be automatically scanned after each mutation.
String extension = videoFile.getAbsolutePath(); extension = extension.substring(extension.lastIndexOf("."));
ContentValues values = new ContentValues(2); values.put(MediaStore.Video.Media.TITLE, title);
values.put(MediaStore.Video.Media.DISPLAY_NAME, title + extension );
context.getContentResolver().update(MediaStore.Video.Media. EXTERNAL_CONTENT_URI, values,
MediaStore.MediaColumns.DATA + "=?", new String[]{videoFile. getAbsolutePath()});
if (videoOptionListener != null) { videoOptionListener.onEdit();
} dialogRenameVideo.dismiss(); });
I have an android app that uses a service to collect sensor data every 5ms and inserts it into a sqlite table. In a typical session there will be about 40mins of recordings. All of that code seems to be working fine.
I have a strange problem where if the user navigates to a particular fragment I get a CursorWindow: Window is full: requested allocation XXX error. I'm not sure what is special about this specific fragment that is causing that error, and only happens with this one fragment
The fragment in question contains a button, which when clicked will do a number of things:
Creates some directories on external storage
Copies all of the sensor data from the temporary table and inserts it into a more permanent table
Creates a copy of the entire .db file to external storage
Takes the contents of a table and writes it to a CSV file
Queries another table for sensor data, and writes all of that sensor data to another CSV file
Uses media scanner to scan all of the files in the export directory so they can be accessed via MTP
The fragment code looks like this (a lot of the catch blocks have been left out for brevity - they mostly just log information):
public class SaveFragment extends Fragment implements View.OnClickListener {
Button saveButton;
MainActivity mainActivity;
DBHelper dbHelper;
Boolean subjectDataExists;
MediaScanner mediaScanner;
static ProgressDialog dialog;
public SaveFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_save, container, false);
//Get save button view
saveButton = (Button) view.findViewById(R.id.saveButton);
saveButton.setOnClickListener(this);
//Get DBHelper
dbHelper = DBHelper.getInstance(getActivity(), new DatabaseHandler());
//Check if sensor data has been recorded
subjectDataExists = dbHelper.checkSubjectDataExists(Short.parseShort(dbHelper.getTempSubInfo("subNum")));
// Inflate the layout for this fragment
return view;
}
#Override
public void onClick(View v) {
//Alert dialog for saving/quitting
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mainActivity);
if (subjectDataExists) {
alertDialogBuilder.setTitle("Save and quit?");
alertDialogBuilder.setMessage("Are you sure you want to save the data and quit the current session?");
} else {
alertDialogBuilder.setTitle("Quit?");
alertDialogBuilder.setMessage("Are you sure you want to quit the current session? \n\n No data will be saved.");
}
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Save if sensor data exists, otherwise quit
if (subjectDataExists) {
new ExportDatabaseCSVTask().execute();
} else {
quitSession();
}
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog quitAlertDialog = alertDialogBuilder.create();
quitAlertDialog.show();
}
//Quit the current session and go back to login screen
private void quitSession(){
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
getActivity().finishAffinity();
}
//Message handler class for database progress updates
private static class DatabaseHandler extends Handler {
#Override
public void handleMessage (Message msg){
Double progressPercent = (Double) msg.obj;
Integer progressValue = 40 + (int) Math.ceil(progressPercent/2);
dialog.setProgress(progressValue);
}
}
//Async class for CSV export task
public class ExportDatabaseCSVTask extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
//show a progress dialog
}
protected Boolean doInBackground(final String... args) {
//Create directories for the output csv files
String pathToExternalStorage = Environment.getExternalStorageDirectory().toString();
File exportDir = new File(pathToExternalStorage, "/Data");
File subjectDataDir = new File(exportDir, "/subjects");
publishProgress(5);
//The sleep is here just so the progress updates in the dialog are visually slower
SystemClock.sleep(100);
if (!exportDir.exists()) {
Boolean created = exportDir.mkdirs();
}
publishProgress(10);
SystemClock.sleep(100);
if (!subjectDataDir.exists()) {
Boolean created = subjectDataDir.mkdirs();
}
publishProgress(15);
SystemClock.sleep(100);
//If all directories have been created successfully
if (exportDir.exists() && subjectDataDir.exists()) {
try {
//Copy temp subject and sensor data to persistent db tables
dbHelper.copyTempData();
publishProgress(20);
SystemClock.sleep(200);
//Backup the SQL DB file
File data = Environment.getDataDirectory();
String currentDBPath = "//data//com.example.app//databases//" + DBHelper.DATABASE_NAME;
File currentDB = new File(data, currentDBPath);
File destDB = new File(exportDir, DBHelper.DATABASE_NAME);
publishProgress(25);
SystemClock.sleep(100);
if (exportDir.canWrite()) {
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(destDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
publishProgress(35);
SystemClock.sleep(300);
//Export subjects table/tracking sheet
File trackingSheet = new File(exportDir, "trackingSheet.csv");
try{
dbHelper.exportTrackingSheet(trackingSheet);
} catch (SQLException | IOException e){
}
publishProgress(40);
SystemClock.sleep(300);
//Export individual subject data
String subNum = dbHelper.getTempSubInfo("subNum");
File subjectFile = new File(subjectDataDir, subNum + ".csv");
try{
dbHelper.exportSubjectData(subjectFile, subNum);
} catch (SQLException | IOException e){
}
publishProgress(90);
SystemClock.sleep(300);
//Scan all files for MTP
List<String> fileList = getListFiles(exportDir);
String[] allFiles = new String[fileList.size()];
allFiles = fileList.toArray(allFiles);
mediaScanner = new MediaScanner();
try{
mediaScanner.scanFile(getContext(), allFiles, null, mainActivity.logger);
} catch (Exception e) {
}
publishProgress(100);
SystemClock.sleep(400);
return true;
} catch (SQLException | IOException e) {
} else {
//Directories don't exist
if (!exportDir.exists()) {
} else if (!subjectDataDir.exists()) {
return false;
}
}
public void onProgressUpdate(Integer ... progress){
dialog.setProgress(progress[0]);
if (progress[0] == 100){
dialog.setMessage("Quitting...");
}
}
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
//Restart app and go back to login screen
quitSession();
}
}
//Recursive file lister for MTP
private List<String> getListFiles(File parentDir) {
ArrayList<String> inFiles = new ArrayList<>();
File[] files = parentDir.listFiles();
//Loop through everything in base directory, including folders
for (File file : files) {
if (file.isDirectory()) {
//Recursively add files from subdirectories
inFiles.addAll(getListFiles(file));
} else {
inFiles.add(file.getAbsolutePath());
}
}
return inFiles;
}
}
}
After a lot of sensor data has been recorded, I get the error every time the user navigates to the fragment. But when the button is clicked, I get the error continuously every 2 seconds.
The sensor recording service code can be found in my other question: Android sending messages between fragment and service
This fragment calls a number of methods from my DBHelper class (which is set up as a singleton):
public class DBHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
CSVWriter csvWrite;
Cursor curCSV;
static Handler messageHandler;
private static DBHelper sInstance;
public static synchronized DBHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new DBHelper(context.getApplicationContext());
Log.d(TAG, "New DBHelper created");
}
return sInstance;
}
public static synchronized DBHelper getInstance(Context context, Handler handler) {
if (sInstance == null) {
sInstance = new DBHelper(context.getApplicationContext());
Log.d(TAG, "New DBHelper created");
}
messageHandler = handler;
return sInstance;
}
private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWritableDatabase();
}
public boolean checkSubjectDataExists(Short subNum) throws SQLException {
//Check if sensor data, for this subject, exists in the temp data table
String query = "SELECT * FROM " + DATA_TABLE_NAME_TEMP + " WHERE " + DATA_SUBJECT + "=" + subNum;
Cursor c = db.rawQuery(query, null);
boolean exists = (c.getCount() > 0);
c.close();
return exists;
}
public void copyTempData() throws SQLException{
String copySubjectSQL = "INSERT INTO " + SUBJECTS_TABLE_NAME + " SELECT * FROM " + SUBJECTS_TABLE_NAME_TEMP;
db.execSQL(copySubjectSQL);
String copyDataSQL = "INSERT INTO " + DATA_TABLE_NAME + " SELECT * FROM " + DATA_TABLE_NAME_TEMP;
db.execSQL(copyDataSQL);
}
public void exportTrackingSheet(File outputFile) throws SQLException, IOException {
csvWrite = new CSVWriter(new FileWriter(outputFile));
curCSV = db.rawQuery("SELECT * FROM " + SUBJECTS_TABLE_NAME, null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2),
curCSV.getString(3), curCSV.getString(4), curCSV.getString(5), curCSV.getString(6)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
public void exportSubjectData(File outputFile, String subNum) throws IOException, SQLException {
csvWrite = new CSVWriter(new FileWriter(outputFile));
curCSV = db.rawQuery("SELECT * FROM " + DATA_TABLE_NAME + " WHERE id = " + subNum, null);
csvWrite.writeNext(curCSV.getColumnNames());
Integer writeCounter = 0;
Integer numRows = curCSV.getCount();
while (curCSV.moveToNext()) {
writeCounter++;
String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2),
curCSV.getString(3), curCSV.getString(4), curCSV.getString(5),
curCSV.getString(6), curCSV.getString(7), curCSV.getString(8),
curCSV.getString(9), curCSV.getString(10), curCSV.getString(11),
curCSV.getString(12), curCSV.getString(13), curCSV.getString(14),
curCSV.getString(15), curCSV.getString(16), curCSV.getString(17),
curCSV.getString(18), curCSV.getString(19), curCSV.getString(20),
curCSV.getString(21), curCSV.getString(22), curCSV.getString(23),
curCSV.getString(24), curCSV.getString(25)};
csvWrite.writeNext(arrStr);
if ((writeCounter % 1000) == 0){
csvWrite.flush();
}
Double progressPercent = Math.ceil(((float) writeCounter / (float) numRows)*100);
Message msg = Message.obtain();
msg.obj = progressPercent;
msg.setTarget(messageHandler);
msg.sendToTarget();
}
csvWrite.close();
curCSV.close();
}
}
The DBHelper and any SQL connections are closed in onDestroy of my main activity
My media scanner class is also pretty straightforward:
public class MediaScanner {
protected void scanFile(final Context context, String[] files, String[] mimeTypes, final Logger logger) {
MediaScannerConnection.scanFile(context, files, mimeTypes,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
//Log some info
}
}
);
}
}
Can anyone see anything special about my fragment code that is causing this cursor window error?
I want to convert a single row to a .csv file. How am I going to do that? All I've seen in the Internet are most of them the whole sqlite db is being converted/exported to a .csv file. But my requirement is only a single record? Do you have ideas as to how am I gonna achieve this? Help is much appreciated. Thanks!
Update:
public class CSVCreationActivity extends Activity {
TextView empidtxt,empnametxt,empsaltxt;
EditText empidet,empnameet,empsalet;
Button insetbt,viewbt;
SQLiteDatabase myDatabase=null;
String DataBase_Name="employeedata";
String Table_Name="employeedetails";
Cursor c1,c2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
empidtxt=(TextView)findViewById(R.id.tv1);
empnametxt=(TextView)findViewById(R.id.tv2);
empsaltxt=(TextView)findViewById(R.id.tv3);
empidet=(EditText)findViewById(R.id.et1);
empnameet=(EditText)findViewById(R.id.et2);
empsalet=(EditText)findViewById(R.id.et3);
insetbt=(Button)findViewById(R.id.bt1);
viewbt=(Button)findViewById(R.id.bt2);
try {
myDatabase=this.openOrCreateDatabase(DataBase_Name, MODE_PRIVATE, null);
System.out.println("databse has been created.....");
myDatabase.execSQL("create table if not exists " + Table_Name + "(empid integer(10),empname varchar(50),empsal integer(10))");
System.out.println("table has been created.....");
c1 = myDatabase.rawQuery("select * from " + Table_Name, null);
c1.moveToFirst();
int count1 = c1.getCount();
System.out.println("columns --->" + count1);
if (count1 == 0) {
myDatabase.execSQL("insert into "+Table_Name+ "(empid,empname,empsal)" +"values(101,'asha',20000)");
System.out.println("data base has been inserted.....");
}
c2 = myDatabase.rawQuery("select * from " + Table_Name, null);
c2.moveToFirst();
int count2 = c2.getCount();
System.out.println("columns --->" + count2);
final int column1 = c2.getColumnIndex("empid");
final int column2 = c2.getColumnIndex("empname");
final int column3 = c2.getColumnIndex("empsal");
insetbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (c2 != null) {
do {
int id = c2.getInt(column1);
String name = c2.getString(column2);
int salary = c2.getInt(column3);
System.out.println("empID --> "+id);
System.out.println("empNAME --> "+name);
System.out.println("empsalalry --> "+salary);
} while(c2.moveToNext());
}
}
});
viewbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new ExportDatabaseCSVTask().execute("");
} catch(Exception ex) {
Log.e("Error in MainActivity",ex.toString());
}
}
});
}
catch(SQLException ex) { ex.printStackTrace(); }
/*finally {
if (myDB != null) { myDB.close(); }
}*/
}
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(CSVCreationActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
File dbFile = getDatabasePath("myDatabase.db");
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) { exportDir.mkdirs(); }
File file = new File(exportDir, "myfile.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = myDatabase.rawQuery("select * from " + Table_Name,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()) {
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
// curCSV.getString(3),curCSV.getString(4)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
return true;
} catch(SQLException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
} catch (IOException e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) { this.dialog.dismiss(); }
if (success) {
Toast.makeText(CSVCreationActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CSVCreationActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}
}
CSVWriter and CSVReader can be downloaded here
Better way to get specific record from database and then convert it to csv file ...
you just need to modify your query to achieve this
Replace this line
Cursor curCSV = myDatabase.rawQuery("select * from " + Table_Name,null);
with ur conditional query means using where operator or anything else...
I've been having a weird issue lately regarding my database-driven android app. I use the code UPDATE before with no problem but now it won't allow me to update changes to my records.
I did try to log if it's saving the changes I've made but it doesn't.
Here's the code I'm using:
private void initControls() {
userInput = (EditText) findViewById (R.id.editTextDialogUserInput);
save = (Button) findViewById (R.id.btSave);
cancel = (Button) findViewById (R.id.btCancel);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
stID = extras.getString("dog_id");
dog_name = extras.getString("dog_name");
cursor = dbHelper.fetchbBreedByName(dog_name);
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
Log.d("Animal ID", "Animal ID is " + stID + " and breed is " + dog_name);
userInput.setText(strDesc);
}
}
private void checkDatabaseConnection() {
// TODO Auto-generated method stub
dbHelper = new DBHelper(this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btSave:
if(userInput.equals("")){
Toast.makeText(this, "No input", Toast.LENGTH_SHORT).show();
}
else {
id = Long.valueOf(stID);
dbHelper.updateDescription( id, userInput.getText().toString() );
Toast.makeText(this, "Description has been updated successfully!",
Toast.LENGTH_SHORT).show();
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
Log.d("Updated", dog_name + " " + strDesc);
Intent i = new Intent(this, DogClass.class);
startActivity(i);
finish();
}
break;
case R.id.btCancel:
userInput.setText("");
break;
}
}
#Override
protected void onDestroy() {
dbHelper.close(); // close DB
cursor.close(); // close cursor
super.onDestroy();
}
Whole code can be viewed here
I really don't know what's wrong, anybody here has experienced this before? Might as well help me figure out what I'm missing in my code. Help is pretty much appreciated. Thanks.
Try to use update method like this..
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(IConstants.FOLDER_LOCKED, isSelected);
database.update(FOLDER_TABLE, cv, IConstants.FOLDER_NAME + "= ?",
new String[] { foldername });