Typeface.createFromFile file not found? - android

Before that I post question and get solution too.But Data stored in data/data/com.customfonts/Robotoo.ttf but its searching file in wrong path and throwing Font not found /data/user/0/com.customfonts/files/Robottoo.ttf
Downloading file from url error " java.io.FileNotFoundException: /Users/Documents (No such file or directory)" but I facing file not found exception.Here this my code I have tried.
// Storing file
private class DownloadingTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(new File(getFilesDir(),"Robotto.ttf"));
Log.i("Download","complete");
Log.i("File",getFilesDir().getAbsolutePath());
( I/File: /data/user/0/com.customfonts/files)//files stores under
Log.i("FOS",""+fos.toString());
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
}
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String filename="Robottoo.ttf";
getTypeface(filename);
}
});
private Typeface getTypeface(String filename)
{
Typeface font;
try
{
font = Typeface.createFromFile(getFilesDir().getAbsolutePath() +"/"+filename);
Log.i("FOnt found",""+font);
(java.lang.RuntimeException: Font not found /data/user/0/com.customfonts/files/Robotoo.ttf)
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return font;
}
java.lang.RuntimeException: Font not found /data/user/0/com.customfonts/files/Robottoo.ttf

Try to use getExternalFilesDir() method insted of getFilesDir()
getExternalFilesDir method give you the path of your app private folder directory where you store your ttf file for more info check this out.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),filename);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
font = Typeface.createFromFile(file.getPath());
Other Way - Try This ContextWrapper.getFilesDir() check

you can try this way,
1. check directory is exist or not if not then create directory
File rootDirectory;
PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = null;
try {
p = m.getPackageInfo(s, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
s = p.applicationInfo.dataDir;
rootDirectory = new File(s + "/files");
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
String FileName = "Robotto.ttf";
String finalUrl = rootDirectory.getAbsolutePath() + "/" + FileName;
2. Some changes in your code
private class DownloadingTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
File rootDirectory = null;
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(finalUrl);
// Log.i("Download","complete");
// Log.i("File",getFilesDir().getAbsolutePath());
// ( I/File: /data/user/0/com.customfonts/files)//files stores under
// Log.i("FOS",""+fos.toString());
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
}
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String filename="Robottoo.ttf";
getTypeface(finalUrl);
}
});
private Typeface getTypeface(String finalUrl)
{
Typeface font;
try
{
font = Typeface.createFromFile(finalUrl);
// Log.i("FOnt found",""+font);
// (java.lang.RuntimeException: Font not found /data/user/0/com.customfonts/files/Robotoo.ttf)
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return font;
}
I hope this will help you.
Update 1:
Once check your file name "Robotto.ttf" this is different name.
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String filename="Robottoo.ttf";
getTypeface(filename);
}
});
you should use
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String filename="Robotto.ttf";
getTypeface(filename);
}
});
Update 2:
check your application having "WRITE_EXTERNAL_STORAGE" permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
for more details, you can go threw Write a file in external storage in Android
Update 3: (just copy and paste code this is working)
1. WriteSDCard.java
import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class WriteSDCard extends AppCompatActivity {
String finalUrl;
private TextView tv;
private String fonturl= "http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isStoragePermissionGranted()){
checkExternalMedia();
writeToFile();
new DownloadingTask().execute();
}
}
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
private void writeToFile(){
File rootDirectory;
PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = null;
try {
p = m.getPackageInfo(s, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
s = p.applicationInfo.dataDir;
rootDirectory = new File(s + "/files");
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
String FileName = "Roboto-Regular.ttf";
finalUrl= rootDirectory.getAbsolutePath() + "/" + FileName;
}
private class DownloadingTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(finalUrl); // File you want to save to, It creates Roboto-Regular.ttf in your Internal Storage you got from "getFilesDir() method
Log.i("Download","complete");
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
// outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// super.onPostExecute(aVoid);
File file = new File(finalUrl);
if(file.exists()) {
//something,
Toast.makeText(WriteSDCard.this,"File exists",Toast.LENGTH_SHORT).show();
/**
*
*/
getTypeface();
}
else{
//something
Toast.makeText(WriteSDCard.this,"File Not exists",Toast.LENGTH_SHORT).show();
}
}
}
private Typeface getTypeface()
{
Typeface font;
try
{
font = Typeface.createFromFile(finalUrl);
Log.i("Font found",""+font);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return font;
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Log.v(TAG,"Permission is granted");
return true;
} else {
// Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
// Log.v(TAG,"Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
// Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
}
2. Manifest File
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.download_fontform_url">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".WriteSDCard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

create assets folder in app level hierarchy and paste your .ttf font file inside it.
and use this code to apply font
Typeface face = Typeface.createFromAsset(getAssets(), "font.ttf");
textview.setTypeface(face);

Related

Saving file to storage programmatically

I have tried with the following code: (Previously it was working fine, Now I am testing its not working may be due to android 10 or some other error).
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
public class AboutUs extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new DownloadFile().execute("https://4.img-dpreview.com/files/p/E~TS590x0~articles/3925134721/0266554465.jpeg");
}
private class DownloadFile extends AsyncTask<String,Integer, String> {
private PowerManager.WakeLock mWakeLock;
#Override
protected String doInBackground(String... strings) {
String fileUrl = strings[0];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "MyFolder");
folder.mkdir();
File pdfFile = new File(folder, fileUrl);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else {
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
activity.startActivity(activity.getIntent());
activity.finish();
}
}
}
public static class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have tried with the above code.
I have added WRITE_INTERNAL_STORAGE and also ask run time permission
There were major changes on how files can be accessed on Android 10
See https://developer.android.com/training/data-storage
You need to use MediaStore or Storage Access Framework (SAF), details https://developer.android.com/training/data-storage/shared for files outside of your App's private directories.
As you are storing photo then MediaStore would be the way to access pictures https://developer.android.com/training/data-storage/shared/media
Though as a quick fix is to temporarily opt out https://developer.android.com/training/data-storage/compatibility but this will only work until Android 11
Some better examples at https://proandroiddev.com/working-with-scoped-storage-8a7e7cafea3
Android 10 requered android:requestLegacyExternalStorage="true" in your AndroidManifest file
check this link
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xxx.xxxx">
<application
android:requestLegacyExternalStorage="true">
</application>
</manifest>

How to cancel file downloading from a dialog

When user download a file, I show user a dialog that contain a cancel button.
My problem is when user press the cancel button on dialog file, the downloading process won't be cancel.
I want when user press cancel button either file download complete or not, I the must be delete.
Please explain anyone how I can do this.
Code:
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf( '/' ),downloadUrl.length());
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Integer, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(bookejtemaeat.this);
progressDialog.setMessage("يتم تحميل الملف مرة واحدة يرجى الانتظار ......");
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setCanceledOnTouchOutside(false) ;
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadingTask.this.cancel(true);
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URL
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
final int fileLength = c.getContentLength();
Log.e(TAG, "fileLength " + fileLength);
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = getApplicationContext().getDir(
"NKDROID FILES",Context.MODE_PRIVATE);
} else
Toast.makeText(context, "Tidak ada SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
long total = 0;
while ((len1 = is.read(buffer)) != -1) {
total += len1;
final long total_tmp = total;
Log.e(TAG, "progressDialog " + (total*100/fileLength));
publishProgress((int) (total * 100 / fileLength));
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress((int) (total_tmp*100/fileLength));
}
});
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
}
Just add a boolean value in your class that will let you control while loop. like
while (continueDownload&& (len1 = is.read(buffer)) != -1) {
and make this work like
yourDwnloadTask.setContinueDownload(false);
and handle your output file
if (!continueDownload && outputFile.exists()) {
try {
outputFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
If you ask me full code.
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTask {
private static final String TAG = "Download Task";
private Context context;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
private boolean continueDownload = true;
public void setContinueDownload(boolean continueDownload) {
this.continueDownload = continueDownload;
}
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());
continueDownload = true;
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Integer, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(bookejtemaeat.this);
progressDialog.setMessage("يتم تحميل الملف مرة واحدة يرجى الانتظار ......");
progressDialog.setIndeterminate(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadingTask.this.cancel(true);
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URL
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
final int fileLength = c.getContentLength();
Log.e(TAG, "fileLength " + fileLength);
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = getApplicationContext().getDir(
"NKDROID FILES", Context.MODE_PRIVATE);
} else
Toast.makeText(context, "Tidak ada SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
long total = 0;
while (continueDownload && (len1 = is.read(buffer)) != -1) {
total += len1;
final long total_tmp = total;
Log.e(TAG, "progressDialog " + (total * 100 / fileLength));
publishProgress((int) (total * 100 / fileLength));
runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress((int) (total_tmp * 100 / fileLength));
}
});
fos.write(buffer, 0, len1);//Write new file
}
if (!continueDownload && outputFile.exists()) {
try {
outputFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
}

Writing to a file, but file is empty when I read it in [duplicate]

I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.
Here's the code:
package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num = (EditText) findViewById(R.id.sNum);
Button ch = (Button) findViewById(R.id.rButton);
TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String opname = operator.getNetworkOperatorName();
TextView status = (TextView) findViewById(R.id.setStatus);
final EditText ID = (EditText) findViewById(R.id.IQID);
Button save = (Button) findViewById(R.id.sButton);
final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get Text From EditText "ID" And Save It To Internal Memory
}
});
if (opname.contentEquals("zain SA")) {
status.setText("Your Network Is: " + opname);
} else {
status.setText("No Network");
}
ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Read From The Saved File Here And Append It To String "myID"
String hash = Uri.encode("#");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
+ hash));
startActivity(intent);
}
});
}
I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
Just a a bit modifications on reading string from a file method for more performance
private String readFromFile(Context context, String fileName) {
if (context == null) {
return null;
}
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int size = inputStream.available();
char[] buffer = new char[size];
inputStreamReader.read(buffer);
inputStream.close();
ret = new String(buffer);
}
}catch (Exception e) {
e.printStackTrace();
}
return ret;
}
The Kotlin way by using builtin Extension function on File
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Kotlin
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
We can use this code to write String to a file
public static void writeTextToFile(final String filename, final String data) {
File file = new File(filename);
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write(data.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then in the Main code, we use this, for example
writeTextToFile(getExternalFilesDir("/").getAbsolutePath() + "/output.txt", "my-example-text");
After that, check the file at Android/data/<package-name>/files.
The easiest way to append to a text file in kotlin:
val directory = File(context.filesDir, "LogsToSendToNextMunich").apply {
mkdirs()
}
val file = File(directory,"Logs.txt")
file.appendText("You new text")
If you want to just write to the file:
yourFile.writeText("You new text")
writing anything to the files, using bytes:
FileOutputStream(file).use {
it.write("Some text for example".encodeToByteArray())
}

image is not saving to android device in Sd card

package com.lociiapp;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.example.imageslideshow.R;
public class recciverfullimageActivty extends Activity {
String reccvierid;
Context context;
ImageView recciverimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent myintent = getIntent();
reccvierid = myintent.getStringExtra("reccvierid");
recciverimage = (ImageView) findViewById(R.id.recciverImage);
String myfinalpathare = reccvierid;
Toast.makeText(getApplicationContext(), reccvierid, 10000).show();
String imagepathe = "http://api.lociiapp.com/TransientStorage/"
+ myfinalpathare + ".jpg";
try {
saveImage(imagepathe);
Log.e("****************************", "Sucess");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void saveImage(String urlPath) throws Exception {
String fileName = "test.jpg";
File folder = new File("/sdcard/LociiImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder, fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection()
.getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with
// bytes from the data
// input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is My code I am trying to save Image which is coming from server we have Image Url . when i Run this Code then Folder is creating in Sd card But image is not downloading on Save in Sd care please help and tell where i am doing wrong .
Your checklist should be as follows:
A. Make sure you have the right permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
B. Move networking and file IO logic to non-UI thread:
new AsyncTask<Params, Progress, Result>() {
#Override protected Result doInBackground() {
saveImage(imagepathe);
}
#Override protected void onPostExecute(String result) {
// update UI here
}
}.execute(params);
C. Do not read one byte at the time. It is probably not the source of your problem but it
does make your solution much slower than it can be:
Instead of:
for(;;) {
fileData[x] = dis.readByte();
}
Do this:
URL u = new URL(url);
URLConnection connection = u.openConnection();
byte[] buffer = new byte[connection.getContentLength()];
stream.readFully(buffer); // <------------- read all at once
stream.close();
D. And , finally, consider using Picasso for the job:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Nowadays you just no not need to write that much code to get were you're going..
Try this..
Call like below instead of saveImage(imagepathe);
myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();
and myAsyncTask.class
class myAsyncTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog dialog;
myAsyncTask()
{
dialog = new ProgressDialog(webview.this);
dialog.setMessage("Loading image...");
dialog.setCancelable(true);
dialog.setIndeterminate(true);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
protected Void doInBackground(Void... arg0) {
try {
InputStream stream = null;
URL url = new URL("http://api.lociiapp.com/TransientStorage/286.jpg");
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File myDir = new File(SDCardRoot + "/LociiImages");
myDir.mkdirs();
File file = new File(myDir,"test.jpg");
FileOutputStream fileOutput = new FileOutputStream(file);
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = stream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
EDIT
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LociiImages/test.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

Can't write an Object. Read-only file system

I'm trying to save this Object, Inventory, to the internal storage. I have the saving and getting methods in the class itself. When I try and call the save method, I end up with the exception. I had the Exception message write to the Logcat, and here's what I got:
08-04 02:32:23.690: VERBOSE/alex(278): /test (Read-only file system)
The file /test is "Read-only file system", but I had allowed writing external storage in the Manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Here's the Inventory class. The last two methods are the save and read methods.
package com.androidbook.inventoryproject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import android.util.Log;
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
int numIngred;;
Ingredient[] ingredients;
ArrayList ingred = new ArrayList<Ingredient>();
public Inventory() {
numIngred = 0;
ingredients = new Ingredient[numIngred];
}
public int getNumIngred() {
return numIngred;
}
public String getIngredientName(int n) {
return ((Ingredient)ingred.get(n)).getName();
}
public Ingredient[] getIngredients() {
return ingredients;
}
public Ingredient getIngredient(int n) {
return (Ingredient)ingred.get(n);
}
public void addIngredient(String iname) {
numIngred++;
ingred.add(new Ingredient(iname));
}
public boolean saveInventory( Inventory inv) {
File suspend_f = new File("test");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(inv);
}
catch (Exception e) {
keep = false;
Log.v("alex", "" + e.getMessage());
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
return keep;
}
public Inventory getInventory() {
File suspend_f = new File("test");
Inventory inven = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try{
fis = new FileInputStream(suspend_f);
ois = new ObjectInputStream(fis);
inven = (Inventory)ois.readObject();
}
catch (Exception e) {
String mess = e.getMessage();
}
finally {
try {
if (fis != null)
fis.close();
if (ois != null)
ois.close();
}
catch (Exception e) { }
}
return inven;
}
}
WRITE_EXTERNAL_STORAGE lets you write to the SD card, not to the filesystem root. You should try this:
File suspend_f = new File(Environment.getExternalStorageDirectory(), "test");
This verifies that the file you are using goes into a writable external folder.
EDIT: there is a bunch of other work you should do to verify that the SD card is available and writable. Read the specs to see how to make your file access robust by checking availability.

Categories

Resources