Cannot open PDF in Android Studio - java

I am developing an app in API 27, I have a problem in opening a PDF from the asset folder. I have tried lots of different approaches, but still not successful.
When the PDF opens, a blank black screen appears. I checked the file.exist() return false in all steps it returns 'false'.
I really need help about this topic. In addition, I tried both internal and external storage. Also tried different intent tag. But still no luck.
Here is the function I've used.
private void openPDFFiles(String fileName) //fileName is the pdf file name which is keep in assets folder. ex file.pdf
{
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File imagePath = new File(getFilesDir(), "Videos");
File file = new File(imagePath, "1.pdf");
try {
in = assetManager.open(fileName);
out = openFileOutput(file.getName(), MODE_PRIVATE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
System.out.println(e);
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(FileProvider.getUriForFile(getApplicationContext(), "com.administrator.siemens.android.fileprovider", file), "application/pdf");
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} catch (RuntimeException ex) {
Toast.makeText(Document.this, "There's no PDF Reader found in your device", Toast.LENGTH_SHORT).show();
}
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);
}
System.out.println("1222222222");
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.administrator.siemens">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/me"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.administrator.siemens.android.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepath" />
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
filepath.xml:
<paths>
<files-path name="my_docs" path="Videos/"/>
</paths>
Really thanks!, if anyone can help me.

Related

How to write scoped storage for android 11 in java?

Here is my app code below. I want to store images and files such as pdf to my folder path to the above 10+ version and below version. I just want to know. Is the correct way? please let me know what I have missed. It's working perfectly but I just confused with manifest permission as per google play policy for app successful update
my question is the correct way for scoped storage and permissions?
my manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.flendzz.licstickynote.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"
android:maxSdkVersion="29"/>
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity.java
private void SaveImageaBOVE10(Bitmap bitmap) {
OutputStream fos;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "image_" + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "Note App");
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = (FileOutputStream) contentResolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos);
Toast.makeText(this, "image saved", Toast.LENGTH_SHORT).show();
} else {
SaveImage(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//below 10 version
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/NoteApp");
if (!myDir.exists()) {
myDir.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "image saved in storage", Toast.LENGTH_SHORT).show();
}

download a text-file from Webserver using Asynctask

/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString(); // "/storage/emulated/0"
System.out.println("Downloading");
URL url = new URL(f_url[0]); //http://xxx.168.2.200/tmp/bsp1.txt;
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(fileNameDaten);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
String fel=e.getMessage();
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
#Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
}
}
doInBackground is running until "conection.connect();"
After about 3 minutes the app will continue with an exception:
"Failed to connect to /xxx.168.2.200:80"
In principle, I can access the web server's HTML pages with my mobile phone.
My question: What does the error message mean and how can I fix the error?
networkSecurityConfig : not added to manifest, how to formulate ?
app targets android 9, API 28 only partially installed
I will use the app only for local adresses
Follows manifest:enter code here
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.wicki.pdftextapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<application
android:usesCleartextTraffic="true"
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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UploadToServer"></activity>
</application>
</manifest>

File provider used in sending email attachment keeps crashing

I am trying to send an email upon button click with an attachment stored in internal storage. I tried following this tutorial in implementing a file provider, however every time I try running the app and pressing the button the app crashes and stops working.
I am lost for why that may be. Below is the relevant code:
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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">
<provider
android:name="android.support.v4.content.FileProvider"
android:grantUriPermissions="true"
android:exported="false"
android:authorities="${applicationId}">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths"/>
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<paths>
<cache-path name="cache" path="/" />
<files-path name= "files" path="/" />
</paths>
</PreferenceScreen>
MainActivity.java
Button emailBtn = (Button) findViewById(R.id.button);
main = findViewById(R.id.main);//email form button
emailBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = Screenshot.takescreenshotOfRootView(main);
ImageView programLogo = (ImageView) findViewById(R.id.imageView);
programLogo.setImageBitmap(b);
File filePath = new File(loadImageFromStorage(saveToInternalStorage(b)), "profile.jpg");
Intent intent = new Intent(Intent.ACTION_SEND, Uri.fromParts(
"mailto","myemail#gmail.com", null));
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = (Uri) FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, filePath);
intent.setDataAndType(uri, "application/jpg");
String subject = "please work";
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
});
}
private String saveToInternalStorage(Bitmap bitmapImage) {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
private String loadImageFromStorage(String path) {
File f = new File(path, "profile.jpg");
return f.getAbsolutePath();
}
This is the error I get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication234567, PID: 5272
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.myapplication234567/app_imageDir/profile.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:739)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:418)
at com.example.myapplication234567.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:6913)
at android.view.View.performClickInternal(View.java:6890)
at android.view.View.access$3200(View.java:792)
at android.view.View$PerformClick.run(View.java:27158)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:209)
at android.app.ActivityThread.main(ActivityThread.java:7021)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
Your message contains this path which appears incorrect: /data/data/com.example.myapplication234567/app_imageDir/profile.jpg/profile.jpg
try catches are your friend.

Android: Saving a file to the SD card

This is my first Android application I'm making, so I'm a bit lost on what the terms are for everything.
I'm trying to copy a file I have in my /raw/ directory to the root of my SD card.
Currently, my (used Stackoverflow, didn't write this fully myself) code looks like this:
btnWriteSDFile.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "fileName.docx");
myFile.createNewFile();
Toast.makeText(v.getContext(),"Wrote line", Toast.LENGTH_SHORT).show();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append("testFile");
myOutWriter.close();
fOut.close();
Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I get the error: "open failed; EACCES (Permission Denied)".
My Manifest looks like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Clarification to avoid duplication:
Besides the fact that I get this error: how can I write a /raw/file.docx file to my SD card root?
According to this documentation you have to add the uses permission inside and immediate to <manifest> tag
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
...
<application>
...
<activity>
...
</activity>
</application>
</manifest>
like this
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
this should work for copying file
InputStream in = getResources().openRawResource(R.raw.fileNameYourGoingToCopy);
String path = Environment.getExternalStorageDirectory() + "/anyFolder" + File.separator + fileNameWithExtension;
FileOutputStream out = new FileOutputStream(path);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}

Share the Selected Image Only in Android

HOW CAN I REPLACE THE R.id.ic_launcher with the specific id that user selected.
i have created an application which represents some grid view of images, then after user selection it select the specific image and then a share menu button share the image to the social apps.
but the error is whenever any image is selected and shared to any application it only sends the default launcher icon i.e, ic_launcher.png.
my code goes below like this:
FullImageActivity.java
#SuppressLint("SdCardPath")
public class FullImageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch (item.getItemId()) {
case R.id.item:
Uri uri = Uri.fromFile(dest);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is where i implemented the share method, this is shere my code sending the defautl ic_launcher.png instead of selected image.
further i kept all the images in .jpeg format in ImageAdapter.java class.
private Context mContext;
// Keeping all Images in array
public Integer[] mThumbIds = {
R.drawable.rage_0001,R.drawable.rage_0002,
and my AndroidManifest.XML goes like this for all uses permissions and activity records.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:permission="android.permission.WRITE_EXTERNAL_STORAGE"
android:theme="#style/AppTheme" >
<activity
android:name="com.jai.desimeme.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<!-- FullImageActivity -->
<activity android:name="com.jai.desimeme.FullImageActivity" >
</activity>
<activity
android:name="com.jai.desimeme.About"
android:theme="#android:style/Theme.Dialog" >
</activity>
<activity
android:name="com.jai.desimeme.ShareActivity"
android:label="#string/title_activity_share" >
</activity>
</application>
tell me where i need to modify my code for proper working as i mentioned above.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),drawable.ic_launcher);//launcher being saved to file
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the part where you are saving the launcher image to a file and hence sharing that image

Categories

Resources