open files which stored in database using default android program - android

i want to open files in database using default android program...but i have a trouble in opening it...
i store the files path in my database (as string), because it is better to store the files path instead of the files it self...(from what i read)
but when i want to open it in android using the default android program, it goes nothing...just blank...
i don't know which part i wrong, because the log cat didn't show anything...
here is my code...
String fileId = ((TextView)view.findViewById(R.id.fileid)).getText().toString();
String fileName = ((TextView)view.findViewById(R.id.TextView01)).getText().toString();
String filePath = ((TextView)view.findViewById(R.id.filepath)).getText().toString();
//starting activity intent
Intent intent= new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File("http://10.0.2.2/" + filePath);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = file.getName().substring(file.getName().indexOf(".")+1).toLowerCase();
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file), type);
try
{
startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(FileChooser.this, "No Application available to View this file", Toast.LENGTH_SHORT).show();
}
the filePath is android/untitled.jpg
actually i'm really new in developing android...i hope anyone can help me solve my problem...

i got it...
finally i finished it with my own...
if one of you guys confuse about the same thing with me...hope this will help...
public void clearCache()
{
fileCache.clear();
}
private File getFileFromUrl(String url)
{
File f = fileCache.getFile(url);
try
{
URL docUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)docUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
return f;
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
public String GetExtention(String name)
{
name = name.replaceAll("%20", " ");
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = name;
String filenameArray[] = type.split("\\.");
type = filenameArray[filenameArray.length-1];
String ext = mime.getMimeTypeFromExtension(type.toLowerCase());
return ext;
}
while the file cache is class you make...
for more help this can help you...

Related

Reading data from downloaded .txt file downloaded multiple times in Android app

I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.

Sharing an image with ShareActionProvider

I'm trying to share a downloaded bitmap via Android's ShareActionProvider, and I'm having an issue actually passing the bitmap to appropriate apps (such as Messenger, Google+, Gmail). When I pass the intent with the uri, nothing happens (image isn't populated in the 3rd party app).
Here is my Intent:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
writeToDirectory(bitmap, "cached-image.png"); // write bitmap to file system in order to share
intent.putExtra(Intent.EXTRA_STREAM, getFileUri("cached-image.png"))
mShareActionProvider.setShareIntent(intent);
I'm currently saving the bitmap to file using the following:
public String writeToDirectory(Bitmap bitmap, String filename) {
assert context != null;
assert bitmap != null;
assert filename != null;
// Ensure directory exists and create if not
String path = Environment.getExternalStorageDirectory() + File.separator + "myApp";
File f = new File(path);
boolean dirExists = f.isDirectory();
if (!f.isDirectory() && !f.exists()) {
dirExists = f.mkdirs();
}
if (dirExists) {
File file = new File(sharedPrivateExternalPath, filename);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (IOException ex) {
e(TAG, "Write failed!");
e(TAG, ex.getMessage());
ex.printStackTrace();
}
return file.toString();
} else {
return "";
}
}
and I'm retrieving the Uri with this method
public Uri getFileUri(String filename) {
assert context != null;
assert filename != null;
String path = Environment.getExternalStorageDirectory() + File.separator + "myApp";
File file = new File(path, filename);
return Uri.fromFile(file);
}
I've checked that the file gets written to the appropriate place (Uri is file:///storage/emulated/0/myApp/cached-image.png) and was able to view the image there (did an adb pull from the device), though the image doesn't get passed. I don't see any errors in the log (no FileNotFoundException or anything of the sort). Is this a file permission issue? Am I not able to share to a "non-public" location?
If I change getExternalStorageDirectory() + File.separator + "myApp"; to plain getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) it works fine... but it's bothering me it doesn't work the other way :).
Any help would be great!
Turns out it had to do with code I didn't post (surprise, surprise). I was attempting to set the shareIntent in the setOnShareTargetSelectedListener... which apparently you can't do.
My problem was with this code snippet
mShareActionProvider = (ShareActionProvider)
MenuItemCompat.getActionProvider(shareItem);
mShareActionProvider.setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener() {
#Override
public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent) {
String urlKey = mImageUrlList.get(mImageGallery.getCurrentItem()) + "\n";
// This is the problem line
mShareActionProvider.setShareIntent(getImageIntent(app.getImageCache().get(urlKey)));
return false;
}
})

Android: How do I download a file from a dynamic url webview

In my app I am using a webview to navigate through to a site, automatically fill in a web form using javascript then submit to obtain a link to a CSV export file.
The link looks like this: XYZ.com/TEST/index/getexport?id=130.
I'd like to download the file this URL points to, then when complete read it into a local database but I'm having trouble downloading the linked file.
If I simply try to open the URL in webview I get an error from the webpage telling me no such file exists.
If I use the Download Manager to download it myself, the source code is downloaded as an html file, not the associated .csv file.
I can open the url with an ACTION_VIEW intent and a browser (chrome) downloads the correct file, but this way I have no notification of when the download completes.
Any ideas of how to download my .CSV file?
To download a file from webview use this :
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Hope this helps.
You could resort to manually downloading the file from the url using an AsyncTask.
Here id the background part:
#Override
protected String doInBackground(Void... params) {
String filename = "inputAFileName";
HttpURLConnection c;
try {
URL url = new URL("http://someurl/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file = new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
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) {
return e.getMessage();
}
if (file.exists()) {
return "File downloaded!";
} else {
Log.e(TAG, "file not found");
}
} else {
Log.e(TAG, "unable to create folder");
}
}
Perhaps it would make sense to refactor it so that the file is returned. Then you get the file as an argument in onPostExecute as soon as the download is complete.

How to get the file name of a file which is transferred via wifi direct in android?

I have seen an example about this question.But when I have a try on it , it just occur an error in this code File f = new File(Uri.parse(uri.toString())); and just say that Constructor File(Uri) is undefined . I have stucked in this error for many days. I don't know what's wrong with it because other people can work. The following is the suggested code
public class WiFiDirectBundle extends Serializable {
private String fileName;
private String mimeType;
private Long fileSize;
private byte[] fileContent;
public WiFiDirectBundle() {}
// adds a file to the bundle, given its URI
public void setFile(Uri uri) {
File f = new File(Uri.parse(uri.toString()));
fileName = f.getName();
mimeType = MimeTypeMap.getFileExtensionFromUrl(f.getAbsolutePath());
fileSize = f.length();
FileInputStream fin = new FileInputStream(f);
fileContent = new byte[(int) f.length()];
fin.read(fileContent);
}
// restores the file of the bundle, given its directory (change to whatever
// fits you better)
public String restoreFile(String baseDir) {
File f = new File(baseDir + "/" + fileName);
try {
FileOutputStream fos = new FileOutputStream(f);
if (fileContent != null) {
fos.write(fileContent);
}
fos.close();
return f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getFileName() {
return fileName;
}
public String getMimeType() {
return mimeType;
}
public Long getFileSize() {
return fileSize;
}
}
And this is original qusetion:
How to find file name of a file which is transferred via wifi direct mode in android?
Also I am a beginner in Wifi Direct ,I can successfully link two device and transfer file ,but I want to linked more device and transfer file Sequentially can anyone give me some advices about learning it or some examples about how to do it.Thanks!
use
File f = new File(uri.getPath());
instead of
File f = new File(Uri.parse(uri.toString()));
to get file path from Uri
you can open inputstream of a file from its uri using content resolver
ContentResolver cr=getContentResolver();
InputStream in=cr.OpenInputStream(file_uri);
you can use this input stream to read from the file

How to read PDF file saved to internal storage of device?

I am using following code to download and read a PDF file from internal storage on device.
I am able to download the files successfully to the directory:
data/data/packagename/app_books/file.pdf
But I am unable to read the file using a PDF reader application like Adobe Reader.
Code to download file
//Creating an internal dir;
File mydir = getApplicationContext().getDir("books", Context.MODE_WORLD_READABLE);
try {
File file = new File(mydir, outputFileName);
URL downloadUrl = new URL(url);
URLConnection ucon = downloadUrl.openConnection();
ucon.connect();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte data[] = new byte[1024];
int current = 0;
while ((current = is.read(data)) != -1) {
fos.write(data, 0, current);
}
is.close();
fos.flush();
fos.close();
isFileDownloaded=true;
} catch (IOException e) {
e.printStackTrace();
isFileDownloaded = false;
System.out.println(outputFileName + " not downloaded");
}
if (isFileDownloaded)
System.out.println(outputFileName + " downloaded");
return isFileDownloaded;
Code to read the file
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File fileToRead = new File(
"/data/data/com.example.filedownloader/app_books/Book.pdf");
Uri uri = Uri.fromFile(fileToRead.getAbsoluteFile());
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception ex) {
Log.i(getClass().toString(), ex.toString());
Toast.makeText(MainActivity.this,
"Cannot open your selected file, try again later",
Toast.LENGTH_SHORT).show();
}
All works fine but the reader app says "File Path is not valid".
Your path is only valid for your app. Place the file in a place where other apps can 'see' it. Use GetExternalFilesDir() or getExternalStorageDirectory().
Note about files which are created inside the directory created by Context.getDir(String name, int mode) that they will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
So you can use Context.openFileOutput(String name, int mode). I'm re-using your code for an example:
try {
// Now we use Context.MODE_WORLD_READABLE for this file
FileOutputStream fos = openFileOutput(outputFileName,
Context.MODE_WORLD_READABLE);
// Download data and store it to `fos`
// ...
You might want to take a look at this guide: Using the Internal Storage.
If you would like to keep the file app specific, you can use PdfRenderer available for Lollipop and above builds. There are great tutorials on google and youtube that work well. The method you are using is a secure way to store a PDF file that is only readable from inside the app ONLY. No outside application like Adobe PDF Reader will be able to even see the file.It took me a lot of seaching but I found a solution to my specific usage by using this site and especially youtube.
How to download PDF file from asset folder to storage by making folder
make sure you have storage permission are given like marshmallow device support etc then follow these steps
private void CopyReadAssets()
{
AssetManager assetManager = getContext().getAssets();
FileInputStream in = null;
FileOutputStream out = null;
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(Environment.getExternalStorageDirectory()+File.separator+ "A_level");
File dir2;
if (dir.exists() && dir.isDirectory()){
Log.e("tag out", ""+ dir);
}else {
dir.mkdir();
Log.e("tag out", "not exist");
}
File file = new File(dir, mTitle+".pdf");
try
{
Log.e("tag out", ""+ file);
out = new FileOutputStream(file);
in = new FileInputStream (new File(mPath));
Log.e("tag In", ""+ in);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag out", ""+ out);
Log.e("tag In", ""+ in);
Log.e("tag", e.getMessage());
Log.e("tag", ""+file);
Log.i("tag",""+sdcard.getAbsolutePath() + "A_level");
}
}
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);
}
}

Categories

Resources