when i run this piece of code as normal java application in main it runs fine. but when i try to use the same code in onCreate in one of the activity it says file not found exception and prints nothing in logcat. i have tried every possible way but dont know whts the cause of the problem. Also in logcat the msg is like this filenotfound exception: /D:/android/Suyesh.2DV106.Assignment3/southern_cities.txt (no such file or directory) . is it because of the leading forward slash /D:/.. but i didnt put it there and when i try to print the path it doesnt contain that / in front of D. But when i print the absoulte path it contains that /D. Whats the problem here? I have also my manifest file as below.
public class TheCityMap extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String strFile = Environment.getExternalStorageDirectory() +"/android/Suyesh.2DV106.Assignment3/southern_cities.txt";
BufferedReader br = new BufferedReader(new FileReader(strFile));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (strLine = br.readLine()) != null){
lineNumber++;
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
tokenNumber++;
System.out.println("Line # " + lineNumber +", Token # " + tokenNumber+ ", Token : "+ st.nextToken());
}
tokenNumber = 0;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="assignment3.demos"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainListActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="TheCityMap"></activity>
<uses-library android:name="com.google.android.maps"/>
<uses-permission android:name="android.permission.INTERNET" > </uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" > </uses-permission>
</application>
Android is based on linux so things like "D:" should never work.
If the file is on sd card try this:
String strFile = Environment.getExternalStorageDirectory() + "/android/Suyesh.2DV106.Assignment3/southern_cities.txt";
At the end your path should be something like:
"/mnt/sdcard/android/Suyesh.2DV106.Assignment3/southern_cities.txt"
Have you tried to use:
File file = new File(TheCityMap.class.getResource(/* name */));
BufferedReader reader = new BufferedReader(new FileReader( file ));
or:
new BufferedReader(new InputStreamReader(FlowAp.class.getResourceAsStream("" /* name */)))
if D is your external storage directory (sdcard or flash), use Enviroment.getExternalStorageDirectory()
Related
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();
}
/**
* 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>
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.
I have a problem when I try to save a file. First of all, it worked correctly when I try it on an older Eclipse, but I have to use new Eclipse so I export the project from the older Eclipse and import it on the new. Now it doesn't save and give me this excepction:
java.io.FileNotFoundException: /storage/sdcard/MyApp/questions.txt: open failed: EACCES (Permission denied)
I put the code I use to save (this code works on the older eclipse, in the new gives me the exception):
public void saveDates(boolean mainScreen)
{
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/MyApp");
if (!mFolder.exists())
{
mFolder.mkdir();
}
String strF = mFolder.getAbsolutePath();
File mSubFolder = new File(strF /*+ "/MyApp-SubFolder"*/);
if (!mSubFolder.exists())
{
mSubFolder.mkdir();
}
//Nombre del fichero
String s = "questions.txt";
BufferedWriter out;
try
{
FileWriter fileWriter = new FileWriter(mSubFolder.getAbsolutePath() + "/" + s, false);
out = new BufferedWriter(fileWriter);
out.write(indexAnswer + ";");
out.write("\r\n");
out.write(finished + ";");
out.write("\r\n");
out.write(directricesGenerales + ";");
out.write("\r\n");
out.write(politicaAmbiental + ";");
out.write("\r\n");
out.write(planificacion + ";");
out.write("\r\n");
out.write(implementacion + ";");
out.write("\r\n");
out.write(verificacion + ";");
out.write("\r\n");
out.write(revision + ";");
out.write("\r\n");
out.write(definicionProyecto + ";");
out.write("\r\n");
out.write(analisisAmbiental + ";");
out.write("\r\n");
out.write(desarrollo + ";");
out.write("\r\n");
out.write(disenyoDetalle + ";");
out.write("\r\n");
out.write(planAccion + ";");
out.write("\r\n");
out.write(evaluacionContinua + ";");
out.write("\r\n");
out.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Datos guardados.", Toast.LENGTH_LONG).show();
if(mainScreen)
{
// Cerrar la ventana de test y volver a la de inicio
Intent intent = new Intent();
intent.setClass(questions.this, MainActivity.class);
startActivity(intent);
finish();
}
}
And my manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.XXX"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.ecotoolin.principal"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.ecotoolin.questions"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<activity
android:name="com.example.ecotoolin.Chart"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<activity
android:name="com.example.ecotoolin.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<activity
android:name="com.example.ecotoolin.reload"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
<activity
android:name="com.example.ecotoolin.sendMail"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
</activity>
</application>
<uses-permission
android:name="android.permission.INTERNET">
</uses-permission>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
And an image of my emulator details:
Can anyone help me? Iwant to save the file like I do it in the older version, I don't know why doesn't work.
First, you need this permission in manifest to read files:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Second, does your file actually exist. If not then you first need to create the file before writing data to it.
How to create a file: How to create a file in Android?
Sample code to create a file:
// use "File.separator" instead of "/"
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
//create the file
file.createNewFile();
//text you want to write to your file
String text = "your_text";
//check if file exists
if(file.exists()){
OutputStream fo = new FileOutputStream(file);
//write the data
fo.write(text);
//close to avoid memory leaks
fo.close();
//give a log message that the file was created with "text"
System.out.println("file created: "+file);
}
I don't know why since I switched to kitkat my app cannot create any file in system (This method was working on android 4.1.2). My app has su permissions, mount system as RW and READ and WRITE_EXTERNAL_STORAGE permissions declared in manifest.
Logcats show me that it allows SU permissions but no errors.
The code that it is not working is this one below.
File file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hasta.cocoremanager"
android:versionCode="1"
android:versionName="1.7" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.hasta.cocoremanager.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Since 4.4.2 there are new rules for IO on the device storage:
Article
To put it short: Now you can only write in your app's folder.
Ensure that the file has read/write permissions to everyone.
Runtime.getRuntime().exec(new String[] { "su", "-c", "chown 777 /etc/init.d/script" });
Now you will be able to get an instance of that file.
If the file does not exist, first run
Runtime.getRuntime().exec(new String[] { "su", "-c", "echo '#' > /etc/init.d/script" });
EDIT: Without knowing how you want to use the file instance, i'll take a stab at it
File file = null;
try
{
file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
}
catch (Exception e)
{
// Cannot get file so set permissions.
Runtime.getRuntime().exec(new String[] { "su", "-c", "chown 777 /etc/init.d/script" });
try
{
file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
}
catch (Exception e)
{
// File does not exits, so create it.
Runtime.getRuntime().exec(new String[] { "su", "-c", "echo '#' > /etc/init.d/script" });
// Now set permissions.
Runtime.getRuntime().exec(new String[] { "su", "-c", "chown 777 /etc/init.d/script" });
try
{
file = new File(Environment.getRootDirectory().getPath().toString(), "/etc/init.d/script");
}
catch (Exception e)
{
// Should never get here.
}
}
// Do stuff with your file.
You can always do all this in your app user area and then do
Runtime.getRuntime().exec(new String[] { "su", "-c", "cp " + Environment.getDataDirectory() + "/script /etc/init.d/script" });
A note on calling su, this syntax also works.
Runtime.getRuntime().exec("su -c cp " + Environment.getDataDirectory() + "/script /etc/init.d/script");
Set menifest permissions that both:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Becasuse also you required the read permission for RW and READ