how to generate a identified filename from url? - java

Now I have to download a file whose url has known. I need to save it to SD card when download action finished. The problem is I should know whether the file is existed before downloading. So I plan to save the file with a identified filename which is generated from url. So when I get the url I can calculate his corresponding filename. Which algorithm should I use?
BTW, JAVA is what I'm using.
Maybe, I have not told my requirement clearly. Fetch the filename "abc.png" from url "www.yahoo.com/abc.png" is not what I need. Because "www.google.com/abc.png" results the same filename. I need to generate a unique filename from url.

full example working ...i tried myself some days ago..
im sure it will help..
package com.imagedownloader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class ImageDownloaderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap=DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img =(ImageView)findViewById(R.id.imageView1);
img.setImageBitmap(bitmap);
}
private Bitmap DownloadImage(String URL) {
// TODO Auto-generated method stub
Bitmap bitmap=null;
InputStream in=null;
try {
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String stingurl) throws IOException {
// TODO Auto-generated method stub
InputStream in=null;
int response=-1;
URL url = new URL(stingurl);
URLConnection conn=url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("not and http exception");
try{
HttpURLConnection httpconn=(HttpURLConnection)conn;
httpconn.setAllowUserInteraction(false);
httpconn.setInstanceFollowRedirects(true);
httpconn.setRequestMethod("GET");
httpconn.connect();
response=httpconn.getResponseCode();
if(response==HttpURLConnection.HTTP_OK)
{
in=httpconn.getInputStream();
}
}
catch(Exception ex)
{throw new IOException("Error connecting"); }
return in;
}
}

Related

Android - HTTP Post request [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
I want to call a POST request, to send some geo information from my android device to my server.
My server use PHP and I want use a php script to save all incoming post requests in my database. My php script works fine when I tried it with curl, but when I want to send some information from my android device I get some network errors.
Here is my error log
12-11 12:08:02.871 10241-10241/local.example.markus.geoapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: local.example.markus.geoapp, PID: 10241
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.getOutputStream(TrackedHttpURLConnection.java:288)
at com.android.tools.profiler.support.network.httpurl.HttpURLConnection$.getOutputStream(HttpURLConnection$.java:212)
at local.example.markus.geoapp.MapsListener.sendPost(MapsListener.java:121)
at local.example.markus.geoapp.MapsListener.onLocationChanged(MapsListener.java:77)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:291)
at android.location.LocationManager$ListenerTransport.-wrap0(Unknown Source:0)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:236)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Here is my java code
package local.example.markus.geoapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
/**
* Created by markus on 04.12.17.
*/
public class MapsListener implements LocationListener {
// Member Variablen
private GoogleMap googleMap;
// Konstruktor
public MapsListener() {
}
// Getter und Setter
public GoogleMap getGoogleMap() {
return googleMap;
}
public void setGoogleMap(GoogleMap googleMap) {
this.googleMap = googleMap;
}
// Interface Methods
#Override
public void onLocationChanged(Location location) {
// Print new Latitide and Logtitude into log
Log.d("INFO", "New Location! Latitude: '" + location.getLatitude() + "', '" + location.getLongitude() + "'");
// Define new Latitude and Logtitude object
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add a new Marker to the Map
this.googleMap.addMarker(new MarkerOptions().position(latLng).title("Lat:" + location.getLatitude() + ", Lng: " + location.getLongitude()));
// Build ca,era position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to north
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
// Animate camera to zoom to the new position with defined settings
this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Log.d("Device ID", this.getDeviceId());
this.sendPost(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private String getDeviceId() {
if (Build.VERSION.SDK_INT <= 25) {
return Build.SERIAL;
} else {
return Build.getSerial();
}
}
private void sendPost(Location location) {
URL url = null;
HttpURLConnection httpURLConnection = null;
OutputStream outputStream = null;
try{
url = new URL("http://example.local");
httpURLConnection = (HttpURLConnection) url.openConnection();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
/*httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("d", this.getDeviceId());
httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude()));
httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude()));
httpURLConnection.setRequestProperty("t", timestamp.toString());
httpURLConnection.setDoOutput(true);*/
outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(Double.toString(location.getLongitude()));
writer.flush();
writer.close();
outputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How I can send some information about POST requests to my php script on http://example.local/gps.php?
The post Sending POST data in Android does not work.
The post Sending POST data in Android does not work.
The above should work absolutely fine else ans would have been not in accepted and upvoted state.
The error what you're getting obvious since missed how the network call is made in that ans
You missed below one.
public class CallAPI extends AsyncTask {
In android or other platforms most of the platforms also network call ui thread is not allowed. In Android AsyncTask is one way making network call off the ui thread.
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask.
public class HttpPost extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
URL url = null;
HttpURLConnection httpURLConnection = null;
OutputStream outputStream = null;
try{
url = new URL("http://example.local");
httpURLConnection = (HttpURLConnection) url.openConnection();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
/*httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("d", this.getDeviceId());
httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude()));
httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude()));
httpURLConnection.setRequestProperty("t", timestamp.toString());
httpURLConnection.setDoOutput(true);*/
outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(Double.toString(location.getLongitude()));
writer.flush();
writer.close();
outputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPostExecute(String result) {
//What you want to do with the result
//Call a callback function for instance
//You can also delete this method if you dont expect a result
}
}

How do i use a URL to set an setImageBitmap for a ImageView?

in manifest:
<uses-permission android:name="android.permission.INTERNET">
in the onCreate method:
webImage = (ImageView) findViewById(R.id.webimage);
String urlImage = "https://thetab.com/blogs.dir/91/files/2017/01/maxresdefault-1.jpg";
// Set setImageBitmap to Bitmap created by getURLBitmap method
webImage.setImageBitmap(getURLBitmap(urlImage));
in the getURLBitmap method:
if(!urlString.isEmpty() || urlString != null) {
InputStream inputStream = null;
// pass the string into a URL object
try {
URL urlForImage = new URL(urlString);
// cast url openConnection into HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) urlForImage.openConnection();
// Set HttpURLConnection setDoInput to true
connection.setDoInput(true);
// Start HttpURLConnection connection
connection.connect();
if(connection.getResponseCode() == 200) {
// Start reading Http inputStream (getInputStream) and use it to initialize a InputStream object
inputStream = connection.getInputStream();
// pass InputStream object into a BitmapFactory's decodeStream (is a static method)
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// set Bitmap object to decodedStream
return bitmap;
}
// return Bitmap
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
I keep getting this error:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.EX.perfectmoment, PID: 26747
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.EX.perfectmoment/com.example.EX.perfectmoment.MemeMainActivity}: android.os.NetworkOnMainThreadException
You are getting this error because you are running a network operation on the UI thread, which is something that is very looked down upon in Android Dev as it often results in an unresponsive UI and thus, a bad user experience. I recommend either creating your own ASyncTask, which would do the network operations in another thread and feed it back to the UI thread, or use one of the many popular image libraries there are for Android, such as Picasso or Glide.
As said in above comment running network task on UI thread in android no longer supported so you have to do UI blocking task on separate thread either using AsyncTask or some other thread mechanism available.
So by using AsynTask you can do it like mention below code snippet.
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity{
ImageView webImage;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webImage = (ImageView) findViewById(R.id.imageView1);
new SetImage().execute();
}
private class SetImage extends AsyncTask<Void, Void, Bitmap>{
final String urlImage = "https://thetab.com/blogs.dir/91/files/2017/01/maxresdefault-1.jpg";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(Void... params) {
Bitmap image = getURLBitmap(urlImage);
return image;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
webImage.setImageBitmap(bitmap);
}
}
private Bitmap getURLBitmap(String urlString){
if(!urlString.isEmpty() || urlString != null) {
InputStream inputStream = null;
// pass the string into a URL object
try {
URL urlForImage = new URL(urlString);
// cast url openConnection into HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) urlForImage.openConnection();
// Set HttpURLConnection setDoInput to true
connection.setDoInput(true);
// Start HttpURLConnection connection
connection.connect();
if(connection.getResponseCode() == 200) {
// Start reading Http inputStream (getInputStream) and use it to initialize a InputStream object
inputStream = connection.getInputStream();
// pass InputStream object into a BitmapFactory's decodeStream (is a static method)
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// set Bitmap object to decodedStream
return bitmap;
}
// return Bitmap
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

VB.Net Server & Android Client (Socket) Send & Receive

I am new to Android programming I wrote a simple Server(VB.NET) / Client(Java/Android) program. Text from Android/Java is send successfully to VB.Net but Response from VB.Net is not received in Android/Java (buffer.readLine() returns null)
Am I missing something?
Here are my Codes
VB.NET (Server)
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim server As New TcpListener(9999)
Dim client As New TcpClient
Dim stream As NetworkStream
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
Me.Text = "Waiting...."
Dim str As String
server.Start()
client = server.AcceptTcpClient
stream = client.GetStream()
Dim r_byt(client.ReceiveBufferSize) As Byte
stream.Read(r_byt, 0, client.ReceiveBufferSize)
Str = Encoding.ASCII.GetString(r_byt)
Label1.Text = str
End Sub
Private Sub Responce_Click(sender As Object, e As EventArgs) Handles Responce.Click
Dim s_byt() As Byte = Encoding.ASCII.GetBytes("Got it" & vbCr)
stream.Write(s_byt, 0, s_byt.Length)
stream.Flush()
stream.Close()
client.Close()
server.Stop()
End Sub
Android/Java(Client)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
Button buttonSend, buttonReceive;
private static Socket socket = null;
PrintStream stream = null;
BufferedReader buffer = null;
String string = "a";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
socket = new Socket("192.168.0.104", 9999);
stream = new PrintStream(socket.getOutputStream());
stream.println("Hi Server...");
buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
string = buffer.readLine();
Log.d("ServerActivity", " - " + string);
buffer.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
It looks like you have a couple of issues:
In the server side, you are trying to read something from the socket
into r_byt, and you are not writing anything to it on cliente side.
When you press the send button on server side, r_byt still null and
that's what you receive on cliente side.
On client side the call to socket read is blocking and after a few
seconds will result in a ANR error (Application not Responding) in
the cliente. You should move the socket read to a different thread
from the UI. The newer Android versions don't even let you read from
a socket in the UI thread.
Regards.

Android - Saving object on internal memory

this code is supposed to create a new user with the username and password he entered and then save that new object to phone memory with the file name matching his email so that in the login method I can look for the file matching the email entered deserialize it, and all his user info would be there... But I keep getting a FileNotFooundException... I really don't understand... please someone help me! :)
Here's the code:
package com.example.eventmanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class CreateAccount extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
}
public void createUserAccount(View v) {
EditText username = (EditText) findViewById(R.id.editText1);
EditText password = (EditText) findViewById(R.id.editText2);
EditText secondPassword = (EditText) findViewById(R.id.editText3);
if (!(password.getText().toString().equals((secondPassword.getText()
.toString())))) {
Toast.makeText(this, "Passwords Don't Match", Toast.LENGTH_LONG).show();
} else {
User newUser = new User(username.getText().toString(), password.getText().toString());
String fileName = newUser.getEmail();
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(newUser);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "FileNotFoundException", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "IOException", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Intent intent = new Intent(this, LoginScreen.class);
startActivity(intent);
Toast.makeText(this, "Account Created Successfully",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_account, menu);
return true;
}
}
Per FileOutputStream documentation: it throws FileNotFoundException in below scenario:
FileNotFoundException - if the file exists but is a directory rather than a regular file OR does not exist but cannot be created, or cannot be opened for any other reason
Please make sure, String fileName = newUser.getEmail().toString(); results in valid file name, which I suspect is the case.
FileOutputStream uses an absolute path which (I think) will default to the root of the internal storage if you only provide a filename - on a normal device, the root of the internal storage will not be accessible.
You should use openFileOutput(String name, int mode) instead. This guarantees creating a file in the internal storage in the area allocated to your own app. To read the file back, use the corresponding openFileInput(String name) method.

Android - Access file from assets \ PDF display

I am trying to retrieve a reference to a file stored in the assets directory to a file named myfile.pdf. I have tried to do it as follows:
File file = new File("android_assest/myfile.pdf);
Log.d("myTag", "" + file.isFile());
Somehow, I get false when the myfile.pdf do exists in the assets directory. I verified it using getAssets().list("") and Log.d() each element in the returned array.
More of which, I am trying to get a reference to a PDF file and then use any PDF viewer, which is already installed on the device, in order to view the PDF.
I guess that since the previous issue (retrieving a reference to the file) returns false then the next snipped code fails:
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("file:///android_asset/myfile.pdf"));
startActivity(i);
Anyone has a clue why I am unable to retrieve a reference to the file? and why I cannot use already installed PDF viewer to display a PDF (after retrieving a reference to the PDF file)?
Thanks.
As Barak said you can copy it out of assets to internal storage or the SD card and open it from there using inbuilt pdf applications.
Following Snippet will help you.
(I have updated this code to write to and read files from internal storage.
But i dont recommend this approach because pdf file can be more than 100mb in size.
So its not recommended to save that huge file into internal storage
Also make sure while saving file to internal storage you use
openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
Then only other applications can read it.
Check following snippet.
package org.sample;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class SampleActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadAssets();
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "git.pdf");
try
{
in = assetManager.open("git.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/git.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
Make sure to include
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in manifest
You can't do it like that. There is no directory structure in an apk, it is just data. The framework knows how to access it (getAssets), but you cannot look for it as a file in a directory.
You can open it as an input stream...
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(myfile.pdf)));
Or you can copy it out of assets to internal storage or the SD card and access it there.
like say Vipul Shah, but in the case for external.
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyReadAssets();
}
private void copyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
String strDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ File.separator + "Pdfs";
File fileDir = new File(strDir);
fileDir.mkdirs(); // crear la ruta si no existe
File file = new File(fileDir, "example2.pdf");
try
{
in = assetManager.open("example.pdf"); //leer el archivo de assets
out = new BufferedOutputStream(new FileOutputStream(file)); //crear el archivo
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Pdfs" + "/example2.pdf"), "application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
change parts of code like these:
out = new BufferedOutputStream(new FileOutputStream(file));
the before example is for Pdfs, in case of to example .txt
FileOutputStream fos = new FileOutputStream(file);

Categories