I'm trying to copy a file from assets folder to my app's internal files directory but it keeps throwing FileNotFoundException
j
ava.io.FileNotFoundException: android.content.res.AssetManager#f252431/wordsdb.ser: open failed: ENOENT (No such file or directory)
2020-04-05 19:44:48.829 11247-11247/stickyapps.zabanamooz W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2020-04-05 19:44:48.829 11247-11247/stickyapps.zabanamooz W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:159)
2020-04-05 19:44:48.829 11247-11247/stickyapps.zabanamooz W/System.err: at stickyapps.zabanamooz.Managers.WordsManager.copy(WordsManager.java:91)
2020-04-05 19:44:48.830 11247-11247/stickyapps.zabanamooz W/System.err: at stickyapps.zabanamooz.Managers.WordsManager.<init>(WordsManager.java:46)
2020-04-05 19:44:48.830 11247-11247/stickyapps.zabanamooz W/System.err: at stickyapps.zabanamooz.MainActivity.onCreate(MainActivity.java:40)
2020-04-05 19:44:48.830 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.Activity.performCreate(Activity.java:7802)
2020-04-05 19:44:48.830 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.Activity.performCreate(Activity.java:7791)
2020-04-05 19:44:48.830 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
2020-04-05 19:44:48.831 11247-11247/stickyapps.zabanamooz W/System.err: at android.os.Handler.dispatchMessage(Handler.java:107)
2020-04-05 19:44:48.832 11247-11247/stickyapps.zabanamooz W/System.err: at android.os.Looper.loop(Looper.java:214)
2020-04-05 19:44:48.832 11247-11247/stickyapps.zabanamooz W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356)
2020-04-05 19:44:48.832 11247-11247/stickyapps.zabanamooz W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2020-04-05 19:44:48.832 11247-11247/stickyapps.zabanamooz W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2020-04-05 19:44:48.833 11247-11247/stickyapps.zabanamooz W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-04-05 19:44:48.836 11247-11247/stickyapps.zabanamooz W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
2020-04-05 19:44:48.836 11247-11247/stickyapps.zabanamooz W/System.err: at libcore.io.Linux.open(Native Method)
...
I'm using this code:
File file1 = new File(context.getAssets() + "/wordsdb.ser");
File file2 = new File(context.getFilesDir() + "/wordsdb.ser");
try {
copy(file1,file2);
} catch (IOException e) {
e.printStackTrace();
}
copy method:
public void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
I tried restarting android studio, rebuilding project, reinstalling app and ...
but still no luck.
Try using asset manager
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
This to open a certian file:
InputStream input = assetManager.open(assetName);
Related
I can successfully send notifications from the Firebase console to my device, but when I try to do it from Java code, I get a very unhelpful error:
04-12 20:18:09.284 17549-17549/com.package.example W/System.err: at com.package.example.FCMNotification.pushFCMNotification(FCMNotification.java:102)
Here is my FCMNotification Class
public class FCMNotification {
public final static String AUTH_KEY_FCM = "FCM_SERVERKEY";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static void pushFCMNotification(String deviceToken, String title, String body)
throws IOException, JSONException {
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to",deviceToken.trim());
JSONObject info = new JSONObject();
info.put("title", title); // Notification title
info.put("body", body); // Notification body
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}
}
And I call this class in my activity like this
FCMNotification obj = new FCMNotification();
obj.pushFCMNotification("DEVICE_TOKEN", "TITLE", "BODY");
EDIT
My app might be having trouble connecting to firebase server itself, so I have included my manifest and Gradle:
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.package.example">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/globalicon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/cardview_shadow_start_color" />
<service android:name="com.package.example.PushNotification"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name="com.package.example.FCMService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
Gradle:
apply plugin: 'com.android.application'
android {
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/io.netty.versions.properties'
exclude 'META-INF/INDEX.LIST'
}
signingConfigs {
config {
}
}
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
multiDexEnabled true
applicationId "com.gespanet.global"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 29
versionName "1.2"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
disable 'MissingTranslation'
disable 'ExtraTranslation'
}
dexOptions {
javaMaxHeapSize "4g"
}
repositories {
mavenCentral()
}
dependencies {
compile ('com.google.apis:google-api-services-translate:v2-rev49-1.22.0') {
exclude group: 'com.google.guava'
}
compile ('com.google.cloud:google-cloud-translate:0.11.0-alpha') {
exclude group: 'io.grpc', module: 'grpc-all'
exclude group: 'com.google.protobuf', module: 'protobuf-java'
exclude group: 'com.google.api-client', module: 'google-api-client-appengine'
}
compile 'com.google.android.gms:play-services:10.2.1'
compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-messaging:10.2.0'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.parse.bolts:bolts-tasks:1.3.0'
compile 'com.parse:parse-android:1.13.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.facebook.android:facebook-android-sdk:4.+'
}
configurations.all {
exclude group: 'org.json', module: 'json'
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
apply plugin: 'com.google.gms.google-services'
FULL ERROR LOG CAT FROM TRY/CATCHEXCEPTION:
04-12 23:31:56.027 12815-12815/com.gespanet.global W/System.err: android.os.NetworkOnMainThreadException
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:500)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:483)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.FCMNotification.pushFCMNotification(FCMNotification.java:52)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6397)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6389)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.Looper.loop(Looper.java:148)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7223)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: java.lang.NullPointerException: Attempt to invoke interface method 'void com.android.okhttp.internal.http.Transport.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:971)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:482)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.FCMNotification.pushFCMNotification(FCMNotification.java:64)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6397)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6389)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.os.Looper.loop(Looper.java:148)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7223)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-12 23:31:56.037 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-12 23:31:56.037 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: Hongbao
04-12 23:31:56.037 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:31:56.037 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: Hongbao
04-12 23:31:56.037 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:31:56.047 12815-12815/com.gespanet.global I/push: Error is here
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: android.os.NetworkOnMainThreadException
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:500)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:483)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.FCMNotification.pushFCMNotification(FCMNotification.java:52)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6397)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6389)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.Looper.loop(Looper.java:148)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7223)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: java.lang.NullPointerException: Attempt to invoke interface method 'void com.android.okhttp.internal.http.Transport.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:971)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:482)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.FCMNotification.pushFCMNotification(FCMNotification.java:64)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6397)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$2$1.done(IndividualFeed.java:6389)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.os.Looper.loop(Looper.java:148)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7223)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-12 23:31:56.047 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-12 23:31:56.067 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: Hongbao
04-12 23:31:56.067 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:31:56.067 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: Hongbao
04-12 23:31:56.067 12815-12815/com.gespanet.global I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
04-12 23:31:56.067 12815-12815/com.gespanet.global I/push: Error is here
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: android.os.NetworkOnMainThreadException
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:500)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:483)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.FCMNotification.pushFCMNotification(FCMNotification.java:52)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$1$1.done(IndividualFeed.java:6366)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$1$1.done(IndividualFeed.java:6358)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.Looper.loop(Looper.java:148)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7223)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: java.lang.NullPointerException: Attempt to invoke interface method 'void com.android.okhttp.internal.http.Transport.writeRequestHeaders(com.android.okhttp.Request)' on a null object reference
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:971)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:482)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.FCMNotification.pushFCMNotification(FCMNotification.java:64)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$1$1.done(IndividualFeed.java:6366)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.gespanet.global.IndividualFeed$214$1$1$3$1$1$1.done(IndividualFeed.java:6358)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.os.Looper.loop(Looper.java:148)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7223)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
04-12 23:31:56.067 12815-12815/com.gespanet.global W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
To Send a Notification with Java. Implement this class:
public class FCMNotification {
// Method to send Notifications from server to client end.
public final static String AUTH_KEY_FCM = "YOUR_SERVERKEY";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static void pushFCMNotification(final String DeviceIdKey, final String title, final String body) throws Exception {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
BufferedReader in = null;
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = null;
try {
url = new URL(FMCurl);
} catch (MalformedURLException e) {
Log.i("yoyoyo", "error: 1");
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
Log.i("yoyoyo", "error: 2");
e.printStackTrace();
}
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
Log.i("yoyoyo", "error: 3");
e.printStackTrace();
}
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
try {
json.put("to",DeviceIdKey.trim());
} catch (JSONException e) {
Log.i("yoyoyo", "error: 4");
e.printStackTrace();
}
JSONObject info = new JSONObject();
try {
info.put("title", title); // Notification title
} catch (JSONException e) {
Log.i("yoyoyo", "error: 5");
e.printStackTrace();
}
try {
info.put("body", body); // Notification body
} catch (JSONException e) {
Log.i("yoyoyo", "error: 6");
e.printStackTrace();
}
try {
json.put("notification", info);
} catch (JSONException e) {
Log.i("yoyoyo", "error: 7");
e.printStackTrace();
}
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
} catch (IOException e) {
Log.i("yoyoyo", "error: 8");
e.printStackTrace();
}
try {
wr.write(json.toString());
} catch (IOException e) {
Log.i("yoyoyo", "error: 9");
e.printStackTrace();
}
try {
wr.flush();
} catch (IOException e) {
Log.i("yoyoyo", "error: 10");
e.printStackTrace();
}
try {
conn.getInputStream();
} catch (IOException e) {
Log.i("yoyoyo", "error: 11");
e.printStackTrace();
}
return null;
}
};
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
So I've been tasked with creating an android app which will be using web services frequently.
I'm new to android and java but I cant see why this isn't working. Can someone help out? At this point all I'm trying to do is log the html code of a website, in this case Google.
MainActivity.java
package com.dummies.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import com.dummies.myapplication.WebService;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String contents = WebService.getContents("http://www.google.com", "utf-8");
Log.d("Jon", contents);
setContentView(R.layout.activity_main);
}
public void invokeWS(){
}
}
WebService.java
package com.dummies.myapplication;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
class WebService {
public static String getContents(String url, String encodeType) {
URL u;
StringBuilder builder = new StringBuilder();
try {
u = new URL(url);
try {
BufferedReader theHTML = new BufferedReader(new InputStreamReader(u.openStream(), encodeType));
String thisLine;
while ((thisLine = theHTML.readLine()) != null) {
builder.append(thisLine).append("\n");
}
} catch (Exception e) {
Log.d("Jon", "Error 2");
}
} catch (MalformedURLException e) {
Log.d("Jon", "Error");
System.err.println(url + " is not a parseable URL");
System.err.println(e);
}
return builder.toString();
}
}
I keep getting the Error 2 coming up in the log, why is this? can someone help get this code working and logging the output.
Thanks!
Stack:
02-03 23:41:56.261 2297-2297/com.dummies.myapplication D/Jon: Stack Trace:
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: android.os.NetworkOnMainThreadException
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:752)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
02-03 23:41:56.262 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at java.net.URL.openStream(URL.java:1057)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.dummies.myapplication.WebService.getContents(WebService.java:22)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.dummies.myapplication.MainActivity.onCreate(MainActivity.java:23)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.Activity.performCreate(Activity.java:6662)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.os.Looper.loop(Looper.java:154)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
02-03 23:41:56.263 2297-2297/com.dummies.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
02-03 23:41:56.527 1278-1484/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
[ 02-03 23:41:56.529 2297: 2297 D/ ]
HostConnection::get() New Host Connection established 0xa4a93200, tid 2297
[ 02-03 23:41:56.530 2297: 2297 W/ ]
Process pipe failed
02-03 23:41:56.556 1278-1318/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
[ 02-03 23:41:56.557 2297: 2413 D/ ]
HostConnection::get() New Host Connection established 0xa4a93600, tid 2413
02-03 23:41:56.563 2297-2413/com.dummies.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
02-03 23:41:56.563 2297-2413/com.dummies.myapplication D/OpenGLRenderer: Swap behavior 1
02-03 23:41:56.564 1278-1318/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
02-03 23:41:56.572 1278-1318/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
02-03 23:41:56.594 2297-2413/com.dummies.myapplication E/EGL_emulation: tid 2413: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
02-03 23:41:56.594 2297-2413/com.dummies.myapplication W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x98224160, error=EGL_BAD_MATCH
02-03 23:41:56.603 2271-2271/com.google.android.googlequicksearchbox:search W/art: Long monitor contention with owner Binder:2271_1 (2283) at void java.lang.Object.wait!()(Object.java:-2) waiters=0 in java.lang.Object a.a.c.get() for 470ms
02-03 23:41:56.641 1569-1592/system_process I/ActivityManager: Displayed com.dummies.myapplication/.MainActivity: +6s119ms
02-03 23:41:56.655 1569-1693/system_process I/WindowManager: Destroying surface Surface(name=com.android.launcher3/com.android.launcher3.Launcher) called by com.android.server.wm.WindowStateAnimator.destroySurface:2014 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:881 com.android.server.wm.WindowState.destroyOrSaveSurface:2073 com.android.server.wm.AppWindowToken.destroySurfaces:363 com.android.server.wm.AppWindowToken.notifyAppStopped:389 com.android.server.wm.WindowManagerService.notifyAppStopped:4456 com.android.server.am.ActivityStack.activityStoppedLocked:1252 com.android.server.am.ActivityManagerService.activityStopped:6895
02-03 23:41:56.669 2271-2414/com.google.android.googlequicksearchbox:search W/ModelDownloadController: Cannot find any speech config location.
The problem is that Android doesn't allow you to execute Network Operations on the same Thread where UIOperations happen.
In order to connect to a network, you must create a different Thread using AsyncTasks or Services.
Here's a more detailed answer about Networks on Android: How to fix android.os.NetworkOnMainThreadException?
Maybe You should use Jsoup Library. It is super cool. You can find more information here.
https://jsoup.org/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Button mBtn1 = (Button) findViewById(R.id.start_Quit_button);
mBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks", "You Clicked B1");
Intent i = new Intent(
StartActivity.this,
MainActivity.class);
startActivity(i);
}
});
Button mBtn2 = (Button) findViewById(R.id.start_Next_button);
mBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks", "You Clicked B2");
TextView username = (TextView) findViewById(R.id.login_text);
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ExperimentLog");
if (!root.exists()) {
root.mkdir();
}
Username = username.getText().toString();
save(root, Username);
Intent i = new Intent(
StartActivity.this,
Test1_0.class);
startActivity(i);
}
});
}
public void save(File dir, String string) {
try {
File filepath = new File(dir, Username + ".txt");
FileWriter writer = new FileWriter(filepath);
writer.append(string);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the code I have. As you can see that i want the second button to go to the next activity and save the text I get from the editText start_Next_button. And a save method to write the string into the file created.
But the when I press the button on the AVD, android studio shows this:
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: java.io.FileNotFoundException: /sdcard/ExperimentLog/Name.txt: open failed: ENOENT (No such file or directory)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at libcore.io.IoBridge.open(IoBridge.java:452)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at java.io.FileWriter.<init>(FileWriter.java:42)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at com.android.mick.encodingaidingexperiment.StartActivity.save(StartActivity.java:74)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at com.android.mick.encodingaidingexperiment.StartActivity$2.onClick(StartActivity.java:61)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at android.view.View.performClick(View.java:5198)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at android.view.View$PerformClick.run(View.java:21147)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at android.os.Looper.loop(Looper.java:148)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at libcore.io.Posix.open(Native Method)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: at libcore.io.IoBridge.open(IoBridge.java:438)
04-28 10:09:44.242 2379-2379/com.android.mick.encodingaidingexperiment W/System.err: ... 14 more
BTW I use AVD galaxy Nexus running android 6.0
Try adding a / after ExperimentLog and then mkdir() or mkdirs().
first of all the exception is about file is not exist, so you need create that folder and file if it doesn't exist on your directory.
you need a try catch block to handle FileNotFoundException.
and also you can use Files.createFile(thePath); to create file if not exist.
Just try this
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ExperimentLog"+".txt");
instead of
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ExperimentLog");
For some reason I am getting a fileNotFoundException for both the times I read. Something worth noting is that the Toast prints "File exists!". I used the BufferedReader at the bottom to test if the content of the file is correct.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
recipes = new ArrayMap<>();
filename = "calendar_recipes.txt";
bText= (EditText) v.findViewById(R.id.bEditText);
lText= (EditText) v.findViewById(R.id.lEditText);
dText= (EditText) v.findViewById(R.id.dEditText);
cal = (CalendarView) v.findViewById(R.id.calendarView);
date = cal.getDate();
File file = getActivity().getFileStreamPath(filename);
if(file.exists())
{
Toast.makeText(getActivity(), "File exists!", Toast.LENGTH_SHORT).show();
try
{
FileInputStream fileInputStream = new FileInputStream(getActivity().getFilesDir()+filename);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map recipes = (Map)objectInputStream.readObject();
}
catch(ClassNotFoundException | IOException | ClassCastException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getActivity(), "File does not exist!!", Toast.LENGTH_SHORT).show();
file = new File(getActivity().getFilesDir(), filename);
}
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
Logcat...
03-24 23:54:57.626 14059-14067/com.stringcheese.recipez.recip_ez W/art: Suspending all threads took: 7.202ms
03-24 23:54:58.409 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: java.io.FileNotFoundException: /data/data/com.stringcheese.recipez.recip_ez/filescalendar_recipes.txt: open failed: ENOENT (No such file or directory)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at libcore.io.IoBridge.open(IoBridge.java:456)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:76)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:103)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at com.stringcheese.recipez.recip_ez.CalendarFragment.onCreateView(CalendarFragment.java:80)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1259)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.Activity.performStart(Activity.java:6026)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:155)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.os.Looper.loop(Looper.java:135)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5343)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-24 23:54:58.410 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at libcore.io.Posix.open(Native Method)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
03-24 23:54:58.411 14059-14059/com.stringcheese.recipez.recip_ez W/System.err: ... 23 more
getFilesDir returns a File object. If you call onString on it (which you do implicitly), it returns its path. The path is not ending with a slash if the file is a directory, so getActivity().getFilesDir()+filename will result in something like "/data/data/com.yourapp/filescalendar_recipes.txt".
You can either use getActivity().getFilesDir()+File.separator+filename, or just call new FileInputStream(file).
I was Getting the same error.
This Answer worked for me.
You just have to add one line in your manifest like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:requestLegacyExternalStorage="true" //Add this Line
android:label="#string/app_name">
-------------------
You have already created a File instance with File file = getActivity().getFileStreamPath(filename); which is the instance that you are checking with the file.exists() method. Then you are trying to read another thing with the FileInputStream. You should try FileInputStream fileInputStream = new FileInputStream(file);. With that you are creating your stream with the file that you already checked.
Newer version of android sometimes don't support creating folders ( very strange for me, but I experienced it), then :-
1- be sure that folder is created and or/
2- add this to mainfests
<application android:requestLegacyExternalStorage="true" tools:targetApi="q">
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
I have button which function is to take screenshot and share it to Facebook. when i try it in my Samsung with JellyBean OS device its working perfectly, but when i try it to BlueStack with JellyBean OS and CheeryMobile with Lollipop OS things are not working, i check the Logcat and i see some error.
my code
onClick of Button call takeScreenshot();
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
sharePhotoToFacebook(imageFile);
} catch (Throwable
e.printStackTrace();
}
}
private void sharePhotoToFacebook(File imageFile){
Uri imageUri = Uri.fromFile(imageFile);
try {
image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
//this loginManager helps you eliminate adding a LoginButton to your UI
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try{
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption(scoreFinal)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
final Dialog dialog = new Dialog(ActivityShare.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.sucess_shared);
dialog.show();
Button btnOk = (Button) dialog.findViewById(R.id.btnOk);
btnOk.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}catch (Exception e){
Log.e("Error on share", String.valueOf(e));
}
}
#Override
public void onCancel() {
Log.w("OnCancel", "Canceled by user");
// System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
final Dialog dialog = new Dialog(ActivityShare.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.sucess_shared);
TextView title = (TextView)dialog.findViewById(R.id.titleSuccess);
TextView desc = (TextView)dialog.findViewById(R.id.descriptionHere);
title.setText("Unsuccessfull");
desc.setText("Something's wrong, Please check your internet connection and try again.");
dialog.show();
Button btnOk = (Button) dialog.findViewById(R.id.btnOk);
btnOk.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Log.e("OnError", String.valueOf(exception));
// System.out.println("onError");
}
});
}
LogCat Error
01-07 23:34:36.767 2024-2024/com.sample.app W/System.err: java.io.FileNotFoundException: /mnt/sdcard/Thu Jan 07 23:34:36 SGT 2016.jpg: open failed: EINVAL (Invalid argument)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.IoBridge.open(IoBridge.java:406)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.sample.app.ActivityShare.takeScreenshot(ActivityShare.java:225)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.sample.app.ActivityShare.access$000(ActivityShare.java:42)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.sample.app.ActivityShare$1.onClick(ActivityShare.java:103)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.view.View.performClick(View.java:3511)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.view.View$PerformClick.run(View.java:14105)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.os.Handler.handleCallback(Handler.java:605)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.os.Looper.loop(Looper.java:137)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at android.app.ActivityThread.main(ActivityThread.java:4424)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at dalvik.system.NativeStart.main(Native Method)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: Caused by: libcore.io.ErrnoException: open failed: EINVAL (Invalid argument)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.Posix.open(Native Method)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: at libcore.io.IoBridge.open(IoBridge.java:390)
01-07 23:34:36.787 2024-2024/com.sample.app W/System.err: ... 16 more
i have no idea about the problem.
Please help me. Thank you!!!