1

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

saiRam89
  • 325
  • 7
  • 20
  • Did you check if getFilesDir().getAbsolutePath() +"/"+filename this path having your Robottoo.ttf ? – sushant gosavi Aug 16 '17 at 05:39
  • ill suggest you to put this ttf file in assets folder than use getAssets() to get ttf file and use it – sushant gosavi Aug 16 '17 at 05:40
  • @sushantgosavi yes there is a file in data/data/com.customfonts/Robotoo.ttf in this path but its searching file in /data/user/0/com.customfonts/files/Robottoo.ttf that's y showing file not found exception. but i was confused why its searching in wrong path – saiRam89 Aug 16 '17 at 05:43
  • can u share code for `getFilesDir()` method? – rockstar Aug 16 '17 at 05:53
  • `data/data/com.customfonts/Robotoo.ttf` this path is shown by your emulator path and `/data/user/0/com.customfonts/files/Robottoo.ttf ` this is for device path. – rockstar Aug 16 '17 at 06:01
  • in your device path `files/Robottoo.ttf ` can i ask for extra `files` in your path. – rockstar Aug 16 '17 at 06:02
  • Yes i know i am running on emulator only but it searching /data/user/0/com.customfonts/files/Robottoo.ttf file in this path – saiRam89 Aug 16 '17 at 06:03
  • ok @sowmya i want to ask for extra `files` in your device directory "_package_name`/files/`_font_name.ttf" . – rockstar Aug 16 '17 at 06:06
  • can u update code for `getFilesDir()` method? – rockstar Aug 16 '17 at 06:07
  • extra package name i can't get ur question? – saiRam89 Aug 16 '17 at 06:08
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/152008/discussion-between-rockstar-and-sowmya). – rockstar Aug 16 '17 at 06:11
  • Device Path: `/data/user/0/com.customfonts/files/Robottoo.ttf` Emulator Path: `data/data/com.customfonts/Robotoo.ttf` ---------- in your `Device Path` why `/files/` is extra. – rockstar Aug 16 '17 at 07:11
  • Its's showing its emulator data/data/com.customfonts/files/Robotoo.ttf – saiRam89 Aug 16 '17 at 07:20
  • ok! for `font = Typeface.createFromFile(getFilesDir().getAbsolutePath() +"/"+filename);` line let me know about `getFilesDir()` method. so please update code for `getFilesDir()` method. – rockstar Aug 16 '17 at 07:39

3 Answers3

0

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

sushant gosavi
  • 2,781
  • 3
  • 26
  • 47
  • Thanks its working but file is not shows for the user it will be stores as internal storage – saiRam89 Aug 16 '17 at 08:35
  • you are using private folder of app so it will not visible for user if you want file should visible for user than use Environment.getExternalStorageDirectory() insted of getFilesDir() so it will create file in your internal storage – sushant gosavi Aug 16 '17 at 09:19
  • although user can view it if you go to setting check Show Hidden files. Than go to your Memory->android->data->data->com.yourPakageName->fileName – sushant gosavi Aug 16 '17 at 09:22
  • sushant gosavi thnks it's working but it not storing with extension – saiRam89 Aug 16 '17 at 11:00
0

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>
rockstar
  • 477
  • 3
  • 21
-1

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);
Athar Iqbal
  • 350
  • 2
  • 12