store the Sugar ORM database in sd card rather than default path android - android

i am using sugar orm to store my data in sqlite database in android and it is working perfectly so now i want to store the data in the local storage rather than the default path so how can i achieve that and moreover that is it possible to do this
Thanks.
This is my mainactivity code
public class MainActivity extends AppCompatActivity {
EditText firstname;
EditText lastname;
Button button;
Note note;
public SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstname=findViewById(R.id.edit1);
lastname=findViewById(R.id.edit2);
button=findViewById(R.id.button);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void click(View view) {
String first = firstname.getText().toString();
String last = lastname.getText().toString();
note = new Note(first, last);
note.save();
if (note.getFirstname() != null && note.getLastname() != null) {
firstname.setText("");
lastname.setText("");
}
onShareDb();
//Log.e("Notes saved", String.valueOf(onShareDb()));
}
public void show(View view) {
String one=note.getFirstname();
String two=note.getLastname();
Log.e("firstName",one);
Log.e("lastName",two);
}
public void update(View view) {
note = Note.findById(Note.class, 4);
Log.e("firstName",note.getFirstname());
note.setFirstname("kullu");
Log.e("firstName",note.getFirstname());
note.save();
}
public void delete(View view) {
note = Note.findById(Note.class, 2);
if(note.getId()==null){
Toast.makeText(this,"there is no such data",Toast.LENGTH_SHORT).show();
}
Log.e("firstName",note.getFirstname());
note.delete();
Log.e("firstName",note.getFirstname());
}
public void onShareDb() {
#SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String output_name = "YourApp_" + df.format(new Date()) + ".db";
File output_file = new File(getExternalCacheDir() + File.separator + output_name);
try {
File file = new File(new SugarDb(MainActivity.this).getDB().getPath()); // get private db reference
if (!file.exists() || file.length() == 0) throw new Exception("Empty DB");
//IOUtils.copy(new FileInputStream(file), new FileOutputStream(output_file));
/* Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(output_file));
startActivity(Intent.createChooser(i, "Send db"));*/
database = SQLiteDatabase.openDatabase(output_file
+ File.separator + "notes.db", null,
SQLiteDatabase.OPEN_READWRITE);
Log.e("storage", String.valueOf(database));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Unable to export db: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("storage", e.getMessage());
}
}
}
So, basically i m trying to get the path of stored images by using the shareDB() property of sugar orm and trying to overwrite the default path to my new path so how do i get it done, i m calling shareDB method in button click listener, the exception is something like unknown error: could not open database.

After a lot of research and trial error, I somehow manage to succeed in copying the sqllite file from one folder to another folder in the directory
Here is the code,
private void copyDatabase() throws IOException {
File actualFile = new File(new SugarDb(MainActivity.this).getDB().getPath());
File cuurentfile = new File(actualFile.toString());
Log.e("actualPath", actualFile.toString());
File newFile = createTempFile("sugarFiles",".db",Environment.getExternalStorageDirectory());
Log.e("newPath", newFile.toString());
boolean yes=FileUtils.copyFile(cuurentfile,newFile);
if(yes) {
Log.e("result", "" + true);
}
}
call this copydatabase function inside the click listener or wherever you are inserting into the database, make sure it is after you set the insertion values, in my case
public void click(View view) {
String first = firstname.getText().toString();
String last = lastname.getText().toString();
note = new Note(first, last);
note.save();
if (note.getFirstname() != null && note.getLastname() != null) {
firstname.setText("");
lastname.setText("");
}
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
FileUtils.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileUtils {
FileUtils instance = null;
public FileUtils getInstance() {
instance = new FileUtils();
return instance;
}
public static Boolean copyFile(File sourceFile, File destFile)
throws IOException {
// if (!destFile.exists()) {
destFile.createNewFile();
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null)
source.close();
if (destination != null)
destination.close();
}
return true;
// }
// return false;
}
/**
* Read a text file into a String.
*
* #param file
* File to read (will not seek, so things like /proc files are
* OK).
* #return The contents of the file as a String.
* #throws IOException
*/
public static String readTextFile(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
BufferedInputStream stream = new BufferedInputStream(
new FileInputStream(file));
stream.read(buffer);
stream.close();
return new String(buffer);
}
}
Hope it helps someone someday...Have a nice day

Related

How to download Google Doc, Spreadsheet and Presentation file by using Drive API?

I used the following Drive API code in Android for download files from Google Drive.
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(GoogleDriveActivity.this);
DriveClient mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
DriveResourceClient mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
By using this code I am able to download all files i.e Docx, Doc, Image, xls, xlsx, txt, pdf etc.
but it has given the issue for the following files.
Google Doc (application/vnd.google-apps.document),
SpreadSheet (application/vnd.google-apps.spreadsheet),
Presentation file (application/vnd.google-apps.presentation)
even I tried to change metadata for the selected file by using this code but still, its shown file size is 0 (Zero) and
the extension is null.
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setMimeType(Constants.MIME_TYPE_DOCX)
.build();
Task<Metadata> updateMetadataTask =
mDriveResourceClient.updateMetadata(file, changeSet);
So please suggest the solution if anybody implemented it.
I tried to download Google Doc, Spreadsheet and Presentation file by using Google Drive Android API but didn’t get any proper solution for it by using Drive API.
But I have read in many places that you can download this documents using REST. Finally, I got the right solution for it when I combined both these codes i.e. Drive API Code and REST code
Here is the code for it.
First, you need to add these two lines in your build.gradle file in App module.
compile('com.google.api-client:google-api-client-android:1.23.0') {
exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev107-1.23.0') {
exclude group: 'org.apache.httpcomponents'
}
Second, Initialize GoogleAccountCredential and Drive by your selected account.
private com.google.api.services.drive.Drive driveService = null;
private GoogleAccountCredential signInCredential;
private long timeStamp;
private String fileName;
// Initialize credentials and service object.
signInCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
if (!TextUtils.isEmpty(signInAccount.getAccount().name)) {
signInCredential.setSelectedAccountName(signInAccount.getAccount().name);
signInCredential.setSelectedAccount(new Account(signInAccount.getAccount().name, getPackageName()));
}
if (!TextUtils.isEmpty(signInCredential.getSelectedAccountName())) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
driveService = new com.google.api.services.drive.Drive.Builder(transport, jsonFactory, signInCredential)
.setApplicationName(appName)
.build();
}
//Pass two parameters i.e fileId and mimeType which one you get when you select the file name.
public void retrieveGoogleDocContents(String fileId, String mimeType) throws IOException {
try {
File storageDir =createStorageDir();
timeStamp = System.currentTimeMillis();
//selectedFileName which one you get when you select any file from the drive, or you can use any name.
fileName = selectedFileName + "." +getFileExtension(mimeType);
File localFile = new File(storageDir, timeStamp + "_" + fileName);
if (!localFile.exists()) {
if (localFile.createNewFile())
Log.d(TAG, fileCreated);
}
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean isSuccess = false;
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(localFile);
com.google.api.services.drive.Drive.Files.Export request = driveService.files().export(fileId,getFileMimeType(mimeType));
request.getMediaHttpDownloader().setProgressListener(new GoogleDriveActivity.CustomProgressListener());
request.getMediaHttpDownloader().setDirectDownloadEnabled(false);
request.executeMediaAndDownloadTo(outputStream);
isSuccess = true;
} catch (UserRecoverableAuthIOException e) {
Log.d(TAG, "REQUEST_AUTHORIZATION Called");
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} finally {
close(outputStream);
}
return isSuccess;
}
#Override
protected void onPostExecute(Boolean isSuccess) {
Log.i(TAG, "Download Successfully :" + isSuccess);
}
};
task.execute();
} catch (IOException e){
Log.e(TAG, e.toString());
}
}
public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
public static File createStorageDir() {
String path = Environment.getExternalStorageDirectory() + "/" + Constants.IMAGE_DIRECTORY;
File storageDir = new File(path);
if (!storageDir.exists()) {
if (storageDir.mkdir())
Log.d(TAG, "Directory created.");
else
Log.d(TAG, "Directory is not created.");
} else
Log.d(TAG, "Directory exist.");
return storageDir;
}
Here are file mime type and extension.
public final static String ICON_DOCX = "docx";
public final static String ICON_PPTX = "pptx";
public final static String ICON_XLSX = "xlsx";
public final static String MIME_TYPE_GOOGLE_DOC = "application/vnd.google-apps.document";
public final static String MIME_TYPE_GOOGLE_SPREADSHEET = "application/vnd.google-apps.spreadsheet";
public final static String MIME_TYPE_GOOGLE_PRESENTATION = "application/vnd.google-apps.presentation";
public final static String MIME_TYPE_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public final static String MIME_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public final static String MIME_TYPE_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
public static String getFileExtension(String fileMimeType) {
String fileExtension = Constants.ICON_PDF;
if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
fileExtension = Constants.ICON_DOCX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
fileExtension = Constants.ICON_XLSX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
fileExtension = Constants.ICON_PPTX;
return fileExtension;
}
public static String getFileMimeType(String fileMimeType) {
String newMimeType = Constants.MIME_TYPE_PDF;
if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_DOC))
newMimeType = Constants.MIME_TYPE_DOCX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_SPREADSHEET))
newMimeType = Constants.MIME_TYPE_XLSX;
else if (fileMimeType.equals(Constants.MIME_TYPE_GOOGLE_PRESENTATION))
newMimeType = Constants.MIME_TYPE_PPTX;
return newMimeType;
}

Save an item from a listview in to a textfile in android

I am browsing an xml file from external usb storage (using otg cable, connected in the tablet/android phone) to be parsed.
Steps:
Browse for the file from external usb storage
Parse the xml file
Save the file in a text file
For the time being, I am now able to browse and parse the xml file then display the parsed file wherein it shows the needed information in a listview. Now, I want to save the displayed information as a text file and save it to the external sd card of the tablet. Here's the code:
Model.java :
public class Model {
String _model;
String _part;
String _sw;
String _desc;
// constructor
public Model() {
}
// constructor with parameters
public Model(String model, String part, String sw, String desc) {
this._model = model;
this._part = part;
this._sw = sw;
this._desc = desc;
}
// Set all methods
public void setModel(String model) {
this._model = model;
}
public void setPart(String part) {
this._part = part;
}
public void setSw(String sw) {
this._sw = sw;
}
public void setDesc(String desc) {
this._desc = desc;
}
// Get all methods
public String getModel() {
return this._model;
}
public String getPart() {
return this._part;
}
public String getSw() {
return this._sw;
}
public String getDesc() {
return this._desc;
}
//
#Override
public String toString() {
return "\n" + "Device" + "\n" + "\n"
+ "Model ID : " + _model + "\n"
+ "Part Number : " + _part + "\n"
+ "Software Version: " + _sw + "\n"
+ "Description : " + _desc ;
}
}
ModelParser.java :
public class ModelParser extends DefaultHandler{
static final String ERROR = "Errors";
static final String ID = "ID";
static final String PART = "PartNumber";
static final String SW = "SoftwareVersion";
static final String DESC = "Description";
private boolean done = false;
private String currentTag = null;
private Model current = null;
private ArrayList<Model> model = new ArrayList<Model>();
public ArrayList<Model> getItemsList() {
return model;
}
public ArrayList<Model> parse(Context context) {
try {
String file = ReadSystemActivity.getFilename();
file.toString();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
FileInputStream fis = new FileInputStream(file);
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
model = new ArrayList<Model>();
break;
case XmlPullParser.START_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR)) {
current = new Model();
}
else if (current != null) {
if (currentTag.equalsIgnoreCase(ID)) {
current.setModel(parser.nextText());
} else if (currentTag.equalsIgnoreCase(PART)) {
current.setPart(parser.nextText());
} else if (currentTag.equalsIgnoreCase(SW)) {
current.setSw(parser.nextText());
}else if (currentTag.equalsIgnoreCase(DESC)) {
current.setDesc(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR) && current != null) {
model.add(current);
} else if (currentTag.equalsIgnoreCase(ERROR)) {
done = true;
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return model;
}
}
And ReadActivity.java :
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
String modd = modId.getModel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
#Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
ModelParser parser = new ModelParser();
model = parser.parse(getBaseContext());
return model;
}
#Override
protected void onPostExecute(List<Model> models) {
ArrayAdapter<Model> adapter = new ArrayAdapter<Model>(getBaseContext(), android.R.layout.simple_list_item_1, models);
setListAdapter(adapter);
}
}
public boolean isSDCardWritable() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status))
{
return true;
}
return false;
} //isSDCardWritable
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Problem is, I want to save the Id but I am getting a null value in the SystemInfo.txt when I click the save button.
You're storing model inside another object and trying to retrieve it from a new object.
This is where you're storing your model object inside ModelParser
current = new GarminModel()
whereas you're trying to retrieve it from a new object inside ReadActivity
GarminModel modId = new GarminModel();
String modd = modId.getModel();
Get reference to your Model arraylist by calling ModelParser's getItemsList() inside ReadActivity and from it try to get your model objects
Check position of below two lines in the code below
ModelParser parser = new ModelParser();
ArrayList<Model> modelList = parser.getItemsList();
Model modd = modelList.get(0);
Note that you need to remove ModelParser parser = new ModelParser(); from LoadSystemTask
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
ModelParser parser = new ModelParser();
//-----------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
ArrayList<Model> modelList = parser.getItemsList();
//-----
Model modd = modelList.get(0);
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
#Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
model = parser.parse(getBaseContext());
return model;
}

where should place the excel sheet when reading it to android application

I'm trying to read data from excel sheet to android application in android studio 1.0.1. I referred http://www.cuelogic.com/blog/creatingreading-an-excel-file-in-android/ to do this.This is my code snippet;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button readExcelButton;
static String TAG = "ExelLog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readExcelButton = (Button) findViewById(R.id.readExcel);
readExcelButton.setOnClickListener((android.view.View.OnClickListener) this);
}
private static void readExcelFile(Context context, String filename) {
if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
{
Log.e(TAG, "Storage not available or read only");
return;
}
try{
// ***I think this is the place to correct***
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,filename);
// File file = new File(context.getExternalFilesDir(null), filename);
FileInputStream myInput = new FileInputStream(file);
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
Log.d(TAG, "Cell Value: " + myCell.toString());
Toast.makeText(context, "cell Value: " + myCell.toString(), Toast.LENGTH_SHORT).show();
}
}
}catch (Exception e){
e.printStackTrace();
}
return;
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.readExcel:
readExcelFile(this,"test.xls");
break;
}
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
This is the thing I want to do. I want to add excel sheet to my mobile device and (some where like in sdCard). When I run this this is the output on logcat after clicking the button
03-07 21:40:40.620 12484-12484/com.example.t_buddhika.csv W/System.err﹕ java.io.FileNotFoundException: /storage/sdcard0/test.xls: open failed: ENOENT (No such file or directory)
03-07 21:40:40.620 12484-12484/com.example.t_buddhika.csv W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:427)
03-07 21:40:40.620 12484-12484/com.example.t_buddhika.csv W/System.err﹕ at java.io.FileInputStream.<init>(FileInputStream.java:78)
....
03-07 21:40:40.630 12484-12484/com.example.t_buddhika.csv W/System.err﹕ ... 14 more
So how could I do that? How should I change the code and where should I put excel sheet? Help me on this.

What class and method to use while reading/writing a file to internal/external storage android?

I have google alot, read javadoc, plus search different forums including this reading the issue but not found the correct answer to my question. The code snippet below is working fine but I want to exactly know what function to use exactly for read/write file in android. One can write to internal storage using OutputStream, FileOutputSteam.write(), Other is to use OutputStreamWriter(FileOutputSteam).write(), further BufferedWriter(OutputStreamWriter).write(), and finally PrintWriter.write().
Same goes for the InputStream case whether to use InputStream, FileInputSteam.read(), InputSreamReader(FileInputStream).read(), BufferedReader(InputStreamReader).
I want to know which exactly is the best proper way to do it. Please help me out as totally confused with this.
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "students.txt";
private EditText stdId;
private Button Insert;
private Button Search;
private Button Update;
private Button Delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String TAG = MainActivity.class.getName(); //output: com.fyp2.testapp.MainActivity
//value used for insert/delete/search
stdId = (EditText) findViewById(R.id.editTxtId);
//insert value in application sandbox file
Insert = (Button) findViewById(R.id.btnInsert);
Insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String IdToInsert = stdId.getText().toString().trim();
if(IdToInsert.length() > 0) {
myInsertFunc(IdToInsert);
}
else {
Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
stdId.requestFocus();
}
}
});
//search value from application sandbox file
Search = (Button) findViewById(R.id.btnSearch);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String IdToSearch = stdId.getText().toString().trim();
if(IdToSearch.length() > 0) {
mySearchFunc(IdToSearch);
}
else {
Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
stdId.requestFocus();
}
}
});
//delete value from application sandbox file
Delete = (Button) findViewById(R.id.btnDelete);
Delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String IdToDelete = stdId.getText().toString().trim();
if(IdToDelete.length() > 0) {
myDeleteFunc(IdToDelete);
}
else {
Toast.makeText(getApplicationContext(), "Id cannot be null!", Toast.LENGTH_SHORT).show();
stdId.requestFocus();
}
}
});
}
//function to insert
private void myInsertFunc(String data) {
//If student id already exist don't write it again -> Not handled at the moment
//Other exceptions may not have been handled properly
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_APPEND));
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.append(data);
bufferedWriter.newLine();
Toast.makeText(getApplicationContext(), "Student ID: " + data + " Inserted Successfully!", Toast.LENGTH_SHORT).show();
bufferedWriter.close();
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
//function to search
private void mySearchFunc(String data) {
//Id id not found show toast to user -> Not handled at the moment
try {
InputStream inputStream = openFileInput(FILENAME);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ((receiveString = bufferedReader.readLine()) != null) {
if(receiveString.contains(data))
{
Toast.makeText(getApplicationContext(), "Found Student ID: " + data , Toast.LENGTH_SHORT).show();
break;
}
}
bufferedReader.close();
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
}
private void myDeleteFunc(String data) {
/* I have found a solution to delete a specific line from the file.
* But the problem is that it needs to scan the whole file line by line and copy the file contents that not matches the string to temp file.
* This solution can reduce the effeciency. Consider search 20,000 records in a file.
* Need to work around on it.
*/
}
private void myUpdateFunc(String data) {
/* Same goes to the update process...
* Need to scan all records and copy content in temp file and put the updated data in that file.
* Need to work around on this issue too...
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
They all serve a purpose. There is best proper way, because each writer was made for a reason. Usually anything that has buffered is more efficient if you have mulitple read/writes/flush.
Both the Android and Java docs can be helpful and java docs give you more description for these writers. Check out these documentation. Try reading the javase6 ones which are more detailed:
Android_FileWriter
Java_FileWriter
Android_OutputStreamWriter
Java_OutputStreamWriter
Android_BufferedWriter
Java_BufferedWriter

How to scan SD card for particular extension of files in android?

I am working on a project which contains a module to scan pdf, doc xls files from sd card and make list of them. I also want to make list of folders only.
As I am very new to android. Anyone have idea of achieving this.
Here is my code:
public class MediaScannerWrapper implements
MediaScannerConnection.MediaScannerConnectionClient {
private MediaScannerConnection mConnection;
private String mPath;
private String mMimeType;
// filePath - where to scan;
// mime type of media to scan i.e. "image/jpeg".
// use "*/*" for any media
public MediaScannerWrapper(Context ctx, String filePath, String mime){
mPath = filePath;
mMimeType = mime;
mConnection = new MediaScannerConnection(ctx, this);
}
// do the scanning
public void scan() {
mConnection.connect();
}
// start the scan when scanner is ready
public void onMediaScannerConnected() {
mConnection.scanFile(mPath, mMimeType);
Log.w("MediaScannerWrapper", "media file scanned: " + mPath);
}
public void onScanCompleted(String path, Uri uri) {
// when scan is completes, update media file tags
}
}
public void walkdir(File dir) {
String pdfPattern = ".pdf";
File[] listFile = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pdfPattern)){
//Do what ever u want
}
}
}
} }
To search on the whole sdcard call this function usingwalkdir(Environment.getExternalStorageDirectory());
Use getExternalStorageDirectory () to get the SD card path. (Do not hardcode it)
Loop through each subfolder, and check files names with your desired extension. Use String endswith() method to check if file name ends with the extension.
Here's a sample code that might help you.
I advice using commons.io library which handles symbolic links and extension resolution as well.
Task to scan for files with extensions:
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ScanTask extends AsyncTask<String,Void,ScanTask.Result> {
#Override
protected Result doInBackground(String... extensions) {
if(extensions == null){
extensions = new String[0];
}
List<File> files = new ArrayList<File>();
boolean success = false;
String status = "";
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
try {
files.addAll(FileUtils.listFiles(Environment.getExternalStorageDirectory(), extensions, true));
success = true;
status = "ok";
} catch (Exception e) {
Log.e("MyApp","File error:",e);
success = false;
status = "Scan error";
}
}else {
success = false;
status = "External storage not available";
}
return new Result(success,status,files);
}
public static class Result{
public final boolean success;
public final String message;
public final List<File> files;
public Result(boolean success, String message,List<File> files) {
this.success = success;
this.message = message;
this.files = files;
}
}
}
Usage:
ScanTask task = new ScanTask(){
#Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
if(result.success){
List<File> files = result.files;
//--do something with files--
}else {
String error = result.message;
//--do something with error message--
}
}
};
task.execute("mp3","jpeg");
You can use this code:
here is the link.
/**
* Class to filter files which are having .mp3 extension
* */
//you can choose the filter for me i put .mp3
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".pdf" ) || name.endsWith(".docs" )) || name.endsWith(".3gp" ) ;
}
}

Categories

Resources