File.createNewFile() method throws exception in Android M - java

I have a problem to create file in Android M.
I use Nexus 9 with Android 6.0.1. Then I set in my project as below:
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
build.gradle
android {
defaultConfig {
targetSdkVersion 23
...
}
}
MainActivity.Java
public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String rootPath = storagePath + "/test";
String fileName = "/test.zip";
File root = new File(rootPath);
if(!root.mkdirs()) {
Log.i("Test", "This path is already exist: " + root.getAbsolutePath());
}
File file = new File(rootPath + fileName);
try {
if (!file.createNewFile()) {
Log.i("Test", "This file is already exist: " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Build was success and application was launched, but I got exception message like this:
IOExceiption
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: java.io.IOException: open failed: ENOENT (No such file or directory)
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: at java.io.File.createNewFile(File.java:939)
01-07 18:13:40.669 18027-18027/com.sample.myapplication W/System.err: at com.sample.myapplication.MainActivity.onCreate(MainActivity.java:36)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.Activity.performCreate(Activity.java:6251)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
01-07 18:13:40.670 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.-wrap11(ActivityThread.java)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.os.Looper.loop(Looper.java:148)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at libcore.io.Posix.open(Native Method)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: at java.io.File.createNewFile(File.java:932)
01-07 18:13:40.671 18027-18027/com.sample.myapplication W/System.err: ... 13 more
How can I solve this problem? I don't catch what I miss....
Please help.

Updated
Replace storagePath to access scoped storage, for Android 10.
Refer this document for more detail.
Thanks, laalto.
I didn't know about runtime permission.
I solved exception like this:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Request user permissions in runtime */
ActivityCompat.requestPermissions(MainActivity.this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
100);
/* Request user permissions in runtime */
createTestFile();
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// User checks permission.
} else {
Toast.makeText(MainActivity.this, "Permission is denied.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createTestFile() {
// String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
// If Target API level is 29(Android 10),
// you should access local path in scoped storage mode.
File localStorage = getExternalFilesDir(null);
if (localStorage == null) { return; }
String storagePath = localStorage.getAbsolutePath();
String rootPath = storagePath + "/test";
String fileName = "/test.zip";
File root = new File(rootPath);
if(!root.mkdirs()) {
Log.i("Test", "This path is already exist: " + root.getAbsolutePath());
}
File file = new File(rootPath + fileName);
try {
int permissionCheck = ContextCompat.checkSelfPermission(
MainActivity.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
if (!file.createNewFile()) {
Log.i("Test", "This file is already exist: " + file.getAbsolutePath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
It works!

I was having the same problem. I got an IOException on the file.createNewFile. A closer look at the exception reveals that it was due to "permissions denied". I was writing to my getFilesDir, so I shouldn't need an in the android manifest to accomplish this task. I of course added both READ and WRITE permissions for external storage, and of course, that didn't fix the problem.
I had been testing the code using a NEXUS 6 emulator with sdk 26. Without changing any code, I tried testing using a PIXEL C emulator with sdk 26 and the problem did not occur. So there seems to be some problem with my Nexus 6 emulator.
I suspect that this hasn't always been a problem and that this emulator instance got corrupted, but I haven't verified that. I did take the time to look at the linux file permission on the directories I was creating the file into an it reported "drwxrwxrwx", which is correct. I will add that I've implemented a FileProvider with paths to the directory I'm trying to create the new file at. The code I'm using pretty much looks like the code that Kae10 shows.
I traced the problem down to this code in UnixFileSystem:
public boolean createFileExclusively(String path) throws IOException {
BlockGuard.getThreadPolicy().onWriteToDisk();
return createFileExclusively0(path);
}
the exception is thrown from createFileExlussively0, which I not able to debug into. I haven't investigated this issue any further (i.e. 1.) would deleting the avd instance and recreating it help, my guess is that might, 2.) is there a later system image I should be using?)

Related

Google Sign in Error 12500 SHA1 double checked GoogleSignInAccount account = completedTask.getResult(ApiException.class);

I am getting this error after selecting a google account. OnActivityResult is called, but after evaluating the result this error is thrown. The cause is not a wrong SHA1, I am using the same key for release and debug. The app is not from Google Play. I am not using firebase. The google signin sample works with the same key.
com.google.android.gms.common.api.ApiException: 12500:
Stacktrace:
W/System.err: com.google.android.gms.common.api.ApiException: 12500:
W/System.err: at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source)
W/System.err: at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
W/System.err: at de.org.limindo.limindo2.fragLogin.onActivityResult(fragLogin.java:412)
W/System.err: at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:151)
W/System.err: at de.org.limindo.limindo2.MainActivity.onActivityResult(MainActivity.java:788)
W/System.err: at android.app.Activity.dispatchActivityResult(Activity.java:5456)
W/System.err: at android.app.ActivityThread.deliverResults(ActivityThread.java:3549)
W/System.err: at android.app.ActivityThread.handleSendResult(ActivityThread.java:3596)
W/System.err: at android.app.ActivityThread.access$1300(ActivityThread.java:151)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1369)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:110)
W/System.err: at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5299)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
The code is:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(fragLogin.this._main, gso);
mSignInGoogle0.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
if (account != null)
{
mPasswordView.setVisibility(View.GONE);
mPasswordView.setVisibility(View.GONE);
}
updateUI(account);
} catch (ApiException e) {
e.printStackTrace();
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
lib.ShowMessage(getContext(), getString(R.string.googleloginnotsuccessfull) + "\n" + getString(R.string.ErrorCode) + GoogleSignInStatusCodes.getStatusCodeString(e.getStatusCode()) + ":" + e.getStatusCode(), getString(R.string.Error));
updateUI(null);
}
}
In case this helps anybody: I was in this situation, except that it worked initially then stopped working later. I finally realized that it was because I switched laptops.
The solution is the package name: The package name of the manifest is de.org.limindo.limindo2 but the package of the apk is de.org.limindo2 ..... It seems that gradle shortens package names, if they contain double entries….

Download and save PDF on sdcard not found

I'm trying to download a pdf from an url and then save and read it. But I get the error java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource. when I try to read it. Any idea ?
Here is my Downloader class :
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the line to download and read the pdf :
String extStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
.toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "menu.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", file);
PdfReader reader = new PdfReader(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/menu.pdf");
Here is the error :
05-02 13:59:01.138 16747-16747/? I/art: Not late-enabling -Xcheck:jni (already on)
05-02 13:59:01.139 16747-16747/? W/art: Unexpected CPU variant for X86 using defaults: x86
05-02 13:59:01.676 16747-16747/com.example.yohannmbp.ematoufaire I/InstantRun: starting instant run server: is main process
05-02 13:59:01.868 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-02 13:59:02.440 16747-16787/com.example.yohannmbp.ematoufaire D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire I/OpenGLRenderer: Initialized EGL, version 1.4
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 1
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
05-02 13:59:02.783 16747-16795/com.example.yohannmbp.ematoufaire D/OpenGLRenderer: Swap behavior 0
05-02 13:59:03.029 16747-16747/com.example.yohannmbp.ematoufaire W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
05-02 13:59:11.011 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.IOException: No such file or directory
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.File.createNewFile(File.java:948)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:106)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.012 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.013 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: java.io.FileNotFoundException: /storage/emulated/0/pdf/menu.pdf (No such file or directory)
05-02 13:59:11.015 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.open(Native Method)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.Downloader.DownloadFile(Downloader.java:18)
05-02 13:59:11.016 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.example.yohannmbp.ematoufaire.MenuFragment.onCreateView(MenuFragment.java:110)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
05-02 13:59:11.017 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.os.Looper.loop(Looper.java:154)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at java.lang.reflect.Method.invoke(Native Method)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
05-02 13:59:11.018 16747-16747/com.example.yohannmbp.ematoufaire W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
05-02 13:59:11.088 16747-16752/com.example.yohannmbp.ematoufaire I/art: Do partial code cache collection, code=30KB, data=29KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: After code cache collection, code=23KB, data=25KB
05-02 13:59:11.089 16747-16752/com.example.yohannmbp.ematoufaire I/art: Increasing code cache capacity to 128KB
05-02 13:59:11.127 16747-16747/com.example.yohannmbp.ematoufaire I/System.out: java.io.IOException: /storage/emulated/0/pdf/menu.pdf not found as file or resource.
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
**strong text** #Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(AppConstant.BASE_URL + URLEncoder.encode(sUrl[0], "UTF-8"));
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
fileName = sUrl[0].substring(sUrl[0].lastIndexOf("/") + 1,
sUrl[0].length());
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
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);
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: File is not Found.", Toast.LENGTH_LONG).show();
else {
new AlertDialog.Builder(context)
//.setTitle("Delete entry")
.setMessage("File Downloaded Successfully. Do you want to open it?")
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(file);
intent.setDataAndType(data, type);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "There is no app registered to handle the type of file selected.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
try this
downloadTask = new DownloadTask();
downloadTask.execute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf", "", "");
private class DownloadTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ll_view.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
File sourcePath = Environment.getExternalStorageDirectory();
File path = new File(sourcePath + "/" + Constants.DIR_NAME + "/");
path.mkdir();
File file = new File(path, "/ecute("http://webdfd.mines-ales.fr/restau/Menu_Semaine.pdf");
if (file.exists()) {
file.delete();
}
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ll_view.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(final Integer... values) {
super.onProgressUpdate(values);
// Log.e("progressing", "" + values[0]);
// edt_search.setText("" + values[0]);
// new Thread(new Runnable() {
// public void run() {
progressBar.setProgress(values[0]);
// tv_downloading.setText("" + values[0] + "%");
// }
// }).start();
}
#Override
protected void onCancelled(String s) {
super.onCancelled(s);
}
#Override
protected void onCancelled() {
super.onCancelled();
}
}
if your target and compile sdk higher than lolipop then you have to add request permission code before download refer this link and read and write external storage permission required

Android org.xmlpull.v1.XmlPullParserException: expected: START_TAG

I am newbie to android development. I am using android studio for developing an app. I know there are lot and lot of questions related to it, i looked into them but my problem still exists. Below are the solutions in which i have looked into.
link1
link2
link3
I clearly looked into them and match with my problem. But still i am unable to solve my issue.
The app is simple that will have a editText a button and a textView. User should enter id in editText and when the button is tapped then the corresponding name should be shown. The button will use a webservice.
For this i created some tables in SQL. And created a webservice in dotnet.
Below is my web service
[WebMethod]
public string findContact(string eid)
{
return getContact(eid);
}
public string getContact(string eid)
{
SqlConnection conn;
conn = ConnectionManager.GetConnection();
conn.Open();
SqlCommand newCmd = conn.CreateCommand();
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "Select Name from Users where Id=" + eid + "";
SqlDataReader sdr = newCmd.ExecuteReader();
String address = null;
if(sdr.Read())
{
address = sdr.GetValue(0).ToString();
}
conn.Close();
return address;
}
Below is my manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<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>
Below is my java code
public class MainActivity extends AppCompatActivity {
/** Called when the activity is first created. */
private static final String SOAP_ACTION = "http://tempuri.org/findContact";
private static final String METHOD_NAME = "findContact";// webservice web method name
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://192.168.100.9:9698/WebService.asmx";
TextView textView;
Button button;
EditText editText;
String ID;
public static final String LOG_TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.webServ);
button = (Button)findViewById(R.id.btnSubmit);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
PropertyInfo propertyInfo = new PropertyInfo();
propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "eid";
editText = (EditText)findViewById(R.id.enterID);
ID = editText.getText().toString();
request.addProperty(propertyInfo,ID);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransportSE = new HttpTransportSE(URL);
httpTransportSE.debug = true;
try
{
httpTransportSE.call(SOAP_ACTION,envelope);
Object response = envelope.getResponse();
textView.setText(response.toString());
} catch (XmlPullParserException e) {
textView.setText(e.toString() + " Or enter ID is not valid!");
e.printStackTrace();
} catch (IOException e) {
textView.setText(e.toString() + " IOException Or enter ID is not valid!");
e.printStackTrace();
}
String res = (httpTransportSE.responseDump).toString();
Log.v(LOG_TAG, res);
}
});
}}
When i click on the button i am getting the bellow error.
org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <HTML>#2:7 in java.io.InputStreamReader#960e1fa)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at org.kxml2.io.KXmlParser.require(KXmlParser.java:2065)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:127)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at org.ksoap2.transport.Transport.parseResponse(Transport.java:63)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at com.example.accurat.accesswebservice.MainActivity$1.onClick(MainActivity.java:75)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at android.view.View.performClick(View.java:4780)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at android.view.View$PerformClick.run(View.java:19866)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
02-10 12:20:50.994 11713-11713/com.example.accurat.accesswebservice W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
02-10 12:20:50.995 11713-11713/com.example.accurat.accesswebservice W/System.err: at android.os.Looper.loop(Looper.java:135)
02-10 12:20:50.995 11713-11713/com.example.accurat.accesswebservice W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
02-10 12:20:50.995 11713-11713/com.example.accurat.accesswebservice W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-10 12:20:50.995 11713-11713/com.example.accurat.accesswebservice W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
02-10 12:20:50.995 11713-11713/com.example.accurat.accesswebservice W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
02-10 12:20:50.995 11713-11713/com.example.accurat.accesswebservice W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
It hits at the line httpTransportSE.call(SOAP_ACTION,envelope);
I am testing it on the emulator, below is the screen shot of my emulator
I have also checked my Webservice running in web browser, it's working fine. But it's not on the emulator.
Any help would be highly appreciated.

File not found error for no apparent reason?

My application should save a piechart as a png on the external storage. However this error appears:
java.io.FileNotFoundException: /storage/emulated/0/SAVE IMAGE EXAMPLE/myimage.png (No such file or directory)
I followed the instructions to add this kind of functionality very closely (From this tutorial), but yet the error appears. The app has the permission to write to external storage, I added the permission in my android_manifest.xml.
Can you guys spot the error? Because i can not.
If you also can't find the error, can you recommend any other way to do this?
Im using MPAndroidChart, but i don't really think it has to do with this, because i could try to save any other object and the error remains.
The code is
final PieChart piechart = (PieChart) findViewById(R.id.piechart);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
Toast.makeText(Main.this, "Chart Saved", Toast.LENGTH_SHORT).show();
piechart.setCenterText("Test");
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(),R.id.piechart);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()+"/SAVE IMAGE EXAMPLE");
dir.mkdirs();
File file = new File(dir, "myimage.png");
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
FULL ERROR
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/SAVE IMAGE EXAMPLE/myimage.png (No such file or directory)
W/System.err: at java.io.FileOutputStream.open(Native Method)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
W/System.err: at com.pies.quickpie.Main$1$3.onClick(Main.java:175)
W/System.err: at android.view.View.performClick(View.java:5637)
W/System.err: at android.view.View$PerformClick.run(View.java:22429)
W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You need to implement Runtime Permission model to get Storage Permission from user from marshmallow and above.
See the example here for storage permission

file writing is not performing in android

I need to write the registration credentials into a file during registration and during login will check that file for credentials. but on registration button click nothing is performing.
Manifest file contains this permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
the registration.java part:
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String user=username.getText().toString();
String pwd=password.getText().toString();
String cpwd=confirm.getText().toString();
if(user.equals("")||pwd.equals("")||cpwd.equals("")){
Toast.makeText(getApplicationContext(), "Fields cannot be Blank", Toast.LENGTH_SHORT).show();
}
else if(pwd.equals(cpwd)){
String data=user+","+pwd+":";
try {
FileOutputStream fout = new FileOutputStream(Environment.getExternalStorageDirectory()+"/myapp/userregister.txt/", true);
fout.write(data.getBytes());
Toast.makeText(getApplicationContext(), "Succesfully Register", Toast.LENGTH_SHORT).show();
Intent a=new Intent(getApplicationContext(),LoginActivity.class);
startActivity(a);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(!pwd.equals(cpwd)){
Toast.makeText(getApplicationContext(), "Password not match.. Try again!", Toast.LENGTH_SHORT).show();
}
}
});
In LoginActivity.java
if(username.equals("") || password.equals("")){
Toast.makeText(getApplicationContext(), "Fields Cannot be Blank", Toast.LENGTH_SHORT).show();
}else{
String reply=FileManipulator.authenticateUser(username, password);
if(reply.equals("user")){
Intent gotoNextActivity=new Intent(getApplicationContext(),HomeActivity.class);
startActivity(gotoNextActivity);
}else{
Toast.makeText(getApplicationContext(), "Invalid User.... Try again",Toast.LENGTH_SHORT).show();
}
}
FileManipulator class authenticateUser function:
public static String authenticateUser(String user, String pass){
String data="";
String data1 = "";
try{
FileInputStream fin=new FileInputStream(Path.userregister);
byte[] b=new byte[fin.available()];
fin.read(b);
data=new String(b);
String st=user+","+pass+":";
if(data.contains(st)){
data1="user";
}
}catch(Exception e){
e.printStackTrace();
}
return data1;
}
The log cat shows
09-02 05:48:06.292: D/dalvikvm(1964): GC_CONCURRENT freed 240K, 12% free 2838K/3200K, paused 5ms+32ms, total 177ms
09-02 05:48:06.802: I/Choreographer(1964): Skipped 36 frames! The application may be doing too much work on its main thread.
09-02 05:48:10.362: I/Choreographer(1964): Skipped 32 frames! The application may be doing too much work on its main thread.
09-02 05:48:20.872: W/System.err(1964): java.io.FileNotFoundException: /mnt/sdcard/myapp/userregister.txt: open failed: EACCES (Permission denied)
09-02 05:48:20.872: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:416)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
09-02 05:48:20.882: W/System.err(1964): at java.io.FileOutputStream.<init>(FileOutputStream.java:128)
09-02 05:48:20.882: W/System.err(1964): at com.example.text.RegActivity$1.onClick(RegActivity.java:49)
09-02 05:48:20.892: W/System.err(1964): at android.view.View.performClick(View.java:4204)
09-02 05:48:20.892: W/System.err(1964): at android.view.View$PerformClick.run(View.java:17355)
09-02 05:48:20.902: W/System.err(1964): at android.os.Handler.handleCallback(Handler.java:725)
09-02 05:48:20.912: W/System.err(1964): at android.os.Handler.dispatchMessage(Handler.java:92)
09-02 05:48:20.912: W/System.err(1964): at android.os.Looper.loop(Looper.java:137)
09-02 05:48:20.912: W/System.err(1964): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 05:48:20.922: W/System.err(1964): at java.lang.reflect.Method.invoke(Method.java:511)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-02 05:48:20.922: W/System.err(1964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-02 05:48:20.922: W/System.err(1964): at dalvik.system.NativeStart.main(Native Method)
09-02 05:48:20.932: W/System.err(1964): Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.Posix.open(Native Method)
09-02 05:48:20.942: W/System.err(1964): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
09-02 05:48:20.952: W/System.err(1964): at libcore.io.IoBridge.open(IoBridge.java:400)
09-02 05:48:20.952: W/System.err(1964): ... 14 more
I'm a newbie to android and java..please help me to find the error.
1) Add android.permission.WRITE_EXTERNAL_STORAGE in AndroidManifest.xml file.
2) Always check for the availability of external storage before writing/reading by :
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
} else {
// Can't read or write
}
3) Create a directory, then make your file in it.
File dir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp");
dir.mkdirs();
File file = new File(dir, "userregister.txt");
NOTE :
If you are using Android 4.4 KitKat, Apps are not allowed to write to secondary external storage devices, except in their package-specific directories
The reason from http://source.android.com/devices/tech/storage/index.html
The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions. Restricting writes in this way ensures the system can clean up files when applications are uninstalled.

Categories