The Android Studio keep telling me that cannot find the file - java

#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");

Related

FileNotFoundException on accessing assets files

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);

Android Studio - How do I retrieve the contents of a web page?

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/

NullPointerException while storing value of spinner in a string array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to create a fill in the blanks game. I have given the options to choose from in a spinner dropdown (10 spinner for 10 blanks). Till now its working. But to calculate score, I want to store the selected options in a string array. Here I am getting a NullPointerException.
package com.example.harimohan.myapplication;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class StartPage extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView substring1;
TextView substring2;
TextView substring3;
TextView substring4;
TextView substring5;
TextView substring6;
TextView substring7;
TextView substring8;
TextView substring9;
TextView substring10;
TextView substring11;
Spinner blank1 ;
Spinner blank2 ;
Spinner blank3 ;
Spinner blank4 ;
Spinner blank5 ;
Spinner blank6 ;
Spinner blank7 ;
Spinner blank8 ;
Spinner blank9 ;
Spinner blank10;
String[] subs = new String[20] ;
String[] words = "batsmen domestically scored ranked appearances previously outstanding announced recipient aviation".split(" ");
String[] ans = new String[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
blank1 = (Spinner) findViewById(R.id.Blank1);
Spinner blank2 = (Spinner) findViewById(R.id.Blank2);
Spinner blank3 = (Spinner) findViewById(R.id.Blank3);
Spinner blank4 = (Spinner) findViewById(R.id.Blank4);
Spinner blank5 = (Spinner) findViewById(R.id.Blank5);
Spinner blank6 = (Spinner) findViewById(R.id.Blank6);
Spinner blank7 = (Spinner) findViewById(R.id.Blank7);
Spinner blank8 = (Spinner) findViewById(R.id.Blank8);
Spinner blank9 = (Spinner) findViewById(R.id.Blank9);
Spinner blank10 = (Spinner) findViewById(R.id.Blank10);
blank1.setOnItemSelectedListener(this );
blank2.setOnItemSelectedListener( this);
blank3.setOnItemSelectedListener( this);
blank4.setOnItemSelectedListener( this);
blank5.setOnItemSelectedListener( this);
blank6.setOnItemSelectedListener( this);
blank7.setOnItemSelectedListener( this);
blank8.setOnItemSelectedListener( this);
blank9.setOnItemSelectedListener( this);
blank10.setOnItemSelectedListener( this);
substring1 = (TextView) findViewById(R.id.subs1);
substring2 = (TextView) findViewById(R.id.subs2);
substring3 = (TextView) findViewById(R.id.subs3);
substring4 = (TextView) findViewById(R.id.subs4);
substring5 = (TextView) findViewById(R.id.subs5);
substring6 = (TextView) findViewById(R.id.subs6);
substring7 = (TextView) findViewById(R.id.subs7);
substring8 = (TextView) findViewById(R.id.subs8);
substring9 = (TextView) findViewById(R.id.subs9);
substring10= (TextView) findViewById(R.id.subs10);
substring11= (TextView) findViewById(R.id.subs11);
new jsontask(). execute("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&explaintext=&titles=Sachin_Tendulkar&formatversion=2&format=json");
List<String> categories = new ArrayList<String>();
categories.add("Select Answer");
categories.add(words[8]);
categories.add(words[1]);
categories.add(words[4]);
categories.add(words[3]);
categories.add(words[7]);
categories.add(words[5]);
categories.add(words[6]);
categories.add(words[0]);
categories.add(words[2]);
categories.add(words[9]);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
blank1.setAdapter(dataAdapter);
blank2.setAdapter(dataAdapter);
blank3.setAdapter(dataAdapter);
blank4.setAdapter(dataAdapter);
blank5.setAdapter(dataAdapter);
blank6.setAdapter(dataAdapter);
blank7.setAdapter(dataAdapter);
blank8.setAdapter(dataAdapter);
blank9.setAdapter(dataAdapter);
blank10.setAdapter(dataAdapter);
/*ans[0] = blank1.getSelectedItem().toString();
ans[1] = blank2.getSelectedItem().toString();
ans[2] = blank3.getSelectedItem().toString();
ans[3]= blank4.getSelectedItem().toString();
ans[4] = blank5.getSelectedItem().toString();
ans[5] = blank6.getSelectedItem().toString();
ans[6] = blank7.getSelectedItem().toString();
ans[7] = blank8.getSelectedItem().toString();
ans[8] = blank9.getSelectedItem().toString();
ans[9] = blank10.getSelectedItem().toString();*/
}
public int Score( String[] WordString, String[] AnsString){
for (int j=0;j<AnsString.length;j++) {
Log.d("Ans: " ,j +" : "+ AnsString[j]);
}
int scores=0;
for (int i=0;i<WordString.length;i++){
if (WordString[i].contains(AnsString[i])) {
scores++;
}
}
Log.d("scores",Integer.toString(scores));
return scores;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
try{
Spinner spinner = (Spinner) parent;
Log.d("spinner=",Integer.toString(spinner.getId()));
Log.d("R.id.Blank1=",Integer.toString(R.id.Blank1));
Log.d("Blank1 value=",blank1.getSelectedItem().toString());
/*if(spinner.getId() == R.id.Blank1)
{*/
String ans = blank1.getSelectedItem().toString();
Log.d("ans0 ",ans);
/*}
else if(spinner.getId() == R.id.Blank2)
{
ans[1] = blank2.getSelectedItem().toString();
Log.d("ans1 ",ans[1]);
}*/
}catch (Exception exception)
{
exception.printStackTrace();
}
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item +" at "+position+""+id, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
public class jsontask extends AsyncTask<String, String, String[]> {
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ;
while ((line=reader.readLine())!= null) {
buffer.append(line);
}
String json = buffer.toString();
JSONObject parentObj = new JSONObject(json);
JSONObject query = parentObj.getJSONObject("query");
JSONArray pages = query.getJSONArray("pages");
JSONObject pagearray = pages.getJSONObject(0);
String extract = pagearray.getString("extract");
int lines = 0;
int pos = 0;
String print = null;
int x;
while ((pos = extract.indexOf(".", pos) + 1) != 0) {
lines++;
if(lines==10){
x= extract.indexOf("\n",pos);
print = extract.substring(0,x);
break;
}
}
String[] sentence = print.split(" ");
for (int j = 0 ; j < words.length;j++){
boolean flag= false;
for (int i = 0; i < sentence.length ; i++) {
if (sentence[i].equals(words[j])) {
/* System.out.println(words[j]+" is found at "+ i);
System.out.println("size of "+words[j]+"="+words[j].length());
*/
if (j==0){
System.out.println("end "+print.indexOf(words[j]));
System.out.println(print.substring(0,i));
subs[j]= print.substring(0,print.indexOf(words[j]));
System.out.println(print.indexOf(words[j]));
}
else{
int start = print.indexOf(words[j-1])+ words[j-1].length();
/*System.out.println(print.indexOf(words[j-1])+"+" +words[j-1].length());
System.out.println("start"+start);
System.out.println("end"+print.indexOf(words[j]));*/
subs[j]= print.substring(start,print.indexOf(words[j]));
if(j==9){
int n =print.indexOf(words[j])+ words[j].length();
subs[10]=print.substring(n);
}
}
flag= true;
break;
}
}
if (!flag ){
System.out.println("doesnt found");
}
}
return subs;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e3) {
e3.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
substring1.setText(subs[0]);
substring2.setText(subs[1]);
substring3.setText(subs[2]);
substring4.setText(subs[3]);
substring5.setText(subs[4]);
substring6.setText(subs[5]);
substring7.setText(subs[6]);
substring8.setText(subs[7]);
substring9.setText(subs[8]);
substring10.setText(subs[9]);
substring11.setText(subs[10]);
}
}
public void gotoScorePage(View view){
Score(words,ans);
Intent nextPage=new Intent(StartPage.this,ScorePage.class);
nextPage.putExtra("Score",Score(words,ans));
startActivity(nextPage);
}
}
This is logcat
07-13 12:33:18.360 19760-19760/com.example.harimohan.myapplication D/dalvikvm: VFY: replacing opcode 0x20 at 0x0016
07-13 12:33:18.810 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492976
07-13 12:33:18.810 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.810 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.810 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.810 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.820 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.820 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.820 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.820 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.830 19760-19760/com.example.harimohan.myapplication W/System.err: at dalvik.system.NativeStart.main(Native Method)
07-13 12:33:18.840 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492978
07-13 12:33:18.840 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.850 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.850 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at dalvik.system.NativeStart.main(Native Method)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492980
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.860 19760-19760/com.example.harimohan.myapplication W/System.err: at dalvik.system.NativeStart.main(Native Method)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492982
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.880 19760-19760/com.example.harimohan.myapplication W/System.err: at dalvik.system.NativeStart.main(Native Method)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492984
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at dalvik.system.NativeStart.main(Native Method)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492986
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.890 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at dalvik.system.NativeStart.main(Native Method)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication D/spinner=: 2131492988
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication D/R.id.Blank1=: 2131492976
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: java.lang.NullPointerException
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView.access$200(AdapterView.java:48)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.os.Looper.loop(Looper.java:136)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5017)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-13 12:33:18.900 19760-19760/com.example.harimohan.myapplication
there is :
at com.example.harimohan.myapplication.StartPage.onItemSelected(StartPage.java:174)
in line 174 you have choose and null value
maybe you should initilize blank1 in on create method .
You can try to check the where the null is in line 174 (the blank1.getSelectedItem() return the null value). It's helpful for you to solve the problem . Please forgive my English is poor.

java.io.FileNotFoundException, open failed: ENOENT

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();
}
}

Android - Programmatically Screenshot and Share to Facebook

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!!!

Categories