Saving file to storage programmatically - android

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>

Related

HttpURLConnection problem in Android Studio while loading an image from internet

I'm trying to download the image from URL: "http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png
and after that I want to display it in image view. but continuously the error in HttpURLConnection is occurring
On clicking of a button(download function is called) it should remove the previous image and load the new image from the url
I have tried using internet on emulator and its working fine. emulator and my pc is connected to internet. I have also asked permissions in AndroidMenifest. but nothing is solving the problem.
package com.example.web;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public class ImageDownloader extends AsyncTask<String,Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
Log.i("Error","Error encountered");
}
return null;
}
}
public void download(View view) {
imageView = findViewById(R.id.imageView3);
imageView.setImageResource(0);
ImageDownloader imageDownloader = new ImageDownloader();
try {
Bitmap bitmap = imageDownloader.execute("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Permissions in AndroidMenifiest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
As Per Your Code I write Down New One just Replace it With Existing One
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public class ImageDownloader extends AsyncTask<String,Void, Bitmap> {
OutputStream output;
#Override
protected Bitmap doInBackground(String... strings) {
int count;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
try {
URL url = new URL(strings[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "DownloadedFile" + ts + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
if (Math.min(cur, 100) > 98) {
try {
// Sleep for 5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
public void download(View view) {
imageView = findViewById(R.id.imageView3);
imageView.setImageResource(0);
ImageDownloader imageDownloader = new ImageDownloader();
try {
Bitmap bitmap = imageDownloader.execute("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If you want to download Image and store in Your Local Storage then Use Below Code.
Here I create One DownloadFileFromURL.class File which is my AsyncTask So downloading processed Without Interruption.
public DownloadFileFromURL(Context context) {
this.context = context;
}
protected void onPreExecute() {
super.onPreExecute();
Log.e(TAG, "onPreExecute: Download started");
}
#Override
protected String doInBackground(String... f_url) {
int count;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "Your Folder Name" + ts + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
if (Math.min(cur, 100) > 98) {
try {
// Sleep for 5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Now Call Above File in Your Activity or When You want. At the time of Calling this AsyncTask pass Your URLto download images.
new DownloadFileFromURL(context).execute("Your Download URL");

File not downloading from url in Android

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
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;
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf( '/' ),downloadUrl.length());//Create file name by picking download file name from URL
Log.e(TAG, downloadFileName);
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Downloading...");
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
Toast.makeText(context, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Download Failed" +e);
//Change button text if exception occurs
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
#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
//If Connection response is not OK then show Logs
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 = new File(
Environment.getExternalStorageDirectory() + "/"
+ "NKDROID FILES");
} else
Toast.makeText(context, "Oops!! There is no 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
while ((len1 = is.read(buffer)) != -1) {
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;
}
}
}
I have done the following coding to download a file from a url... But when I run the app it stucks on the downloading screen... I am trying to download the file in the internal storage... I have tried every possible way to download the from ur;l... If anyone can suggests any changes int he above code or anyother code sequence I can use...
I don't know what's the problem with your code.. But you can use the following steps to solve your problem.... Just open your pdf url in android chrome... The code is mentioned below....
try {
Intent i = new Intent("android.intent.action.MAIN");
i.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
i.addCategory("android.intent.category.LAUNCHER");
i.setData(Uri.parse("your pdf url"));
startActivity(i);
}
catch(ActivityNotFoundException e) {
// Chrome is not installed
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("your pdf url"));
startActivity(i);
}

PDF printing view issue

I have tried in two ways,
1) Am creating a WebView and loading my pdf document, and my application is almost done with its part of the printing process. But in that am facing printing issue.
Its not with full A4 sheet view.Can anyone please help,The following code i have used,
public void createWebPagePrint(WebView webView) {
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
printAdapter = webView.createPrintDocumentAdapter();
String jobName = getString(R.string.app_name) + " Document";
PrintAttributes.Builder builder = null;
builder = new PrintAttributes.Builder();
builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
PrintJob printJob = null;
printJob = printManager.print(jobName, printAdapter, builder.build());
if (printJob.isCompleted()) {
Toast.makeText(getApplicationContext(), "Print Complete", Toast.LENGTH_LONG).show();
} else if (printJob.isFailed()) {
Toast.makeText(getApplicationContext(), "Print Failed", Toast.LENGTH_LONG).show();
}
builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setResolution(new PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 1024, 720))
.setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
}
}
Note:
https://developer.android.com/training/printing/html-docs.html
And some times while loading pdf its not displaying.
2) I have tried using with pdf view lib ,
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
But that time am getting better view compared to webview. The problem is only visible view is drawing on canvas.The print view is not clear.Its not readable.I have given the page count, So according to the page count its repeating the pages but print view is same as in first page.The following view am getting while printing.
This is my sample code,
code
If anyone know please help me.
The above procedure is very hard.Even am not getting solution for that.After that i come up with a solution and its working perfectly for me.
1) To view PDF file no need to load with webview or external pdf libraries.Just download the pdf file and view it with default pdf viewer.The below code i have used,
To download a file,
import android.app.Activity;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory, Activity activity){
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();
}
}
}
private class DownloadFile extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0];
String fileName = strings[1];
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "Test");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile,InventoryStockActivity.this);
return null;
}
}
public void download(String viewUrl) {
new DownloadFile().execute(viewUrl, "Test.pdf");
Log.d("Download complete", "----------");
}
To view a pdf file;
public void view() {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Test/" + "Test.pdf");
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(InventoryStockActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
In manifest,
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
And when its open default pdf viewer, there will be print menu.Just print from there.

Typeface.createFromFile file not found?

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);

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);

Categories

Resources