Can't write file in external storage in Android - android

Please check the code below.
I am not able to copy a resource file to external storage in android phone.
Though, i'm able to copy using the code i've commented but I want to know the problem with my original code.
public class ExternalData extends Activity implements OnItemSelectedListener,
OnClickListener {
TextView canRead = null;
TextView canWrite = null;
String state = null;
boolean canR, canW;
EditText userEnteredFileName;
Button bConfirm, bSaveAs;
Spinner spinner = null;
String[] stuff = { "Music", "Pictures", "Downloads" };
File path = null;
File file = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.externaldata);
canRead = (TextView) findViewById(R.id.tvCanRead);
canWrite = (TextView) findViewById(R.id.tvCanWrite);
userEnteredFileName = (EditText) findViewById(R.id.etUserEnteredFileName);
bConfirm = (Button) findViewById(R.id.bConfirm);
bSaveAs = (Button) findViewById(R.id.bSaveAs);
bConfirm.setOnClickListener(this);
bSaveAs.setOnClickListener(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, stuff);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
break;
case 1:
path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
break;
case 2:
path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
break;
}
}
public void checkState() {
state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
canRead.setText("Can Read: true");
canWrite.setText("Can Write: true");
canR = canW = true;
} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
canRead.setText("Can Read: true");
canWrite.setText("Can Write: false");
canR = true;
canW = false;
} else {
canRead.setText("Can Read: false");
canWrite.setText("Can Write: false");
canR = canW = false;
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bConfirm:
bSaveAs.setVisibility(View.VISIBLE);
break;
case R.id.bSaveAs:
checkState();
if(canR == canW == true){
file = new File (path, userEnteredFileName.getText().toString() + "/");
try {
if(!file.exists()){
boolean success = file.mkdirs();
if(success){
Toast.makeText(ExternalData.this, "File created", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ExternalData.this, "Not able to create file", Toast.LENGTH_LONG).show();
}
}
InputStream fis = getResources().openRawResource(R.drawable.darthvader);
/* this works....but wats wrong with the original code
file = new File(file, "darthVader.png");
if(!file.exists()){
file.createNewFile();
}
*/
FileOutputStream fos = new FileOutputStream(file);
byte[] data = new byte[fis.available()];
fis.read(data);
fos.write(data);
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(ExternalData.this, "FilNOT", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(ExternalData.this, "IO", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Did you request the permission in your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

see this example for How to write file in sdcard (external storage)
InputStream input;
try {
URL url = new URL (strURL);
input = url.openStream();
byte[] buffer = new byte[1500];
OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
finally
{
output.close();
buffer=null;
}
don't forget to give permisson in manifeast file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

Android Toast did not show after open Gallery and pick image

I want to show Toast (or progress bar) when clicking on the button "btnSearchImg". If before upload image, button clicked say "first pick image from gallary" and if after upload image clicked say "waiting". the toast before uploading image work fine but after uploading didn't work fine! my entire Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_by_image);
Toasty.Config.getInstance().setTextSize(15).apply();
mSharedPreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.putString(PREF_SKIP,null);
if(mSharedPreferences.contains(PREF_SKIP)){
Log.i("payment", "true");
} else {
try {
}catch (Exception e){
Toast.makeText(getApplicationContext(), "ERORR", Toast.LENGTH_LONG).show();
}
}
context = getApplicationContext();
pbImgRetrvialProccess = (ProgressBar)findViewById(R.id.pbImgRetrvialProccess);
tvPermissionLoadImg = (TextView)findViewById(R.id.tvPermissionLoadImg);
tvPermissionLoadImg.setTypeface(Base.getIranSansFont());
TextView tvSearchImageToolBarText = (TextView) findViewById(R.id.tvSearchImageToolBarText);
tvSearchImageToolBarText.setTypeface(Base.getIranSansFont());
ivGalleryImgLoad = (ImageView) findViewById(R.id.ivGalleryImgLoad);
btnSearchImgLoad = (Button) findViewById(R.id.btnSearchImgLoad);
btnSearchImg = (Button) findViewById(R.id.btnSearchImg);
btnSearchImgLoad.setOnClickListener(this);
btnSearchImg.setOnClickListener(this);
}
public StringBuilder uniformQuantization( File filePath ){...}
private StringBuilder chHistogram( Mat newImage ){...}
private void CopyAssets(String filename){...}
private void copyFile(InputStream in, OutputStream out) throws IOException {...}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearchImgLoad:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);}
OpenGallery();
break;
case R.id.btnSearchImg:
Toasty.success(getBaseContext(), "Waiting...", Toast.LENGTH_LONG).show();
FindSimilarRequestedImage();
break;
}
}
private void OpenGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE && data != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);
} else {
selectedImageUri = data.getData();
ivGalleryImgLoad.setImageURI(selectedImageUri);
tvPermissionLoadImg.setVisibility(View.INVISIBLE);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private void dateiLesenStringBuilder() {
FEATURE_PATH = context.getCacheDir().getPath() + "/" + FEATURE_NAME;
try {
FileOutputStream out = new FileOutputStream(FEATURE_PATH);
InputStream in = context.getAssets().open("coins/"+FEATURE_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0){
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
final File featureList = new File(FEATURE_PATH);
Runnable runner = new Runnable() {
BufferedReader in = null;
#Override
public void run() {
try {
String sCurrentLine;
int lines = 0;
BufferedReader newbw = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
while (newbw.readLine() != null)
lines++;
in = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
ArrayList<Double> nDistVal = new ArrayList<Double>();
ArrayList<String> nImagePath = new ArrayList<String>();
int count = 0;
while ((sCurrentLine = in.readLine()) != null) {
String[] featX = sCurrentLine.split(";")[1].split(" ");
nImagePath.add(sCurrentLine.split(";")[0]);
nDistVal.add(Distance.distL2(featX, queryFeatureX.toString().split(" ")));
count++;
}
ArrayList<Double> nstore = new ArrayList<Double>(nDistVal); // may need to be new ArrayList(nfit)
double maxDistVal = Collections.max(nDistVal);
Collections.sort(nDistVal);
sortedNImagePath = new ArrayList<String>();
for (int n = 0; n < nDistVal.size(); n++) {
int index = nstore.indexOf(nDistVal.get(n));
sortedNImagePath.add(nImagePath.get(index));
sortedNImageDistanceValues.add(String.valueOf(nDistVal.get(n) / maxDistVal));
String filePath = sortedNImagePath.get(0);
String minDistanceImg = sortedNImageDistanceValues.get(n);
FileNameFromPath = filePath.substring(filePath.lastIndexOf("/") + 1);
System.out.println("Distance values -> " + FileNameFromPath.toString());
System.out.println("Distance values -> " + minDistanceImg.toString());
}
} catch (Exception ex) {
String x = ex.getMessage();
System.out.println("ERORR" + x);
}
if (in != null) try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
Intent imgSearchedCoinNameIntent = new Intent(SearchByImageActivity.this, ImageSearchedCoinActivity.class);
imgSearchedCoinNameIntent.putExtra("imgSearchedCoinName", FileNameFromPath);
startActivity(imgSearchedCoinNameIntent);
}
}
};
Thread t = new Thread(runner, "Code Executer");
t.start();
}
}
If I put the "Waiting..." Toast after the FindSimilarRequestedImage() the toast will show up, but I need the toast show immediately after clicking on the btnSearchImg.
NOTE: Also in the dateiLesenStringBuilder() I removed the thread t that this part of code runs in normal flow and serial, but nothing changes!
Instead of toast use logcat to see if they run sequentially or not, maybe toast takes time to run
I solved this problem by putting the part of code in delay like below:
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
pbImgRetrvialProccess.setVisibility(View.VISIBLE);
Toasty.success(getBaseContext(), "Waiting ...", Toast.LENGTH_LONG).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
}
}, 5000);
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
Now before destroying activity throw functions, I first show the toast, then run other functions!

In android, how to print without printer plugins

In android, can we add printer plugins inside application memory or there jar file inside asset folder, and try to call it from application, to create mobile printing.
As I find
> Print Share Application option only. Any other way without Google cloud or any cloud printing.
This is working for me,I am passing pdf file to printer it is
printing!!
class WifiPrint extends Activity { TextView printer_name, gate_way,
printer_port; int port = 9100; WifiManager wifi = null;
android.net.DhcpInfo d; String gateway_ip = "";
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_print); wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE); printer_name = (TextView)
findViewById(R.id.textView1); gate_way = (TextView)
findViewById(R.id.textView2); printer_port = (TextView)
findViewById(R.id.textView3);
/* de.lohndirekt.print.IppPrintService svc = new IppPrintService(printerURI); InputStream stream = new
BufferedInputStream(new FileInputStream("image.epl")); DocFlavor
flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc myDoc = new
SimpleDoc(stream, flavor, null); DocPrintJob job =
svc.createPrintJob(); job.print(myDoc, null);*/
}
#Override public boolean onCreateOptionsMenu(Menu menu) { //
Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.wifi_print, menu); return true;
}
public void wifisettings(View v) { startActivityForResult(new
Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS), 0); }
public void connectSocket(View v) {
/*Uri filepath=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pdfsample); Toast.makeText(this, filepath.getPath(), Toast.LENGTH_LONG).show(); */ ClientThread clientThread = new
ClientThread(""); Thread clientstartThread = new
Thread(clientThread); clientstartThread.start(); }
public String intToIp(int i) { return ((i & 0xFF) + "." + ((i >> 8)
& 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + ((i >> 24) & 0xFF)); }
#Override protected void onActivityResult(int requestCode, int
resultCode, Intent data) { // TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data); if
(requestCode == 0) { WifiInfo wifiinfo = wifi.getConnectionInfo();
d = wifi.getDhcpInfo();
printer_name.setText("Name:" + wifiinfo.getSSID()); gateway_ip =
intToIp(d.gateway); gate_way.setText("Printer Ip:" + gateway_ip);
printer_port.setText("Port:" + port);
} }
public File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("/sdcard/testpdf.pdf");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null; }
class ClientThread implements Runnable { String filepath = "";
BufferedInputStream bis = null; FileInputStream fis;
Socket socket;
public ClientThread(String filename) { filepath = filename; }
#Override public void run() { // TODO Auto-generated method
stub try {
InputStream in = getResources().openRawResource(R.raw.pdfsample);
createFileFromInputStream(in);
File pdfFile = new File("/sdcard/testpdf.pdf");
byte[] mybytearray = new byte[(int) pdfFile.length()];
socket = new Socket(gateway_ip, port);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(socket.isConnected()){
Toast.makeText(WifiPrint.this,
"Socket Connected",
Toast.LENGTH_LONG).show();
}
}
});
fis = new FileInputStream(pdfFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (bis != null) {
bis.close();
os.close();
socket.close();
fis.close();
}
} catch (final UnknownHostException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"UnHost Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"Io Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } finally {
try {
if (bis != null) {
bis.close();
socket.close();
fis.close();
}
} catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(
WifiPrint.this,
"Io Exeption in Closing Socket"
+ e.getMessage(), Toast.LENGTH_LONG)
.show();
}
});
} } }
}
}
In manifest file : just add:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.wifi" />
Yes!!!
In Android 4.4 (API level 19) and higher, the framework provides services for printing images and documents directly from Android applications.
/**
* To print image / photo
*/
private void printPhoto() {
// Get a PrintHelper instance
PrintHelper photoPrinter = new PrintHelper(this);
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
// get image from mipmap folder
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
// provide job name (which will be displayed in the print queue) and bitmap
photoPrinter.printBitmap("droids.jpg - test print", bitmap);
}
Reference for print html and custom document

Retrieve previous inputs Android

I am currently working on a project which requires me to enter and store user's input. Is there any way that I could do so that I can retrieve the previous records as well rather than the current record?
Code
package com.example;
// imports
public class Testing extends Activity {
String tag = "Testing";
EditText amount;
Uri rResult = null;
int request_Code = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testyourself);
amount = (EditText) findViewById(R.id.etUserInput);
Button saveButton = (Button) findViewById(R.id.btnSave);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.example.Result");
Bundle extras = new Bundle();
extras.putString("amount", amount.getText().toString());
intent.putExtras(extras);
startActivityForResult(intent, request_Code);
}
});
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
saveAsText(); // Step E.1
Log.d(tag, "In the onPause() event");
}
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
retrieveText(); // Step E.1
Log.d(tag, "In the onResume() event");
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
public void saveAsText() {
String line = amount.getText().toString();
if (rResult != null)
line += "|" + rResult;
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter pw = null;
try {
String path = Environment.getExternalStorageDirectory().getPath();
fw = new FileWriter(path + "/exercise.txt");
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.println(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pw != null)
pw.close();
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}// saveAsText
public void retrieveText() {
FileReader fr = null;
BufferedReader br = null;
try {
String line;
String path = Environment.getExternalStorageDirectory().getPath();
fr = new FileReader(path + "/exercise.txt");
br = new BufferedReader(fr);
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, "|");
pullup.setText(st.nextToken());
bench.setText(st.nextToken());
String rResult;
if (st.hasMoreTokens())
rResult = st.nextToken();
else
rResult = "";
Log.d(tag, "readAsText: " + line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Results Page
public class Result extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Bundle bundle = getIntent().getExtras();
int amount = Integer.parseInt(bundle.getString("amount"));
TextView ResultView = (TextView) findViewById(R.id.userInput);
ResultView.setText(String.valueOf(amount));
}
}
Instead of writing to a file you can use SharedPreferences which allows you to store information such as user inputs or statistics until explicitly removed. Even if you close your app and re-open it the information that you save using SharedPreferences will remain.
The selected answer for this question is a great example of creating a helper class for SharedPreferences that will allow you to easily save, retrieve, and delete information.
Assuming that you want to save an int value.
If your save and retrieve methods in your helper class are:
public void saveAmount(String key, int amount) {
_prefsEditor.putInt(key,amount);
_prefsEditor.commit();
}
public int getAmount(String key) {
return _sharedPrefs.getInt(key,0); //returns 0 if nothing is found
}
and you have an ArrayList of ints like so:
ArrayList<int> arrayList = new ArrayList<int>();
arrayList.add(123);
arrayList.add(231);
arrayList.add(312); //These are just placeholder values.
then you can create a loop to save:
private AppPreferences _appPrefs;
.
.
.
for(int i = 0; i < arrayList.size(); i++) {
_appPrefs.saveAmount(i,arrayList.get(i));
}
Note that in the above method the keys for the elements are just the indices of the elements within the array.
In order to retrieve the information and recreate the ArrayList you need to first save the length of the ArrayList in shared preferences as well.
public void saveLength(int length) {
_prefsEditor.putInt("length", length);
_prefsEditor.commit();
}
public int getLength() {
return _sharedPrefs.getInt("length",0);
}
then you can create a loop to retrieve:
ArrayList<int> arrayList = new ArrayList<int>();
.
.
.
for(int i = 0; i < _appPrefs.getLength(); i++) {
arrayList.add(getAmount("" + i));
}

How to set on button backup/restore functionality in sqlite database ?

I want to set on button click events backup my applications data on SD-Card.
This is my code :
shv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(SecondActivity.this, "backup Button press",Toast.LENGTH_LONG).show();
boolean rc = MyDatabaseTools.backup();
System.out.println(rc);
if(rc==true)
{
Toast.makeText(SecondActivity.this, "backup Successfully",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(SecondActivity.this, "backup error",Toast.LENGTH_LONG).show();
}
}
});
I proceed like this :
public class MyDatabaseTools {
private String appName = "";
private String packageName = "";
public static boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/<com.example.judgedetail>/databases/ado.db");
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), "ADOBOOK" + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, "ado.db");
try {
fileBackup.createNewFile();
/*Files.copyFile(file, fileBackup);*/ //got error here dis line not work
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private static boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public MyDatabaseTools(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}
Files.copyFile(file, fileBackup);
This line got error.
How shall I solve this ?
Please help.
Try this:
public void writeToSD() throws IOException {
File f=new File("/data/data/com.YourPackageName/databases/DBName");
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream(f);
fos=new FileOutputStream("/mnt/sdcard/dump.db");
while(true){
int i=fis.read();
if(i!=-1){
fos.write(i);
}
else{
break;
}
}
fos.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
fos.close();
fis.close();
}
catch(IOException ioe){
System.out.println(ioe);
}
}
}
I don't know where you copied that code from, but either you or the poster missed something. Files.copyFile() is no existing Android API function, and I guess that's what you describe as the line being not working.
You'll have to copy your file using another method, I'd suggest one like this:
https://stackoverflow.com/a/9293885/1691231

Transferring files from usb to internal memory?

I am making a android app when I plug a flash drive into my tablet or phone via OTG usb, it will transfer the files off of it to a specified location. Now, it will transfer if I specify a file name, but how can I get it to transfer all the files without having to specify a name? I am using fileinput/fileoutput with byte array.
#SuppressLint("SdCardPath")
public class filetransfer extends Activity {
Button btnsend;
String extstorage = Environment.getExternalStorageDirectory().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityfiletransfer);
btnsend = (Button) findViewById(R.id.button1);
final Runtime runtime = Runtime.getRuntime();
try
{
runtime.exec("su -c");
}
catch(Exception e)
{
}
btnsend.setOnClickListener(new View.OnClickListener()
{
Context context = getApplicationContext();
CharSequence scs = "Folder Doesn't Exist, Creating now, Checking for Flash Drive....";
CharSequence mvng = "Folder already exist, checking now for flash drive....";
CharSequence chk1 = "Flash Drive detected, transferring files now.";
CharSequence chk2 = "Flash Drive Is Not Detected";
int duration = Toast.LENGTH_SHORT;
Toast bldng = Toast.makeText(context, scs, duration);
Toast mvfldr = Toast.makeText(context, mvng, duration);
Toast chkffd = Toast.makeText(context, chk1, duration);
Toast chkffd2 = Toast.makeText(context, chk2, duration);
#Override
public void onClick(View arg0)
{
File src = new File(extstorage + "/FILEBACKUP");
File usbdrive = new File(extstorage + "/usbStorage/sda1");
if(!src.exists())
{
src.mkdirs();
bldng.show();
if(!usbdrive.exists())
{
chkffd2.show();
}
else
{
chkffd.show();
copyfiles();
}
}
else
{
mvfldr.show();
if(!usbdrive.exists())
{
chkffd2.show();
}
else
{
chkffd.show();
copyfiles();
}
}
}
private void copyfiles()
{
String pathofd = "/sdcard/usbStorage/sda1";
String internalpath = "/sdcard/FILEBACKUP";
File dir = new File(pathofd);
File[] files = dir.listFiles();
for (File afile : files)
{
if(afile.isFile())
{
copyFile(afile.getAbsolutePath(), internalpath, afile.getName());
}
}
try
{
}
/*OutputStream myoutput = new FileOutputStream("/sdcard/FILEBACKUP");
InputStream myinput = new FileInputStream("/sdcard/usbStorage/");
byte[] buffer = new byte[1024];
int length;
while((length=myinput.read(buffer))>0)
{
myoutput.write(buffer);
}
myoutput.flush();
myoutput.close();
myinput.close();
}*/
catch(Exception e)
{
}
}
private void copyFile(String absolutePath, String internalpath,
String name) {
// TODO Auto-generated method stub
try
{
OutputStream myoutput = new FileOutputStream(extstorage + "/FILEBACKUP/");
InputStream myinput = new FileInputStream(extstorage + "/usbStorage/sda1");
byte[] buffer = new byte[1024];
int length;
while((length=myinput.read(buffer))>0)
{
myoutput.write(buffer, 0, length);
}
myoutput.flush();
myoutput.close();
myinput.close();
}
catch(Exception e)
{
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activityfiletransfer,
menu);
return true;
}
}
Just list the files in the directory:
String pathOfFlashDrive = <path of flash drive goes here>;
String internalPath = <internal destination path goes here>;
File dir = new File( pathOfFlashDrive );
File[] files = dir.listFiles();
for( File aFile : files ) {
if( aFile.isFile() ) {
copyFile( aFile.getAbsolutePath(), internalPath + aFile.getName() );
}
}

Categories

Resources